blob: bb23bc0e2414ab48ef3f62564bffe459fb211330 [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 }
Santos Cordon9b510a22018-08-24 16:42:54 +0100718
719 WirelessChargerDetector createWirelessChargerDetector(
720 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
721 return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
722 }
723
724 AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
725 return new AmbientDisplayConfiguration(context);
726 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100727 }
728
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800729 final Constants mConstants;
730
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700731 private native void nativeInit();
Jeff Brown96307042012-07-27 15:51:34 -0700732 private static native void nativeAcquireSuspendBlocker(String name);
733 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700734 private static native void nativeSetInteractive(boolean enable);
735 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700736 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400737 private static native void nativeSetFeature(int featureId, int data);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000738 private static native boolean nativeForceSuspend();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739
Jeff Brownb880d882014-02-10 19:47:07 -0800740 public PowerManagerService(Context context) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100741 this(context, new Injector());
742 }
743
744 @VisibleForTesting
745 PowerManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800746 super(context);
Santos Cordon64a6e612018-08-22 19:27:04 +0100747
Jeff Brownb880d882014-02-10 19:47:07 -0800748 mContext = context;
Santos Cordon64a6e612018-08-22 19:27:04 +0100749 mBinderService = new BinderService();
750 mLocalService = new LocalService();
751 mNativeWrapper = injector.createNativeWrapper();
752 mInjector = injector;
753
Jeff Brown2c43c332014-06-12 22:38:59 -0700754 mHandlerThread = new ServiceThread(TAG,
755 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
756 mHandlerThread.start();
757 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800758 mConstants = new Constants(mHandler);
Santos Cordon9b510a22018-08-24 16:42:54 +0100759 mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800760 mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800761
Makoto Onukibd7a6252018-05-10 13:41:39 -0700762 mBatterySavingStats = new BatterySavingStats(mLock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100763 mBatterySaverPolicy =
764 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700765 mBatterySaverController = new BatterySaverController(mLock, mContext,
Santos Cordon64a6e612018-08-22 19:27:04 +0100766 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
767 mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700768 mBatterySaverStateMachine = new BatterySaverStateMachine(
769 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700770
Jeff Brown96307042012-07-27 15:51:34 -0700771 synchronized (mLock) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100772 mWakeLockSuspendBlocker =
773 mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
774 mDisplaySuspendBlocker =
775 mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
776 if (mDisplaySuspendBlocker != null) {
777 mDisplaySuspendBlocker.acquire();
778 mHoldingDisplaySuspendBlocker = true;
779 }
Jeff Brown037c33e2014-04-09 00:31:55 -0700780 mHalAutoSuspendModeEnabled = false;
781 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800782
Jeff Brown96307042012-07-27 15:51:34 -0700783 mWakefulness = WAKEFULNESS_AWAKE;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800784 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
785
Santos Cordon64a6e612018-08-22 19:27:04 +0100786 mNativeWrapper.nativeInit(this);
787 mNativeWrapper.nativeSetAutoSuspend(false);
788 mNativeWrapper.nativeSetInteractive(true);
789 mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700790 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800791 }
792
Jeff Brown6f357d32014-01-15 20:40:55 -0800793 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800794 public void onStart() {
Santos Cordon64a6e612018-08-22 19:27:04 +0100795 publishBinderService(Context.POWER_SERVICE, mBinderService);
796 publishLocalService(PowerManagerInternal.class, mLocalService);
Jeff Brown9e316a12012-10-08 19:17:06 -0700797
798 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800799 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700800 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800801
Jeff Brown6d2a9492014-08-07 19:06:49 -0700802 @Override
803 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700804 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600805 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
806 incrementBootCount();
807
808 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700809 final long now = SystemClock.uptimeMillis();
810 mBootCompleted = true;
811 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700812
813 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700814 userActivityNoUpdateLocked(
815 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
816 updatePowerStateLocked();
817 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700818 }
819 }
820
Jeff Brown21392762014-06-13 19:00:36 -0700821 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700822 synchronized (mLock) {
823 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700824 mAppOps = appOps;
825 mDreamManager = getLocalService(DreamManagerInternal.class);
826 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
827 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700828 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800829 mAttentionDetector.systemReady(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800830
Adam Lesinski182f73f2013-12-05 16:48:06 -0800831 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700832 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
833 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
834 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700836 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800837
Jeff Brownc38c9be2012-10-04 13:16:19 -0700838 // The notifier runs on the system server's main looper so as not to interfere
839 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700840 mBatteryStats = BatteryStatsService.getService();
Santos Cordon64a6e612018-08-22 19:27:04 +0100841 mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
842 mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
843 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700844
Santos Cordon9b510a22018-08-24 16:42:54 +0100845 mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
Santos Cordon64a6e612018-08-22 19:27:04 +0100846 mInjector.createSuspendBlocker(
847 this, "PowerManagerService.WirelessChargerDetector"),
Jeff Browndbcc8a22013-10-01 16:16:44 -0700848 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700849 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700850
851 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800852 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400853
Jeff Brown131206b2014-04-08 17:27:14 -0700854 // Initialize display power management.
855 mDisplayManagerInternal.initPowerManagement(
856 mDisplayPowerCallbacks, mHandler, sensorManager);
857
Pavel Grafov28939982017-10-03 15:11:52 +0100858 try {
859 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
860 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
861 } catch (RemoteException e) {
862 // Shouldn't happen since in-process.
863 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800864
Jeff Brown96307042012-07-27 15:51:34 -0700865 // Go.
866 readConfigurationLocked();
867 updateSettingsLocked();
868 mDirty |= DIRTY_BATTERY_STATE;
869 updatePowerStateLocked();
870 }
Shibin George43f5de02016-07-06 02:12:10 +0530871
Jeff Sharkey6e544612017-02-20 11:02:26 -0700872 final ContentResolver resolver = mContext.getContentResolver();
873 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800874
875 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -0700876 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -0700877
878 // Register for settings changes.
879 resolver.registerContentObserver(Settings.Secure.getUriFor(
880 Settings.Secure.SCREENSAVER_ENABLED),
881 false, mSettingsObserver, UserHandle.USER_ALL);
882 resolver.registerContentObserver(Settings.Secure.getUriFor(
883 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
884 false, mSettingsObserver, UserHandle.USER_ALL);
885 resolver.registerContentObserver(Settings.Secure.getUriFor(
886 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
887 false, mSettingsObserver, UserHandle.USER_ALL);
888 resolver.registerContentObserver(Settings.System.getUriFor(
889 Settings.System.SCREEN_OFF_TIMEOUT),
890 false, mSettingsObserver, UserHandle.USER_ALL);
891 resolver.registerContentObserver(Settings.Secure.getUriFor(
892 Settings.Secure.SLEEP_TIMEOUT),
893 false, mSettingsObserver, UserHandle.USER_ALL);
894 resolver.registerContentObserver(Settings.Global.getUriFor(
895 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
896 false, mSettingsObserver, UserHandle.USER_ALL);
897 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700898 Settings.System.SCREEN_BRIGHTNESS_MODE),
899 false, mSettingsObserver, UserHandle.USER_ALL);
900 resolver.registerContentObserver(Settings.System.getUriFor(
901 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
902 false, mSettingsObserver, UserHandle.USER_ALL);
903 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700904 Settings.Global.THEATER_MODE_ON),
905 false, mSettingsObserver, UserHandle.USER_ALL);
906 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100907 Settings.Secure.DOZE_ALWAYS_ON),
908 false, mSettingsObserver, UserHandle.USER_ALL);
909 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700910 Settings.Secure.DOUBLE_TAP_TO_WAKE),
911 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700912 resolver.registerContentObserver(Settings.Global.getUriFor(
913 Settings.Global.DEVICE_DEMO_MODE),
914 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Santos Cordon64a6e612018-08-22 19:27:04 +0100915 IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
Jeff Sharkey6e544612017-02-20 11:02:26 -0700916 if (vrManager != null) {
917 try {
918 vrManager.registerListener(mVrStateCallbacks);
919 } catch (RemoteException e) {
920 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
921 }
922 }
923
Shibin George43f5de02016-07-06 02:12:10 +0530924 // Register for broadcasts from other components of the system.
925 IntentFilter filter = new IntentFilter();
926 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
927 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
928 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
929
930 filter = new IntentFilter();
931 filter.addAction(Intent.ACTION_DREAMING_STARTED);
932 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
933 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
934
935 filter = new IntentFilter();
936 filter.addAction(Intent.ACTION_USER_SWITCHED);
937 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
938
939 filter = new IntentFilter();
940 filter.addAction(Intent.ACTION_DOCK_EVENT);
941 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700942 }
943
Santos Cordon9b510a22018-08-24 16:42:54 +0100944 @VisibleForTesting
945 void readConfigurationLocked() {
Jeff Brown96307042012-07-27 15:51:34 -0700946 final Resources resources = mContext.getResources();
947
Jeff Brown037c33e2014-04-09 00:31:55 -0700948 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800949 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700950 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800951 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700952 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700953 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700954 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
955 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700956 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
957 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700958 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400959 com.android.internal.R.bool.config_dreamsSupported);
960 mDreamsEnabledByDefaultConfig = resources.getBoolean(
961 com.android.internal.R.bool.config_dreamsEnabledByDefault);
962 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
963 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
964 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
965 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800966 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
967 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
968 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
969 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
970 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
971 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
972 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
973 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -0800974 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -0700975 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -0700976 mMinimumScreenOffTimeoutConfig = resources.getInteger(
977 com.android.internal.R.integer.config_minimumScreenOffTimeout);
978 mMaximumScreenDimDurationConfig = resources.getInteger(
979 com.android.internal.R.integer.config_maximumScreenDimDuration);
980 mMaximumScreenDimRatioConfig = resources.getFraction(
981 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400982 mSupportsDoubleTapWakeConfig = resources.getBoolean(
983 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800984 }
985
Jeff Brown96307042012-07-27 15:51:34 -0700986 private void updateSettingsLocked() {
987 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700988
Jeff Brownd4935962012-09-25 13:27:20 -0700989 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400990 Settings.Secure.SCREENSAVER_ENABLED,
991 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700992 UserHandle.USER_CURRENT) != 0);
993 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400994 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
995 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700996 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700997 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400998 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
999 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -07001000 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -07001001 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1002 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1003 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -07001004 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1005 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1006 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -07001007 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -07001008 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -07001009 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1010 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +01001011 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -07001012
Jason Monk27bbb2d2015-03-31 16:46:39 -04001013 if (mSupportsDoubleTapWakeConfig) {
1014 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1015 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1016 UserHandle.USER_CURRENT) != 0;
1017 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1018 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
Santos Cordon64a6e612018-08-22 19:27:04 +01001019 mNativeWrapper.nativeSetFeature(
1020 POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001021 }
1022 }
1023
Christine Franks732c0432017-06-23 18:12:46 -07001024 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1025 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
1026 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1027 }
1028
Jeff Brownd4935962012-09-25 13:27:20 -07001029 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -07001030 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -07001031 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -07001032
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001033 mDirty |= DIRTY_SETTINGS;
1034 }
1035
Jeff Brown96307042012-07-27 15:51:34 -07001036 private void handleSettingsChangedLocked() {
1037 updateSettingsLocked();
1038 updatePowerStateLocked();
1039 }
1040
Dianne Hackborn713df152013-05-17 11:27:57 -07001041 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001042 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001043 synchronized (mLock) {
1044 if (DEBUG_SPEW) {
1045 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1046 + ", flags=0x" + Integer.toHexString(flags)
1047 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001048 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049
Jeff Brown96307042012-07-27 15:51:34 -07001050 WakeLock wakeLock;
1051 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001052 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001053 if (index >= 0) {
1054 wakeLock = mWakeLocks.get(index);
1055 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1056 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001057 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1058 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001059 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001061 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001062 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001063 UidState state = mUidState.get(uid);
1064 if (state == null) {
1065 state = new UidState(uid);
1066 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1067 mUidState.put(uid, state);
1068 }
1069 state.mNumWakeLocks++;
1070 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1071 state);
Jeff Brown96307042012-07-27 15:51:34 -07001072 try {
1073 lock.linkToDeath(wakeLock, 0);
1074 } catch (RemoteException ex) {
1075 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
Jeff Brown96307042012-07-27 15:51:34 -07001077 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001078 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001079 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081
Jeff Brownc12035c2014-08-13 18:52:25 -07001082 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001083 mDirty |= DIRTY_WAKE_LOCKS;
1084 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001085 if (notifyAcquire) {
1086 // This needs to be done last so we are sure we have acquired the
1087 // kernel wake lock. Otherwise we have a race where the system may
1088 // go to sleep between the time we start the accounting in battery
1089 // stats and when we actually get around to telling the kernel to
1090 // stay awake.
1091 notifyWakeLockAcquiredLocked(wakeLock);
1092 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001093 }
1094 }
1095
Jeff Brownec083212013-09-11 20:45:25 -07001096 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001097 private static boolean isScreenLock(final WakeLock wakeLock) {
1098 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1099 case PowerManager.FULL_WAKE_LOCK:
1100 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1101 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1102 return true;
1103 }
1104 return false;
1105 }
1106
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001107 private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1108 if (workSource.getWorkChains() == null) {
1109 return null;
1110 }
1111
1112 for (WorkChain workChain: workSource.getWorkChains()) {
1113 if (workChain.getSize() > 0) {
1114 return workChain;
1115 }
1116 }
1117
1118 return null;
1119 }
1120
Jeff Brownc12035c2014-08-13 18:52:25 -07001121 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001122 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1123 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001124 String opPackageName;
1125 int opUid;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001126 if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1127 WorkSource workSource = wakeLock.mWorkSource;
1128 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1129 if (workChain != null) {
1130 opPackageName = workChain.getAttributionTag();
1131 opUid = workChain.getAttributionUid();
1132 } else {
1133 opPackageName = workSource.getName(0) != null
1134 ? workSource.getName(0) : wakeLock.mPackageName;
1135 opUid = workSource.get(0);
1136 }
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001137 } else {
1138 opPackageName = wakeLock.mPackageName;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001139 opUid = wakeLock.mOwnerUid;
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001140 }
Michael Wrighte3001042019-02-05 00:13:14 +00001141 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1142 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1143 opUid, opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 }
1145 }
1146
Jeff Brown96307042012-07-27 15:51:34 -07001147 private void releaseWakeLockInternal(IBinder lock, int flags) {
1148 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001149 int index = findWakeLockIndexLocked(lock);
1150 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001151 if (DEBUG_SPEW) {
1152 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1153 + " [not found], flags=0x" + Integer.toHexString(flags));
1154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 return;
1156 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001157
Jeff Brown96307042012-07-27 15:51:34 -07001158 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001159 if (DEBUG_SPEW) {
1160 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1161 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1162 }
1163
Michael Wright1208e272014-09-08 19:57:50 -07001164 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001165 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
1167
Jeff Brown3edf5272014-08-14 19:25:14 -07001168 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1169 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
1171 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001172
Jeff Brown96307042012-07-27 15:51:34 -07001173 private void handleWakeLockDeath(WakeLock wakeLock) {
1174 synchronized (mLock) {
1175 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001176 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1177 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001178 }
1179
1180 int index = mWakeLocks.indexOf(wakeLock);
1181 if (index < 0) {
1182 return;
1183 }
1184
Jeff Brown3edf5272014-08-14 19:25:14 -07001185 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001186 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001187 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001188
Jeff Brown3edf5272014-08-14 19:25:14 -07001189 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1190 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001191 UidState state = wakeLock.mUidState;
1192 state.mNumWakeLocks--;
1193 if (state.mNumWakeLocks <= 0 &&
1194 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1195 mUidState.remove(state.mUid);
1196 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001197 notifyWakeLockReleasedLocked(wakeLock);
1198
1199 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1200 mDirty |= DIRTY_WAKE_LOCKS;
1201 updatePowerStateLocked();
1202 }
1203
Jeff Brown96307042012-07-27 15:51:34 -07001204 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001205 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1206 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001207 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1208 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1209 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1210 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
1213
Dianne Hackbornd953c532014-08-16 18:17:38 -07001214 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1215 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001216 synchronized (mLock) {
1217 int index = findWakeLockIndexLocked(lock);
1218 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001219 if (DEBUG_SPEW) {
1220 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1221 + " [not found], ws=" + ws);
1222 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001223 throw new IllegalArgumentException("Wake lock not active: " + lock
1224 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001225 }
1226
1227 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001228 if (DEBUG_SPEW) {
1229 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1230 + " [" + wakeLock.mTag + "], ws=" + ws);
1231 }
1232
Jeff Brown96307042012-07-27 15:51:34 -07001233 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001234 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1235 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001236 ws, historyTag);
1237 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001238 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001239 }
1240 }
1241 }
1242
1243 private int findWakeLockIndexLocked(IBinder lock) {
1244 final int count = mWakeLocks.size();
1245 for (int i = 0; i < count; i++) {
1246 if (mWakeLocks.get(i).mLock == lock) {
1247 return i;
1248 }
1249 }
1250 return -1;
1251 }
1252
1253 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001254 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001255 wakeLock.mNotifiedAcquired = true;
1256 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001257 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1258 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001259 restartNofifyLongTimerLocked(wakeLock);
1260 }
1261 }
1262
1263 private void enqueueNotifyLongMsgLocked(long time) {
1264 mNotifyLongScheduled = time;
1265 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1266 msg.setAsynchronous(true);
1267 mHandler.sendMessageAtTime(msg, time);
1268 }
1269
1270 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1271 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1272 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1273 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1274 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1275 }
1276 }
1277
1278 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1279 if (mSystemReady && !wakeLock.mDisabled) {
1280 wakeLock.mNotifiedLong = true;
1281 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1282 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1283 }
1284 }
1285
1286 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1287 if (wakeLock.mNotifiedLong) {
1288 wakeLock.mNotifiedLong = false;
1289 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1290 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001291 }
1292 }
1293
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001294 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1295 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1296 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1297 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1298 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1299 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001300 notifyWakeLockLongFinishedLocked(wakeLock);
1301 // Changing the wake lock will count as releasing the old wake lock(s) and
1302 // acquiring the new ones... we do this because otherwise once a wakelock
1303 // becomes long, if we just continued to treat it as long we can get in to
1304 // situations where we spam battery stats with every following change to it.
1305 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001306 }
1307 }
1308
Jeff Brown96307042012-07-27 15:51:34 -07001309 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001310 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1311 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001312 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001313 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1314 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1315 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001316 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001317 }
1318 }
1319
Jeff Brownec083212013-09-11 20:45:25 -07001320 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001321 private boolean isWakeLockLevelSupportedInternal(int level) {
1322 synchronized (mLock) {
1323 switch (level) {
1324 case PowerManager.PARTIAL_WAKE_LOCK:
1325 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1326 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1327 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001328 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001329 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001330 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001331
1332 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001333 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001334
1335 default:
1336 return false;
1337 }
1338 }
1339 }
1340
Jeff Brown96307042012-07-27 15:51:34 -07001341 // Called from native code.
1342 private void userActivityFromNative(long eventTime, int event, int flags) {
1343 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1344 }
1345
1346 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1347 synchronized (mLock) {
1348 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1349 updatePowerStateLocked();
1350 }
1351 }
1352 }
1353
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001354 private void onUserAttention() {
1355 synchronized (mLock) {
1356 if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1357 PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1358 Process.SYSTEM_UID)) {
1359 updatePowerStateLocked();
1360 }
1361 }
1362 }
1363
Jeff Brown96307042012-07-27 15:51:34 -07001364 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1365 if (DEBUG_SPEW) {
1366 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1367 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1368 + ", uid=" + uid);
1369 }
1370
1371 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001372 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001373 return false;
1374 }
1375
Jeff Brown3edf5272014-08-14 19:25:14 -07001376 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1377 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001378 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001379 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001380 mLastInteractivePowerHintTime = eventTime;
1381 }
1382
Jeff Brown3edf5272014-08-14 19:25:14 -07001383 mNotifier.onUserActivity(event, uid);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001384 mAttentionDetector.onUserActivity(eventTime, event);
Jeff Brown96307042012-07-27 15:51:34 -07001385
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001386 if (mUserInactiveOverrideFromWindowManager) {
1387 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001388 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001389 }
1390
Jeff Brown0a571122014-08-21 21:50:43 -07001391 if (mWakefulness == WAKEFULNESS_ASLEEP
1392 || mWakefulness == WAKEFULNESS_DOZING
1393 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1394 return false;
1395 }
1396
Pavel Grafov28939982017-10-03 15:11:52 +01001397 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1398
Jeff Brown3edf5272014-08-14 19:25:14 -07001399 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1400 if (eventTime > mLastUserActivityTimeNoChangeLights
1401 && eventTime > mLastUserActivityTime) {
1402 mLastUserActivityTimeNoChangeLights = 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 }
1407
Jeff Brown3edf5272014-08-14 19:25:14 -07001408 return true;
1409 }
1410 } else {
1411 if (eventTime > mLastUserActivityTime) {
1412 mLastUserActivityTime = eventTime;
1413 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001414 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1415 mDirty |= DIRTY_QUIESCENT;
1416 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001417 return true;
1418 }
Jeff Brown96307042012-07-27 15:51:34 -07001419 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001420 } finally {
1421 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001422 }
1423 return false;
1424 }
1425
Pavel Grafov28939982017-10-03 15:11:52 +01001426 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1427 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1428 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1429 profile.mLastUserActivityTime = eventTime;
1430 }
1431 }
1432
Michael Wrighte3001042019-02-05 00:13:14 +00001433 private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1434 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001435 synchronized (mLock) {
Michael Wrighte3001042019-02-05 00:13:14 +00001436 if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001437 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001438 }
1439 }
Jeff Brown96307042012-07-27 15:51:34 -07001440 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001441
Michael Wrighte3001042019-02-05 00:13:14 +00001442 private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1443 int reasonUid, String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001444 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001445 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001446 }
Jeff Brown96307042012-07-27 15:51:34 -07001447
1448 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
Santos Cordon12f92eb2019-02-01 21:28:47 +00001449 || !mBootCompleted || !mSystemReady || mForceSuspendActive) {
Jeff Brown96307042012-07-27 15:51:34 -07001450 return false;
1451 }
1452
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001453 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1454
Jeff Brown3edf5272014-08-14 19:25:14 -07001455 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1456 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001457 Slog.i(TAG, "Waking up from "
1458 + PowerManagerInternal.wakefulnessToString(mWakefulness)
1459 + " (uid=" + reasonUid
1460 + ", reason=" + PowerManager.wakeReasonToString(reason)
1461 + ", details=" + details
1462 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001463
1464 mLastWakeTime = eventTime;
Michael Wrighte3001042019-02-05 00:13:14 +00001465 mLastWakeReason = reason;
1466 setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001467
Michael Wrighte3001042019-02-05 00:13:14 +00001468 mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001469 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001470 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001471 } finally {
1472 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001473 }
Jeff Brown96307042012-07-27 15:51:34 -07001474 return true;
1475 }
1476
Jeff Brownc12035c2014-08-13 18:52:25 -07001477 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001478 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001479 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001480 updatePowerStateLocked();
1481 }
1482 }
1483 }
1484
Santos Cordon12f92eb2019-02-01 21:28:47 +00001485 /**
1486 * Puts the system in doze.
1487 *
1488 * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1489 * and only tucks itself in to SLEEP if requested with the flag
1490 * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1491 */
Jeff Brownec083212013-09-11 20:45:25 -07001492 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001493 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001494 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001495 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001496 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001497 }
1498
Jeff Brown26875502014-01-30 21:47:47 -08001499 if (eventTime < mLastWakeTime
1500 || mWakefulness == WAKEFULNESS_ASLEEP
1501 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001502 || !mBootCompleted || !mSystemReady) {
1503 return false;
1504 }
1505
Jeff Brown3edf5272014-08-14 19:25:14 -07001506 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1507 try {
Santos Cordon12f92eb2019-02-01 21:28:47 +00001508 reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1509 Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1510 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1511 + " (uid " + uid + ")...");
Jeff Brown6d8fd272014-05-20 21:24:38 -07001512
Jeff Brown3edf5272014-08-14 19:25:14 -07001513 mLastSleepTime = eventTime;
Calin Tatarua3805722018-08-09 16:41:28 +02001514 mLastSleepReason = reason;
Jeff Brown3edf5272014-08-14 19:25:14 -07001515 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001516 setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001517
1518 // Report the number of wake locks that will be cleared by going to sleep.
1519 int numWakeLocksCleared = 0;
1520 final int numWakeLocks = mWakeLocks.size();
1521 for (int i = 0; i < numWakeLocks; i++) {
1522 final WakeLock wakeLock = mWakeLocks.get(i);
1523 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1524 case PowerManager.FULL_WAKE_LOCK:
1525 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1526 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1527 numWakeLocksCleared += 1;
1528 break;
1529 }
1530 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001531 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001532
1533 // Skip dozing if requested.
1534 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1535 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1536 }
1537 } finally {
1538 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001539 }
Jeff Brown96307042012-07-27 15:51:34 -07001540 return true;
1541 }
1542
Jeff Brownc12035c2014-08-13 18:52:25 -07001543 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001544 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001545 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001546 updatePowerStateLocked();
1547 }
1548 }
1549 }
1550
Jeff Brownc12035c2014-08-13 18:52:25 -07001551 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001552 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001553 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001554 }
1555
1556 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1557 || !mBootCompleted || !mSystemReady) {
1558 return false;
1559 }
1560
Jeff Brown3edf5272014-08-14 19:25:14 -07001561 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1562 try {
1563 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001564
Jeff Brown3edf5272014-08-14 19:25:14 -07001565 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001566 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001567 } finally {
1568 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1569 }
Jeff Brown26875502014-01-30 21:47:47 -08001570 return true;
1571 }
1572
1573 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001574 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001575 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001576 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1577 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001578 }
1579
1580 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1581 || !mBootCompleted || !mSystemReady) {
1582 return false;
1583 }
1584
Jeff Brown3edf5272014-08-14 19:25:14 -07001585 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1586 try {
1587 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001588
Michael Wrighte3001042019-02-05 00:13:14 +00001589 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1590 eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001591 } finally {
1592 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1593 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001594 return true;
1595 }
1596
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001597 @VisibleForTesting
Michael Wrighte3001042019-02-05 00:13:14 +00001598 void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001599 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001600 mWakefulness = wakefulness;
1601 mWakefulnessChanging = true;
1602 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001603 if (mNotifier != null) {
Michael Wrighte3001042019-02-05 00:13:14 +00001604 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001605 }
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001606 mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
Jeff Brown037c33e2014-04-09 00:31:55 -07001607 }
1608 }
1609
Santos Cordon64a6e612018-08-22 19:27:04 +01001610 @VisibleForTesting
1611 int getWakefulness() {
1612 return mWakefulness;
1613 }
1614
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001615 /**
1616 * Logs the time the device would have spent awake before user activity timeout,
1617 * had the system not been told the user was inactive.
1618 */
1619 private void logSleepTimeoutRecapturedLocked() {
1620 final long now = SystemClock.uptimeMillis();
1621 final long savedWakeTimeMs = mOverriddenTimeout - now;
1622 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001623 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001624 mOverriddenTimeout = -1;
1625 }
1626 }
1627
Jeff Brown416c49c2015-05-26 19:50:18 -07001628 private void finishWakefulnessChangeIfNeededLocked() {
1629 if (mWakefulnessChanging && mDisplayReady) {
1630 if (mWakefulness == WAKEFULNESS_DOZING
1631 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1632 return; // wait until dream has enabled dozing
1633 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001634 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1635 logSleepTimeoutRecapturedLocked();
1636 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001637 if (mWakefulness == WAKEFULNESS_AWAKE) {
Michael Wrighte3001042019-02-05 00:13:14 +00001638 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1639 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1640 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1641 Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1642 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001643 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001644 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001645 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001646 }
1647 }
1648
Jeff Brown96307042012-07-27 15:51:34 -07001649 /**
1650 * Updates the global power state based on dirty bits recorded in mDirty.
1651 *
1652 * This is the main function that performs power state transitions.
1653 * We centralize them here so that we can recompute the power state completely
1654 * each time something important changes, and ensure that we do it the same
1655 * way each time. The point is to gather all of the transition logic here.
1656 */
1657 private void updatePowerStateLocked() {
1658 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001659 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001661 if (!Thread.holdsLock(mLock)) {
1662 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1663 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001664
Jeff Brown3edf5272014-08-14 19:25:14 -07001665 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1666 try {
1667 // Phase 0: Basic state updates.
1668 updateIsPoweredLocked(mDirty);
1669 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001670 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671
Jeff Brown3edf5272014-08-14 19:25:14 -07001672 // Phase 1: Update wakefulness.
1673 // Loop because the wake lock and user activity computations are influenced
1674 // by changes in wakefulness.
1675 final long now = SystemClock.uptimeMillis();
1676 int dirtyPhase2 = 0;
1677 for (;;) {
1678 int dirtyPhase1 = mDirty;
1679 dirtyPhase2 |= dirtyPhase1;
1680 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001681
Jeff Brown3edf5272014-08-14 19:25:14 -07001682 updateWakeLockSummaryLocked(dirtyPhase1);
1683 updateUserActivitySummaryLocked(now, dirtyPhase1);
1684 if (!updateWakefulnessLocked(dirtyPhase1)) {
1685 break;
1686 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001688
Pavel Grafov28939982017-10-03 15:11:52 +01001689 // Phase 2: Lock profiles that became inactive/not kept awake.
1690 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001691
Pavel Grafov28939982017-10-03 15:11:52 +01001692 // Phase 3: Update display power state.
1693 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1694
1695 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001696 updateDreamLocked(dirtyPhase2, displayBecameReady);
1697
Pavel Grafov28939982017-10-03 15:11:52 +01001698 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001699 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001700
Pavel Grafov28939982017-10-03 15:11:52 +01001701 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001702 // Because we might release the last suspend blocker here, we need to make sure
1703 // we finished everything else first!
1704 updateSuspendBlockerLocked();
1705 } finally {
1706 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001707 }
Jeff Brown96307042012-07-27 15:51:34 -07001708 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001709
Jim Miller92e66dd2012-02-21 18:57:12 -08001710 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001711 * Check profile timeouts and notify profiles that should be locked.
1712 */
1713 private void updateProfilesLocked(long now) {
1714 final int numProfiles = mProfilePowerState.size();
1715 for (int i = 0; i < numProfiles; i++) {
1716 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1717 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1718 profile.mLockingNotified = false;
1719 } else if (!profile.mLockingNotified) {
1720 profile.mLockingNotified = true;
1721 mNotifier.onProfileTimeout(profile.mUserId);
1722 }
1723 }
1724 }
1725
1726 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1727 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1728 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1729 || (mProximityPositive &&
1730 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1731 }
1732
1733 /**
Jeff Brown96307042012-07-27 15:51:34 -07001734 * Updates the value of mIsPowered.
1735 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001736 */
Jeff Brown96307042012-07-27 15:51:34 -07001737 private void updateIsPoweredLocked(int dirty) {
1738 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001739 final boolean wasPowered = mIsPowered;
1740 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001741 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001742 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1743 mPlugType = mBatteryManagerInternal.getPlugType();
1744 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1745 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001746
Jeff Brown26875502014-01-30 21:47:47 -08001747 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001748 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001749 + ", mIsPowered=" + mIsPowered
1750 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001751 + ", mPlugType=" + mPlugType
1752 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001753 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001754
Jeff Brownf3fb8952012-10-02 20:57:05 -07001755 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001756 mDirty |= DIRTY_IS_POWERED;
1757
Jeff Brown3b971592013-01-09 18:46:37 -08001758 // Update wireless dock detection state.
1759 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001760 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001761
Jeff Brown96307042012-07-27 15:51:34 -07001762 // Treat plugging and unplugging the devices as a user activity.
1763 // Users find it disconcerting when they plug or unplug the device
1764 // and it shuts off right away.
1765 // Some devices also wake the device when plugged or unplugged because
1766 // they don't have a charging LED.
1767 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001768 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1769 dockedOnWirelessCharger)) {
Michael Wrighte3001042019-02-05 00:13:14 +00001770 wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1771 "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001772 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001773 }
1774 userActivityNoUpdateLocked(
1775 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001776
Beverlyac32c9a2018-01-31 16:10:41 -05001777 // only play charging sounds if boot is completed so charging sounds don't play
1778 // with potential notification sounds
1779 if (mBootCompleted) {
1780 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1781 && BatteryManager.isPlugWired(mPlugType)) {
Beverly91d0a632018-07-02 16:45:00 -04001782 mNotifier.onWiredChargingStarted(mForegroundProfile);
Beverlyac32c9a2018-01-31 16:10:41 -05001783 } else if (dockedOnWirelessCharger) {
Beverly91d0a632018-07-02 16:45:00 -04001784 mNotifier.onWirelessChargingStarted(mBatteryLevel, mForegroundProfile);
Beverlyac32c9a2018-01-31 16:10:41 -05001785 }
Jeff Brown84e27562012-12-07 13:56:34 -08001786 }
Jeff Brown96307042012-07-27 15:51:34 -07001787 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001788
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001789 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001790 }
1791 }
1792
Jeff Brown3b971592013-01-09 18:46:37 -08001793 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1794 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001795 // Don't wake when powered unless configured to do so.
1796 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1797 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001798 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001799
Jeff Brown3b971592013-01-09 18:46:37 -08001800 // Don't wake when undocked from wireless charger.
1801 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001802 if (wasPowered && !mIsPowered
1803 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1804 return false;
1805 }
Jeff Brown3b971592013-01-09 18:46:37 -08001806
1807 // Don't wake when docked on wireless charger unless we are certain of it.
1808 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001809 if (!wasPowered && mIsPowered
1810 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001811 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001812 return false;
1813 }
1814
1815 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001816 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001817 return false;
1818 }
1819
Bryce Lee584a4452014-10-21 15:55:55 -07001820 // Don't wake while theater mode is enabled.
1821 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1822 return false;
1823 }
1824
Adrian Roos56021892017-02-27 20:25:09 +01001825 // On Always On Display, SystemUI shows the charging indicator
1826 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1827 return false;
1828 }
1829
Jeff Brown9fca9e92012-10-05 14:42:56 -07001830 // Otherwise wake up!
1831 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001832 }
1833
Jeff Brown96307042012-07-27 15:51:34 -07001834 /**
1835 * Updates the value of mStayOn.
1836 * Sets DIRTY_STAY_ON if a change occurred.
1837 */
1838 private void updateStayOnLocked(int dirty) {
1839 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001840 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001841 if (mStayOnWhilePluggedInSetting != 0
1842 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001843 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001844 } else {
1845 mStayOn = false;
1846 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001847
1848 if (mStayOn != wasStayOn) {
1849 mDirty |= DIRTY_STAY_ON;
1850 }
Jeff Brown96307042012-07-27 15:51:34 -07001851 }
1852 }
1853
1854 /**
1855 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1856 * Note that most wake-locks are ignored when the system is asleep.
1857 *
1858 * This function must have no other side-effects.
1859 */
Jeff Brownec083212013-09-11 20:45:25 -07001860 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001861 private void updateWakeLockSummaryLocked(int dirty) {
1862 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1863 mWakeLockSummary = 0;
1864
Pavel Grafov28939982017-10-03 15:11:52 +01001865 final int numProfiles = mProfilePowerState.size();
1866 for (int i = 0; i < numProfiles; i++) {
1867 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1868 }
1869
Jeff Brown96307042012-07-27 15:51:34 -07001870 final int numWakeLocks = mWakeLocks.size();
1871 for (int i = 0; i < numWakeLocks; i++) {
1872 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001873 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1874 mWakeLockSummary |= wakeLockFlags;
1875 for (int j = 0; j < numProfiles; j++) {
1876 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1877 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1878 profile.mWakeLockSummary |= wakeLockFlags;
1879 }
Jeff Brown96307042012-07-27 15:51:34 -07001880 }
1881 }
1882
Pavel Grafov28939982017-10-03 15:11:52 +01001883 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1884 for (int i = 0; i < numProfiles; i++) {
1885 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1886 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001887 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001888
Jeff Brown96307042012-07-27 15:51:34 -07001889 if (DEBUG_SPEW) {
1890 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001891 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001892 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1893 }
1894 }
1895 }
1896
Pavel Grafov28939982017-10-03 15:11:52 +01001897 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1898 // Cancel wake locks that make no sense based on the current state.
1899 if (mWakefulness != WAKEFULNESS_DOZING) {
1900 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1901 }
1902 if (mWakefulness == WAKEFULNESS_ASLEEP
1903 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1904 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1905 | WAKE_LOCK_BUTTON_BRIGHT);
1906 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1907 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1908 }
1909 }
1910
1911 // Infer implied wake locks where necessary based on the current state.
1912 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1913 if (mWakefulness == WAKEFULNESS_AWAKE) {
1914 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1915 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1916 wakeLockSummary |= WAKE_LOCK_CPU;
1917 }
1918 }
1919 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1920 wakeLockSummary |= WAKE_LOCK_CPU;
1921 }
1922
1923 return wakeLockSummary;
1924 }
1925
1926 /** Get wake lock summary flags that correspond to the given wake lock. */
1927 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1928 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1929 case PowerManager.PARTIAL_WAKE_LOCK:
1930 if (!wakeLock.mDisabled) {
1931 // We only respect this if the wake lock is not disabled.
1932 return WAKE_LOCK_CPU;
1933 }
1934 break;
1935 case PowerManager.FULL_WAKE_LOCK:
1936 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1937 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1938 return WAKE_LOCK_SCREEN_BRIGHT;
1939 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1940 return WAKE_LOCK_SCREEN_DIM;
1941 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1942 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1943 case PowerManager.DOZE_WAKE_LOCK:
1944 return WAKE_LOCK_DOZE;
1945 case PowerManager.DRAW_WAKE_LOCK:
1946 return WAKE_LOCK_DRAW;
1947 }
1948 return 0;
1949 }
1950
1951 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
1952 if (wakeLock.mWorkSource != null) {
1953 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
1954 final int uid = wakeLock.mWorkSource.get(k);
1955 if (userId == UserHandle.getUserId(uid)) {
1956 return true;
1957 }
1958 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00001959
1960 final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
1961 if (workChains != null) {
1962 for (int k = 0; k < workChains.size(); k++) {
1963 final int uid = workChains.get(k).getAttributionUid();
1964 if (userId == UserHandle.getUserId(uid)) {
1965 return true;
1966 }
1967 }
1968 }
Pavel Grafov28939982017-10-03 15:11:52 +01001969 }
1970 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
1971 }
1972
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001973 void checkForLongWakeLocks() {
1974 synchronized (mLock) {
1975 final long now = SystemClock.uptimeMillis();
1976 mNotifyLongDispatched = now;
1977 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1978 long nextCheckTime = Long.MAX_VALUE;
1979 final int numWakeLocks = mWakeLocks.size();
1980 for (int i = 0; i < numWakeLocks; i++) {
1981 final WakeLock wakeLock = mWakeLocks.get(i);
1982 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1983 == PowerManager.PARTIAL_WAKE_LOCK) {
1984 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1985 if (wakeLock.mAcquireTime < when) {
1986 // This wake lock has exceeded the long acquire time, report!
1987 notifyWakeLockLongStartedLocked(wakeLock);
1988 } else {
1989 // This wake lock could still become a long one, at this time.
1990 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
1991 if (checkTime < nextCheckTime) {
1992 nextCheckTime = checkTime;
1993 }
1994 }
1995 }
1996 }
1997 }
1998 mNotifyLongScheduled = 0;
1999 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2000 if (nextCheckTime != Long.MAX_VALUE) {
2001 mNotifyLongNextCheck = nextCheckTime;
2002 enqueueNotifyLongMsgLocked(nextCheckTime);
2003 } else {
2004 mNotifyLongNextCheck = 0;
2005 }
2006 }
2007 }
2008
Jeff Brown96307042012-07-27 15:51:34 -07002009 /**
2010 * Updates the value of mUserActivitySummary to summarize the user requested
2011 * state of the system such as whether the screen should be bright or dim.
2012 * Note that user activity is ignored when the system is asleep.
2013 *
2014 * This function must have no other side-effects.
2015 */
2016 private void updateUserActivitySummaryLocked(long now, int dirty) {
2017 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07002018 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08002019 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002020 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2021
2022 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08002023 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002024 || mWakefulness == WAKEFULNESS_DREAMING
2025 || mWakefulness == WAKEFULNESS_DOZING) {
Pavel Grafov28939982017-10-03 15:11:52 +01002026 final long sleepTimeout = getSleepTimeoutLocked();
2027 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
2028 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002029 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002030 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002031
2032 mUserActivitySummary = 0;
2033 if (mLastUserActivityTime >= mLastWakeTime) {
2034 nextTimeout = mLastUserActivityTime
2035 + screenOffTimeout - screenDimDuration;
2036 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002037 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002038 } else {
2039 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2040 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002041 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002042 }
2043 }
2044 }
2045 if (mUserActivitySummary == 0
2046 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2047 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002048 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002049 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2050 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002051 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2052 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2053 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2054 }
Jeff Brown96307042012-07-27 15:51:34 -07002055 }
2056 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002057
Jeff Brown05af6ad2014-09-30 20:54:30 -07002058 if (mUserActivitySummary == 0) {
2059 if (sleepTimeout >= 0) {
2060 final long anyUserActivity = Math.max(mLastUserActivityTime,
2061 mLastUserActivityTimeNoChangeLights);
2062 if (anyUserActivity >= mLastWakeTime) {
2063 nextTimeout = anyUserActivity + sleepTimeout;
2064 if (now < nextTimeout) {
2065 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2066 }
2067 }
2068 } else {
2069 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2070 nextTimeout = -1;
2071 }
2072 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002073
2074 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002075 if ((mUserActivitySummary &
2076 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002077 // Device is being kept awake by recent user activity
2078 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2079 // Save when the next timeout would have occurred
2080 mOverriddenTimeout = nextTimeout;
2081 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002082 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002083 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2084 nextTimeout = -1;
2085 }
2086
Lucas Dupin0a5d7972019-01-16 18:52:30 -08002087 if ((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0) {
2088 nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout);
2089 }
2090
Pavel Grafov28939982017-10-03 15:11:52 +01002091 if (nextProfileTimeout > 0) {
2092 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2093 }
2094
Jeff Brown05af6ad2014-09-30 20:54:30 -07002095 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002096 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002097 }
2098 } else {
2099 mUserActivitySummary = 0;
2100 }
2101
2102 if (DEBUG_SPEW) {
2103 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002104 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002105 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2106 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2107 }
2108 }
2109 }
2110
Pavel Grafov28939982017-10-03 15:11:52 +01002111 private void scheduleUserInactivityTimeout(long timeMs) {
2112 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2113 msg.setAsynchronous(true);
2114 mHandler.sendMessageAtTime(msg, timeMs);
2115 }
2116
2117 /**
2118 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2119 */
2120 private long getNextProfileTimeoutLocked(long now) {
2121 long nextTimeout = -1;
2122 final int numProfiles = mProfilePowerState.size();
2123 for (int i = 0; i < numProfiles; i++) {
2124 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2125 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2126 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2127 nextTimeout = timeout;
2128 }
2129 }
2130 return nextTimeout;
2131 }
2132
Jeff Brown96307042012-07-27 15:51:34 -07002133 /**
2134 * Called when a user activity timeout has occurred.
2135 * Simply indicates that something about user activity has changed so that the new
2136 * state can be recomputed when the power state is updated.
2137 *
2138 * This function must have no other side-effects besides setting the dirty
2139 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2140 */
2141 private void handleUserActivityTimeout() { // runs on handler thread
2142 synchronized (mLock) {
2143 if (DEBUG_SPEW) {
2144 Slog.d(TAG, "handleUserActivityTimeout");
2145 }
2146
2147 mDirty |= DIRTY_USER_ACTIVITY;
2148 updatePowerStateLocked();
2149 }
2150 }
2151
Pavel Grafov28939982017-10-03 15:11:52 +01002152 private long getSleepTimeoutLocked() {
2153 final long timeout = mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002154 if (timeout <= 0) {
2155 return -1;
2156 }
2157 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2158 }
2159
Pavel Grafov28939982017-10-03 15:11:52 +01002160 private long getScreenOffTimeoutLocked(long sleepTimeout) {
2161 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002162 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2163 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2164 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002165 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002166 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002167 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002168 if (sleepTimeout >= 0) {
2169 timeout = Math.min(timeout, sleepTimeout);
2170 }
Jeff Brown27736f52014-05-20 17:17:10 -07002171 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002172 }
2173
Pavel Grafov28939982017-10-03 15:11:52 +01002174 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002175 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002176 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002177 }
2178
2179 /**
2180 * Updates the wakefulness of the device.
2181 *
Jeff Brown26875502014-01-30 21:47:47 -08002182 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002183 * based on the current wake locks and user activity state. It may modify mDirty
2184 * if the wakefulness changes.
2185 *
2186 * Returns true if the wakefulness changed and we need to restart power state calculation.
2187 */
2188 private boolean updateWakefulnessLocked(int dirty) {
2189 boolean changed = false;
2190 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002191 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
2192 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002193 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2194 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002195 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002196 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002197 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07002198 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002199 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002200 } else {
2201 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002202 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002203 }
Jeff Brown96307042012-07-27 15:51:34 -07002204 }
2205 }
2206 return changed;
2207 }
2208
Jeff Brown645832d2012-10-03 14:57:03 -07002209 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002210 * Returns true if the device should automatically nap and start dreaming when the user
2211 * activity timeout has expired and it's bedtime.
2212 */
2213 private boolean shouldNapAtBedTimeLocked() {
2214 return mDreamsActivateOnSleepSetting
2215 || (mDreamsActivateOnDockSetting
2216 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2217 }
2218
2219 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002220 * Returns true if the device should go to sleep now.
2221 * Also used when exiting a dream to determine whether we should go back
2222 * to being fully awake or else go to sleep for good.
2223 */
Jeff Brown96307042012-07-27 15:51:34 -07002224 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07002225 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07002226 }
2227
2228 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002229 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002230 * or the stay on while powered setting. We also keep the phone awake when
2231 * the proximity sensor returns a positive result so that the device does not
2232 * lock while in a phone call. This function only controls whether the device
2233 * will go to sleep or dream which is independent of whether it will be allowed
2234 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002235 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002236 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002237 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002238 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002239 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002240 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002241 | USER_ACTIVITY_SCREEN_DIM)) != 0
2242 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002243 }
2244
2245 /**
2246 * Determines whether to post a message to the sandman to update the dream state.
2247 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002248 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002249 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002250 | DIRTY_USER_ACTIVITY
2251 | DIRTY_WAKE_LOCKS
2252 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002253 | DIRTY_SETTINGS
2254 | DIRTY_IS_POWERED
2255 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002256 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002257 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2258 if (mDisplayReady) {
2259 scheduleSandmanLocked();
2260 }
Jeff Brown96307042012-07-27 15:51:34 -07002261 }
2262 }
2263
2264 private void scheduleSandmanLocked() {
2265 if (!mSandmanScheduled) {
2266 mSandmanScheduled = true;
2267 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2268 msg.setAsynchronous(true);
2269 mHandler.sendMessage(msg);
2270 }
2271 }
2272
2273 /**
Jeff Brown26875502014-01-30 21:47:47 -08002274 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002275 *
2276 * We do this asynchronously because we must call out of the power manager to start
2277 * the dream and we don't want to hold our lock while doing so. There is a risk that
2278 * the device will wake or go to sleep in the meantime so we have to handle that case.
2279 */
2280 private void handleSandman() { // runs on handler thread
2281 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002282 final boolean startDreaming;
2283 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002284 synchronized (mLock) {
2285 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002286 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002287 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002288 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002289 mSandmanSummoned = false;
2290 } else {
2291 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002292 }
2293 }
2294
Jeff Brown96307042012-07-27 15:51:34 -07002295 // Start dreaming if needed.
2296 // We only control the dream on the handler thread, so we don't need to worry about
2297 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002298 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002299 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002300 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002301 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002302 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002303 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002304 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002305 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002306 } else {
2307 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002308 }
2309
2310 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002311 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002312 // Remember the initial battery level when the dream started.
2313 if (startDreaming && isDreaming) {
2314 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2315 if (wakefulness == WAKEFULNESS_DOZING) {
2316 Slog.i(TAG, "Dozing...");
2317 } else {
2318 Slog.i(TAG, "Dreaming...");
2319 }
2320 }
2321
2322 // If preconditions changed, wait for the next iteration to determine
2323 // whether the dream should continue (or be restarted).
2324 if (mSandmanSummoned || mWakefulness != wakefulness) {
2325 return; // wait for next cycle
2326 }
2327
2328 // Determine whether the dream should continue.
2329 if (wakefulness == WAKEFULNESS_DREAMING) {
2330 if (isDreaming && canDreamLocked()) {
2331 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002332 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002333 - mDreamsBatteryLevelDrainCutoffConfig
2334 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002335 // If the user activity timeout expired and the battery appears
2336 // to be draining faster than it is charging then stop dreaming
2337 // and go to sleep.
2338 Slog.i(TAG, "Stopping dream because the battery appears to "
2339 + "be draining faster than it is charging. "
2340 + "Battery level when dream started: "
2341 + mBatteryLevelWhenDreamStarted + "%. "
2342 + "Battery level now: " + mBatteryLevel + "%.");
2343 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002344 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002345 }
Jeff Brown96307042012-07-27 15:51:34 -07002346 }
Jeff Brown26875502014-01-30 21:47:47 -08002347
2348 // Dream has ended or will be stopped. Update the power state.
2349 if (isItBedTimeYetLocked()) {
2350 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07002351 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002352 updatePowerStateLocked();
2353 } else {
Michael Wrighte3001042019-02-05 00:13:14 +00002354 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
2355 PowerManager.WAKE_REASON_UNKNOWN,
2356 "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2357 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002358 updatePowerStateLocked();
2359 }
2360 } else if (wakefulness == WAKEFULNESS_DOZING) {
2361 if (isDreaming) {
2362 return; // continue dozing
2363 }
2364
2365 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07002366 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002367 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002368 }
Jeff Brown96307042012-07-27 15:51:34 -07002369 }
2370
Jeff Brown26875502014-01-30 21:47:47 -08002371 // Stop dream.
2372 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002373 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002374 }
2375 }
2376
2377 /**
Jeff Brown26875502014-01-30 21:47:47 -08002378 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002379 */
2380 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002381 if (mWakefulness != WAKEFULNESS_DREAMING
2382 || !mDreamsSupportedConfig
2383 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002384 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002385 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002386 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2387 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002388 || !mBootCompleted) {
2389 return false;
2390 }
2391 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002392 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002393 return false;
2394 }
2395 if (!mIsPowered
2396 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2397 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2398 return false;
2399 }
2400 if (mIsPowered
2401 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2402 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2403 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002404 }
2405 }
Jeff Brown26875502014-01-30 21:47:47 -08002406 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002407 }
2408
Jeff Brown96307042012-07-27 15:51:34 -07002409 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002410 * Returns true if the device is allowed to doze in its current state.
2411 */
2412 private boolean canDozeLocked() {
2413 return mWakefulness == WAKEFULNESS_DOZING;
2414 }
2415
2416 /**
Jeff Brown96307042012-07-27 15:51:34 -07002417 * Updates the display power state asynchronously.
2418 * When the update is finished, mDisplayReady will be set to true. The display
2419 * controller posts a message to tell us when the actual display power state
2420 * has been updated so we come back here to double-check and finish up.
2421 *
2422 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002423 *
2424 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002425 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002426 private boolean updateDisplayPowerStateLocked(int dirty) {
2427 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002428 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2429 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002430 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2431 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002432 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002433
Jeff Browne333e672014-10-28 13:48:55 -07002434 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002435 final boolean autoBrightness;
2436 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002437 if (!mBootCompleted) {
2438 // Keep the brightness steady during boot. This requires the
2439 // bootloader brightness and the default brightness to be identical.
2440 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002441 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002442 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002443 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002444 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2445 } else {
2446 autoBrightness = (mScreenBrightnessModeSetting ==
2447 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2448 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002449 }
Jeff Browne333e672014-10-28 13:48:55 -07002450
2451 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002452 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002453 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002454 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002455 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002456
jackqdyulei92681e82017-02-28 11:26:28 -08002457 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2458
Jeff Brown970d4132014-07-19 11:33:47 -07002459 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2460 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002461 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2462 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002463 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2464 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2465 }
2466 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2467 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2468 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002469 }
Jeff Brown970d4132014-07-19 11:33:47 -07002470 mDisplayPowerRequest.dozeScreenBrightness =
2471 mDozeScreenBrightnessOverrideFromDreamManager;
2472 } else {
2473 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2474 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2475 }
2476
Jeff Brown131206b2014-04-08 17:27:14 -07002477 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002478 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002479 mRequestWaitForNegativeProximity = false;
2480
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002481 if ((dirty & DIRTY_QUIESCENT) != 0) {
2482 sQuiescent = false;
2483 }
Jeff Brown96307042012-07-27 15:51:34 -07002484 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002485 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002486 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002487 + ", mWakefulness=" + mWakefulness
2488 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2489 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002490 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002491 + ", screenBrightnessOverride=" + screenBrightnessOverride
2492 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002493 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002494 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002495 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002496 }
2497 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002498 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002499 }
2500
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002501 private void updateScreenBrightnessBoostLocked(int dirty) {
2502 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2503 if (mScreenBrightnessBoostInProgress) {
2504 final long now = SystemClock.uptimeMillis();
2505 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2506 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2507 final long boostTimeout = mLastScreenBrightnessBoostTime +
2508 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2509 if (boostTimeout > now) {
2510 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2511 msg.setAsynchronous(true);
2512 mHandler.sendMessageAtTime(msg, boostTimeout);
2513 return;
2514 }
Jeff Browne333e672014-10-28 13:48:55 -07002515 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002516 mScreenBrightnessBoostInProgress = false;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002517 mNotifier.onScreenBrightnessBoostChanged();
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002518 userActivityNoUpdateLocked(now,
2519 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002520 }
Jeff Browne333e672014-10-28 13:48:55 -07002521 }
2522 }
2523
Santos Cordon3107d292016-09-20 15:50:35 -07002524 private boolean shouldBoostScreenBrightness() {
2525 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2526 }
2527
Jeff Brown96307042012-07-27 15:51:34 -07002528 private static boolean isValidBrightness(int value) {
2529 return value >= 0 && value <= 255;
2530 }
2531
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002532 @VisibleForTesting
2533 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002534 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002535 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002536 }
2537
Jeff Brown2175e9c2014-09-12 16:11:07 -07002538 if (mWakefulness == WAKEFULNESS_DOZING) {
2539 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2540 return DisplayPowerRequest.POLICY_DOZE;
2541 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002542 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002543 return DisplayPowerRequest.POLICY_OFF;
2544 }
2545 // Fall through and preserve the current screen policy if not configured to
2546 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002547 }
2548
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002549 // It is important that POLICY_VR check happens after the wakefulness checks above so
2550 // that VR-mode does not prevent displays from transitioning to the correct state when
2551 // dozing or sleeping.
2552 if (mIsVrModeEnabled) {
2553 return DisplayPowerRequest.POLICY_VR;
2554 }
2555
Jeff Brown96307042012-07-27 15:51:34 -07002556 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2557 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002558 || !mBootCompleted
2559 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002560 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002561 }
2562
Jeff Brown970d4132014-07-19 11:33:47 -07002563 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002564 }
2565
Jeff Brown131206b2014-04-08 17:27:14 -07002566 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2567 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002568 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002569
Jeff Brown96307042012-07-27 15:51:34 -07002570 @Override
2571 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002572 synchronized (mLock) {
2573 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2574 updatePowerStateLocked();
2575 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002576 }
2577
2578 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002579 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002580 synchronized (mLock) {
2581 mProximityPositive = true;
2582 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2583 updatePowerStateLocked();
2584 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002585 }
2586
2587 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002588 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002589 synchronized (mLock) {
2590 mProximityPositive = false;
2591 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2592 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2593 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2594 updatePowerStateLocked();
2595 }
Jeff Brown96307042012-07-27 15:51:34 -07002596 }
Jeff Brown131206b2014-04-08 17:27:14 -07002597
2598 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002599 public void onDisplayStateChange(int state) {
2600 // This method is only needed to support legacy display blanking behavior
2601 // where the display's power state is coupled to suspend or to the power HAL.
2602 // The order of operations matters here.
2603 synchronized (mLock) {
2604 if (mDisplayState != state) {
2605 mDisplayState = state;
2606 if (state == Display.STATE_OFF) {
2607 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2608 setHalInteractiveModeLocked(false);
2609 }
2610 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2611 setHalAutoSuspendModeLocked(true);
2612 }
2613 } else {
2614 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2615 setHalAutoSuspendModeLocked(false);
2616 }
2617 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2618 setHalInteractiveModeLocked(true);
2619 }
2620 }
2621 }
2622 }
2623 }
2624
2625 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002626 public void acquireSuspendBlocker() {
2627 mDisplaySuspendBlocker.acquire();
2628 }
2629
2630 @Override
2631 public void releaseSuspendBlocker() {
2632 mDisplaySuspendBlocker.release();
2633 }
2634
2635 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002636 public String toString() {
2637 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002638 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002639 }
2640 }
Jeff Brown96307042012-07-27 15:51:34 -07002641 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002642
Jeff Brown96307042012-07-27 15:51:34 -07002643 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002644 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002645 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002646
Jeff Brown96307042012-07-27 15:51:34 -07002647 /**
2648 * Updates the suspend blocker that keeps the CPU alive.
2649 *
2650 * This function must have no other side-effects.
2651 */
2652 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002653 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002654 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2655 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002656 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002657
2658 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002659 // FIXME We should consider just leaving auto-suspend enabled forever since
2660 // we already hold the necessary wakelocks.
2661 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2662 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002663 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002664
2665 // First acquire suspend blockers if needed.
2666 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2667 mWakeLockSuspendBlocker.acquire();
2668 mHoldingWakeLockSuspendBlocker = true;
2669 }
2670 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2671 mDisplaySuspendBlocker.acquire();
2672 mHoldingDisplaySuspendBlocker = true;
2673 }
2674
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002675 // Inform the power HAL about interactive mode.
2676 // Although we could set interactive strictly based on the wakefulness
2677 // as reported by isInteractive(), it is actually more desirable to track
2678 // the display policy state instead so that the interactive state observed
2679 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2680 // Refer to getDesiredScreenPolicyLocked() for details.
2681 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2682 // When becoming non-interactive, we want to defer sending this signal
2683 // until the display is actually ready so that all transitions have
2684 // completed. This is probably a good sign that things have gotten
2685 // too tangled over here...
2686 if (interactive || mDisplayReady) {
2687 setHalInteractiveModeLocked(interactive);
2688 }
2689 }
2690
Jeff Brown27f7a862012-12-12 15:43:31 -08002691 // Then release suspend blockers if needed.
2692 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2693 mWakeLockSuspendBlocker.release();
2694 mHoldingWakeLockSuspendBlocker = false;
2695 }
2696 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2697 mDisplaySuspendBlocker.release();
2698 mHoldingDisplaySuspendBlocker = false;
2699 }
Jeff Brown26875502014-01-30 21:47:47 -08002700
2701 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002702 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2703 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002704 }
Jeff Brown96307042012-07-27 15:51:34 -07002705 }
2706
Jeff Brownec083212013-09-11 20:45:25 -07002707 /**
2708 * Return true if we must keep a suspend blocker active on behalf of the display.
2709 * We do so if the screen is on or is in transition between states.
2710 */
Jeff Brown26875502014-01-30 21:47:47 -08002711 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002712 if (!mDisplayReady) {
2713 return true;
2714 }
Jeff Brown970d4132014-07-19 11:33:47 -07002715 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002716 // If we asked for the screen to be on but it is off due to the proximity
2717 // sensor then we may suspend but only if the configuration allows it.
2718 // On some hardware it may not be safe to suspend because the proximity
2719 // sensor may not be correctly configured as a wake-up source.
2720 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2721 || !mSuspendWhenScreenOffDueToProximityConfig) {
2722 return true;
2723 }
2724 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002725 if (mScreenBrightnessBoostInProgress) {
2726 return true;
2727 }
Jeff Brown26875502014-01-30 21:47:47 -08002728 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002729 return false;
2730 }
2731
Jeff Brown037c33e2014-04-09 00:31:55 -07002732 private void setHalAutoSuspendModeLocked(boolean enable) {
2733 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002734 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002735 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002736 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002737 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002738 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2739 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002740 mNativeWrapper.nativeSetAutoSuspend(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002741 } finally {
2742 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2743 }
Jeff Brown26875502014-01-30 21:47:47 -08002744 }
2745 }
2746
Jeff Brown037c33e2014-04-09 00:31:55 -07002747 private void setHalInteractiveModeLocked(boolean enable) {
2748 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002749 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002750 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002751 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002752 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002753 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2754 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002755 mNativeWrapper.nativeSetInteractive(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002756 } finally {
2757 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2758 }
Jeff Brown26875502014-01-30 21:47:47 -08002759 }
2760 }
2761
Jeff Brown037c33e2014-04-09 00:31:55 -07002762 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002763 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002764 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002765 }
2766 }
2767
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002768 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002769 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002770 if (DEBUG) {
2771 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2772 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002773 if (mIsPowered) {
2774 return false;
2775 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002776
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002777 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002778
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002779 return true;
2780 }
2781 }
2782
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002783 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002784 synchronized (mLock) {
2785 return mDeviceIdleMode;
2786 }
2787 }
2788
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002789 boolean isLightDeviceIdleModeInternal() {
2790 synchronized (mLock) {
2791 return mLightDeviceIdleMode;
2792 }
2793 }
2794
Jeff Brown96307042012-07-27 15:51:34 -07002795 private void handleBatteryStateChangedLocked() {
2796 mDirty |= DIRTY_BATTERY_STATE;
2797 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002798 }
2799
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002800 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002801 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002802 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07002803 if (RescueParty.isAttemptingFactoryReset()) {
2804 // If we're stuck in a really low-level reboot loop, and a
2805 // rescue party is trying to prompt the user for a factory data
2806 // reset, we must GET TO DA CHOPPA!
2807 PowerManagerService.lowLevelReboot(reason);
2808 } else {
2809 throw new IllegalStateException("Too early to call shutdown() or reboot()");
2810 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002811 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002812
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002813 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002814 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002815 public void run() {
2816 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002817 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002818 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002819 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002820 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002821 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002822 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002823 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002824 }
San Mehat1e512792010-01-07 10:40:29 -08002825 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002826 };
Jeff Brown96307042012-07-27 15:51:34 -07002827
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002828 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00002829 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07002830 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00002831 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002832
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002833 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002834 if (wait) {
2835 synchronized (runnable) {
2836 while (true) {
2837 try {
2838 runnable.wait();
2839 } catch (InterruptedException e) {
2840 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002841 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002842 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002843 }
2844 }
2845
Jeff Brown96307042012-07-27 15:51:34 -07002846 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002847 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002848 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002849 public void run() {
2850 throw new RuntimeException(message);
2851 }
Dan Egnor60d87622009-12-16 16:32:58 -08002852 };
2853 try {
2854 t.start();
2855 t.join();
2856 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002857 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002858 }
2859 }
2860
jackqdyulei92681e82017-02-28 11:26:28 -08002861 @VisibleForTesting
2862 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
2863 PowerSaveState state = mBatterySaverPolicy.
Kweku Adams9f488e22019-01-14 16:25:08 -08002864 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
jackqdyulei92681e82017-02-28 11:26:28 -08002865 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
2866 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
2867 }
2868
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002869 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002870 Settings.Global.putInt(mContext.getContentResolver(),
2871 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002872 }
2873
Pavel Grafov28939982017-10-03 15:11:52 +01002874 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
2875 if (userId < 0) {
2876 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
2877 return;
2878 }
Jeff Brown96307042012-07-27 15:51:34 -07002879 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002880 // System-wide timeout
2881 if (userId == UserHandle.USER_SYSTEM) {
2882 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2883 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
2884 mProfilePowerState.delete(userId);
2885 } else {
2886 final ProfilePowerState profile = mProfilePowerState.get(userId);
2887 if (profile != null) {
2888 profile.mScreenOffTimeout = timeMs;
2889 } else {
2890 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
2891 // We need to recalculate wake locks for the new profile state.
2892 mDirty |= DIRTY_WAKE_LOCKS;
2893 }
2894 }
Jeff Brown96307042012-07-27 15:51:34 -07002895 mDirty |= DIRTY_SETTINGS;
2896 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002897 }
2898 }
2899
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002900 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002901 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002902 if (mDeviceIdleMode == enabled) {
2903 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002904 }
Felipe Lemeea014392016-09-06 13:59:54 -07002905 mDeviceIdleMode = enabled;
2906 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002907 }
Felipe Lemeea014392016-09-06 13:59:54 -07002908 if (enabled) {
2909 EventLogTags.writeDeviceIdleOnPhase("power");
2910 } else {
2911 EventLogTags.writeDeviceIdleOffPhase("power");
2912 }
2913 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002914 }
2915
2916 boolean setLightDeviceIdleModeInternal(boolean enabled) {
2917 synchronized (mLock) {
2918 if (mLightDeviceIdleMode != enabled) {
2919 mLightDeviceIdleMode = enabled;
2920 return true;
2921 }
2922 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002923 }
2924 }
2925
2926 void setDeviceIdleWhitelistInternal(int[] appids) {
2927 synchronized (mLock) {
2928 mDeviceIdleWhitelist = appids;
2929 if (mDeviceIdleMode) {
2930 updateWakeLockDisabledStatesLocked();
2931 }
2932 }
2933 }
2934
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002935 void setDeviceIdleTempWhitelistInternal(int[] appids) {
2936 synchronized (mLock) {
2937 mDeviceIdleTempWhitelist = appids;
2938 if (mDeviceIdleMode) {
2939 updateWakeLockDisabledStatesLocked();
2940 }
2941 }
2942 }
2943
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002944 void startUidChangesInternal() {
2945 synchronized (mLock) {
2946 mUidsChanging = true;
2947 }
2948 }
2949
2950 void finishUidChangesInternal() {
2951 synchronized (mLock) {
2952 mUidsChanging = false;
2953 if (mUidsChanged) {
2954 updateWakeLockDisabledStatesLocked();
2955 mUidsChanged = false;
2956 }
2957 }
2958 }
2959
2960 private void handleUidStateChangeLocked() {
2961 if (mUidsChanging) {
2962 mUidsChanged = true;
2963 } else {
2964 updateWakeLockDisabledStatesLocked();
2965 }
2966 }
2967
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002968 void updateUidProcStateInternal(int uid, int procState) {
2969 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002970 UidState state = mUidState.get(uid);
2971 if (state == null) {
2972 state = new UidState(uid);
2973 mUidState.put(uid, state);
2974 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07002975 final boolean oldShouldAllow = state.mProcState
2976 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002977 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07002978 if (state.mNumWakeLocks > 0) {
2979 if (mDeviceIdleMode) {
2980 handleUidStateChangeLocked();
2981 } else if (!state.mActive && oldShouldAllow !=
2982 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
2983 // If this uid is not active, but the process state has changed such
2984 // that we may still want to allow it to hold a wake lock, then take care of it.
2985 handleUidStateChangeLocked();
2986 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002987 }
2988 }
2989 }
2990
2991 void uidGoneInternal(int uid) {
2992 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002993 final int index = mUidState.indexOfKey(uid);
2994 if (index >= 0) {
2995 UidState state = mUidState.valueAt(index);
2996 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
2997 state.mActive = false;
2998 mUidState.removeAt(index);
2999 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
3000 handleUidStateChangeLocked();
3001 }
3002 }
3003 }
3004 }
3005
3006 void uidActiveInternal(int uid) {
3007 synchronized (mLock) {
3008 UidState state = mUidState.get(uid);
3009 if (state == null) {
3010 state = new UidState(uid);
3011 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3012 mUidState.put(uid, state);
3013 }
3014 state.mActive = true;
3015 if (state.mNumWakeLocks > 0) {
3016 handleUidStateChangeLocked();
3017 }
3018 }
3019 }
3020
3021 void uidIdleInternal(int uid) {
3022 synchronized (mLock) {
3023 UidState state = mUidState.get(uid);
3024 if (state != null) {
3025 state.mActive = false;
3026 if (state.mNumWakeLocks > 0) {
3027 handleUidStateChangeLocked();
3028 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003029 }
3030 }
3031 }
3032
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003033 private void updateWakeLockDisabledStatesLocked() {
3034 boolean changed = false;
3035 final int numWakeLocks = mWakeLocks.size();
3036 for (int i = 0; i < numWakeLocks; i++) {
3037 final WakeLock wakeLock = mWakeLocks.get(i);
3038 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003039 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003040 if (setWakeLockDisabledStateLocked(wakeLock)) {
3041 changed = true;
3042 if (wakeLock.mDisabled) {
3043 // This wake lock is no longer being respected.
3044 notifyWakeLockReleasedLocked(wakeLock);
3045 } else {
3046 notifyWakeLockAcquiredLocked(wakeLock);
3047 }
3048 }
3049 }
3050 }
3051 if (changed) {
3052 mDirty |= DIRTY_WAKE_LOCKS;
3053 updatePowerStateLocked();
3054 }
3055 }
3056
3057 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3058 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3059 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003060 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003061 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3062 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003063 // Cached inactive processes are never allowed to hold wake locks.
3064 if (mConstants.NO_CACHED_WAKE_LOCKS) {
Santos Cordon12f92eb2019-02-01 21:28:47 +00003065 disabled = mForceSuspendActive
3066 || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003067 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Santos Cordon12f92eb2019-02-01 21:28:47 +00003068 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003069 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003070 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003071 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003072 // for application uids that are not whitelisted.
3073 final UidState state = wakeLock.mUidState;
3074 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3075 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3076 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003077 state.mProcState >
3078 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003079 disabled = true;
3080 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003081 }
3082 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003083 if (wakeLock.mDisabled != disabled) {
3084 wakeLock.mDisabled = disabled;
3085 return true;
3086 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003087 }
3088 return false;
3089 }
3090
Jeff Brown96307042012-07-27 15:51:34 -07003091 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3092 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003093 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003095
Jeff Brown96307042012-07-27 15:51:34 -07003096 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003097 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003098 synchronized (mLock) {
3099 if (!mSystemReady) {
3100 return;
3101 }
3102 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003103 }
Jeff Brown96307042012-07-27 15:51:34 -07003104
3105 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003106 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003107 }
3108
Lucas Dupin16cfe452018-02-08 13:14:50 -08003109 private void setDozeAfterScreenOffInternal(boolean on) {
3110 synchronized (mLock) {
3111 mDozeAfterScreenOff = on;
3112 }
3113 }
3114
Jeff Browne333e672014-10-28 13:48:55 -07003115 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3116 synchronized (mLock) {
3117 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3118 || eventTime < mLastScreenBrightnessBoostTime) {
3119 return;
3120 }
3121
3122 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3123 mLastScreenBrightnessBoostTime = eventTime;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003124 if (!mScreenBrightnessBoostInProgress) {
3125 mScreenBrightnessBoostInProgress = true;
3126 mNotifier.onScreenBrightnessBoostChanged();
3127 }
Jeff Browne333e672014-10-28 13:48:55 -07003128 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3129
3130 userActivityNoUpdateLocked(eventTime,
3131 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3132 updatePowerStateLocked();
3133 }
3134 }
3135
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003136 private boolean isScreenBrightnessBoostedInternal() {
3137 synchronized (mLock) {
3138 return mScreenBrightnessBoostInProgress;
3139 }
3140 }
3141
Jeff Browne333e672014-10-28 13:48:55 -07003142 /**
3143 * Called when a screen brightness boost timeout has occurred.
3144 *
3145 * This function must have no other side-effects besides setting the dirty
3146 * bit and calling update power state.
3147 */
3148 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3149 synchronized (mLock) {
3150 if (DEBUG_SPEW) {
3151 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3152 }
3153
3154 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3155 updatePowerStateLocked();
3156 }
3157 }
3158
Jeff Brown96307042012-07-27 15:51:34 -07003159 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3160 synchronized (mLock) {
3161 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3162 mScreenBrightnessOverrideFromWindowManager = brightness;
3163 mDirty |= DIRTY_SETTINGS;
3164 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003165 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003166 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003167 }
3168
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003169 private void setUserInactiveOverrideFromWindowManagerInternal() {
3170 synchronized (mLock) {
3171 mUserInactiveOverrideFromWindowManager = true;
3172 mDirty |= DIRTY_USER_ACTIVITY;
3173 updatePowerStateLocked();
3174 }
3175 }
3176
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003177 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3178 synchronized (mLock) {
3179 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3180 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003181 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003182 mDirty |= DIRTY_SETTINGS;
3183 updatePowerStateLocked();
3184 }
3185 }
3186 }
3187
Jeff Brown970d4132014-07-19 11:33:47 -07003188 private void setDozeOverrideFromDreamManagerInternal(
3189 int screenState, int screenBrightness) {
3190 synchronized (mLock) {
3191 if (mDozeScreenStateOverrideFromDreamManager != screenState
3192 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3193 mDozeScreenStateOverrideFromDreamManager = screenState;
3194 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3195 mDirty |= DIRTY_SETTINGS;
3196 updatePowerStateLocked();
3197 }
3198 }
3199 }
3200
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003201 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3202 synchronized (mLock) {
3203 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3204 mDrawWakeLockOverrideFromSidekick = keepState;
3205 mDirty |= DIRTY_SETTINGS;
3206 updatePowerStateLocked();
3207 }
3208 }
3209 }
3210
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003211 @VisibleForTesting
3212 void setVrModeEnabled(boolean enabled) {
3213 mIsVrModeEnabled = enabled;
3214 }
3215
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003216 private void powerHintInternal(int hintId, int data) {
3217 // Maybe filter the event.
3218 switch (hintId) {
3219 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3220 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3221 return;
3222 }
3223 break;
3224 }
3225
Santos Cordon64a6e612018-08-22 19:27:04 +01003226 mNativeWrapper.nativeSendPowerHint(hintId, data);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003227 }
3228
Alex Kershaw2418ea92018-10-19 17:17:49 +01003229 @VisibleForTesting
3230 boolean wasDeviceIdleForInternal(long ms) {
3231 synchronized (mLock) {
3232 return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3233 }
3234 }
3235
3236 @VisibleForTesting
3237 void onUserActivity() {
3238 synchronized (mLock) {
3239 mLastUserActivityTime = SystemClock.uptimeMillis();
3240 }
3241 }
3242
Santos Cordon12f92eb2019-02-01 21:28:47 +00003243 private boolean forceSuspendInternal(int uid) {
3244 try {
3245 synchronized (mLock) {
3246 mForceSuspendActive = true;
3247 // Place the system in an non-interactive state
3248 goToSleepInternal(SystemClock.uptimeMillis(),
3249 PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3250 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3251
3252 // Disable all the partial wake locks as well
3253 updateWakeLockDisabledStatesLocked();
3254 }
3255
3256 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3257 boolean success = mNativeWrapper.nativeForceSuspend();
3258 if (!success) {
3259 Slog.i(TAG, "Force-Suspending failed in native.");
3260 }
3261 return success;
3262 } finally {
3263 synchronized (mLock) {
3264 mForceSuspendActive = false;
3265 // Re-enable wake locks once again.
3266 updateWakeLockDisabledStatesLocked();
3267 }
3268 }
3269 }
3270
Jeff Brown96307042012-07-27 15:51:34 -07003271 /**
3272 * Low-level function turn the device off immediately, without trying
3273 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003274 *
3275 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003276 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003277 public static void lowLevelShutdown(String reason) {
3278 if (reason == null) {
3279 reason = "";
3280 }
3281 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003282 }
3283
3284 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003285 * Low-level function to reboot the device. On success, this
3286 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003287 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003288 *
3289 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003290 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003291 public static void lowLevelReboot(String reason) {
3292 if (reason == null) {
3293 reason = "";
3294 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003295
3296 // If the reason is "quiescent", it means that the boot process should proceed
3297 // without turning on the screen/lights.
3298 // The "quiescent" property is sticky, meaning that any number
3299 // of subsequent reboots should honor the property until it is reset.
3300 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3301 sQuiescent = true;
3302 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003303 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3304 sQuiescent = true;
3305 reason = reason.substring(0,
3306 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3307 }
3308
3309 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3310 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3311 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003312 }
3313
3314 if (sQuiescent) {
3315 // Pass the optional "quiescent" argument to the bootloader to let it know
3316 // that it should not turn the screen/lights on.
3317 reason = reason + ",quiescent";
3318 }
3319
3320 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003321 try {
Tao Bao90237f72015-05-21 16:25:19 -07003322 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003323 } catch (InterruptedException e) {
3324 Thread.currentThread().interrupt();
3325 }
Tao Bao90237f72015-05-21 16:25:19 -07003326 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003327 }
3328
3329 @Override // Watchdog.Monitor implementation
3330 public void monitor() {
3331 // Grab and release lock for watchdog monitor to detect deadlocks.
3332 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003333 }
Jeff Brown96307042012-07-27 15:51:34 -07003334 }
3335
Jeff Brown6f357d32014-01-15 20:40:55 -08003336 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003337 pw.println("POWER MANAGER (dumpsys power)\n");
3338
Jeff Brown3b971592013-01-09 18:46:37 -08003339 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003340 synchronized (mLock) {
3341 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003342 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003343 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003344 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3345 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003346 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003347 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003348 pw.println(" mBatteryLevel=" + mBatteryLevel);
3349 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003350 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003351 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003352 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003353 pw.println(" mBootCompleted=" + mBootCompleted);
3354 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003355 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3356 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003357 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003358 pw.print(" mNotifyLongScheduled=");
3359 if (mNotifyLongScheduled == 0) {
3360 pw.print("(none)");
3361 } else {
3362 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3363 }
3364 pw.println();
3365 pw.print(" mNotifyLongDispatched=");
3366 if (mNotifyLongDispatched == 0) {
3367 pw.print("(none)");
3368 } else {
3369 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3370 }
3371 pw.println();
3372 pw.print(" mNotifyLongNextCheck=");
3373 if (mNotifyLongNextCheck == 0) {
3374 pw.print("(none)");
3375 } else {
3376 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3377 }
3378 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003379 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3380 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3381 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003382 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003383 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003384 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003385 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3386 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003387 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003388 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3389 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Calin Tatarua3805722018-08-09 16:41:28 +02003390 pw.println(" mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
Jeff Brown96307042012-07-27 15:51:34 -07003391 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3392 pw.println(" mLastUserActivityTimeNoChangeLights="
3393 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003394 pw.println(" mLastInteractivePowerHintTime="
3395 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003396 pw.println(" mLastScreenBrightnessBoostTime="
3397 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3398 pw.println(" mScreenBrightnessBoostInProgress="
3399 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003400 pw.println(" mDisplayReady=" + mDisplayReady);
3401 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003402 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003403
3404 pw.println();
3405 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003406 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3407 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3408 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3409 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003410 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3411 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003412 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3413 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3414 pw.println(" mTheaterModeEnabled="
3415 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003416 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3417 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003418 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003419 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3420 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3421 + mDreamsActivatedOnSleepByDefaultConfig);
3422 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3423 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003424 pw.println(" mDreamsEnabledOnBatteryConfig="
3425 + mDreamsEnabledOnBatteryConfig);
3426 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3427 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3428 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3429 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3430 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3431 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003432 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003433 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003434 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003435 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003436 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3437 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3438 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003439 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003440 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003441 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3442 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3443 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3444 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3445 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3446 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3447 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3448 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003449 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3450 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003451 pw.println(" mUserInactiveOverrideFromWindowManager="
3452 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003453 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3454 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003455 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003456 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3457 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003458 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3459 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3460 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003461 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003462 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003463 pw.println(" mForegroundProfile=" + mForegroundProfile);
Jeff Brown96307042012-07-27 15:51:34 -07003464
Pavel Grafov28939982017-10-03 15:11:52 +01003465 final long sleepTimeout = getSleepTimeoutLocked();
3466 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3467 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003468 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07003469 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003470 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3471 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3472
Jeff Brown96307042012-07-27 15:51:34 -07003473 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003474 pw.print("UID states (changing=");
3475 pw.print(mUidsChanging);
3476 pw.print(" changed=");
3477 pw.print(mUidsChanged);
3478 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003479 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003480 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003481 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003482 pw.print(": ");
3483 if (state.mActive) pw.print(" ACTIVE ");
3484 else pw.print("INACTIVE ");
3485 pw.print(" count=");
3486 pw.print(state.mNumWakeLocks);
3487 pw.print(" state=");
3488 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003489 }
3490
3491 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003492 pw.println("Looper state:");
3493 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3494
3495 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003496 pw.println("Wake Locks: size=" + mWakeLocks.size());
3497 for (WakeLock wl : mWakeLocks) {
3498 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003499 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003500
Jeff Brown96307042012-07-27 15:51:34 -07003501 pw.println();
3502 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3503 for (SuspendBlocker sb : mSuspendBlockers) {
3504 pw.println(" " + sb);
3505 }
3506
Jeff Brownc38c9be2012-10-04 13:16:19 -07003507 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003508 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003509
jackqdyulei455e90a2017-02-09 15:29:16 -08003510 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003511 mBatterySaverStateMachine.dump(pw);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08003512 mAttentionDetector.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003513
Pavel Grafov28939982017-10-03 15:11:52 +01003514 pw.println();
3515 final int numProfiles = mProfilePowerState.size();
3516 pw.println("Profile power states: size=" + numProfiles);
3517 for (int i = 0; i < numProfiles; i++) {
3518 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3519 pw.print(" mUserId=");
3520 pw.print(profile.mUserId);
3521 pw.print(" mScreenOffTimeout=");
3522 pw.print(profile.mScreenOffTimeout);
3523 pw.print(" mWakeLockSummary=");
3524 pw.print(profile.mWakeLockSummary);
3525 pw.print(" mLastUserActivityTime=");
3526 pw.print(profile.mLastUserActivityTime);
3527 pw.print(" mLockingNotified=");
3528 pw.println(profile.mLockingNotified);
3529 }
3530
Jeff Brown3b971592013-01-09 18:46:37 -08003531 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003532 }
3533
Jeff Brown3b971592013-01-09 18:46:37 -08003534 if (wcd != null) {
3535 wcd.dump(pw);
3536 }
Jeff Brown96307042012-07-27 15:51:34 -07003537 }
3538
Netta P958d0a52017-02-07 11:20:55 -08003539 private void dumpProto(FileDescriptor fd) {
3540 final WirelessChargerDetector wcd;
3541 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3542
3543 synchronized (mLock) {
3544 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003545 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3546 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3547 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3548 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3549 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3550 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003551 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003552 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003553 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003554 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3555 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3556 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3557 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3558 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003559 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003560 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003561 mHalAutoSuspendModeEnabled);
3562 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003563 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003564 mHalInteractiveModeEnabled);
3565
Kweku Adamse6b00c22017-10-23 16:46:45 -07003566 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003567 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003568 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003569 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3570 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003571 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003572 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3573 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003574 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003575 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3576 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003577 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003578 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3579 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003580 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003581 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3582 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003583 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003584 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3585 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003586 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003587 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3588 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003589 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003590 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3591 proto.end(activeWakeLocksToken);
3592
Kweku Adamse6b00c22017-10-23 16:46:45 -07003593 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3594 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3595 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003596
Kweku Adamse6b00c22017-10-23 16:46:45 -07003597 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003598 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003599 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003600 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3601 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003602 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003603 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3604 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003605 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003606 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3607 proto.end(userActivityToken);
3608
3609 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003610 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003611 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003612 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3613 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003614 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3615 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3616 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003617
3618 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003619 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003620 }
3621 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003622 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003623 }
3624
Kweku Adamse6b00c22017-10-23 16:46:45 -07003625 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3626 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3627 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003628 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003629 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003630 mLastUserActivityTimeNoChangeLights);
3631 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003632 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003633 mLastInteractivePowerHintTime);
3634 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003635 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003636 mLastScreenBrightnessBoostTime);
3637 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003638 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003639 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003640 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003641 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003642 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003643 mHoldingWakeLockSuspendBlocker);
3644 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003645 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003646 mHoldingDisplaySuspendBlocker);
3647
3648 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003649 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003650 proto.write(
3651 PowerServiceSettingsAndConfigurationDumpProto
3652 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3653 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3654 proto.write(
3655 PowerServiceSettingsAndConfigurationDumpProto
3656 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3657 mDecoupleHalInteractiveModeFromDisplayConfig);
3658 proto.write(
3659 PowerServiceSettingsAndConfigurationDumpProto
3660 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3661 mWakeUpWhenPluggedOrUnpluggedConfig);
3662 proto.write(
3663 PowerServiceSettingsAndConfigurationDumpProto
3664 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3665 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3666 proto.write(
3667 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3668 mTheaterModeEnabled);
3669 proto.write(
3670 PowerServiceSettingsAndConfigurationDumpProto
3671 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3672 mSuspendWhenScreenOffDueToProximityConfig);
3673 proto.write(
3674 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3675 mDreamsSupportedConfig);
3676 proto.write(
3677 PowerServiceSettingsAndConfigurationDumpProto
3678 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3679 mDreamsEnabledByDefaultConfig);
3680 proto.write(
3681 PowerServiceSettingsAndConfigurationDumpProto
3682 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3683 mDreamsActivatedOnSleepByDefaultConfig);
3684 proto.write(
3685 PowerServiceSettingsAndConfigurationDumpProto
3686 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3687 mDreamsActivatedOnDockByDefaultConfig);
3688 proto.write(
3689 PowerServiceSettingsAndConfigurationDumpProto
3690 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3691 mDreamsEnabledOnBatteryConfig);
3692 proto.write(
3693 PowerServiceSettingsAndConfigurationDumpProto
3694 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3695 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3696 proto.write(
3697 PowerServiceSettingsAndConfigurationDumpProto
3698 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3699 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3700 proto.write(
3701 PowerServiceSettingsAndConfigurationDumpProto
3702 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3703 mDreamsBatteryLevelDrainCutoffConfig);
3704 proto.write(
3705 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3706 mDreamsEnabledSetting);
3707 proto.write(
3708 PowerServiceSettingsAndConfigurationDumpProto
3709 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3710 mDreamsActivateOnSleepSetting);
3711 proto.write(
3712 PowerServiceSettingsAndConfigurationDumpProto
3713 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3714 mDreamsActivateOnDockSetting);
3715 proto.write(
3716 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08003717 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08003718 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003719 PowerServiceSettingsAndConfigurationDumpProto
3720 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3721 mMinimumScreenOffTimeoutConfig);
3722 proto.write(
3723 PowerServiceSettingsAndConfigurationDumpProto
3724 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3725 mMaximumScreenDimDurationConfig);
3726 proto.write(
3727 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3728 mMaximumScreenDimRatioConfig);
3729 proto.write(
3730 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3731 mScreenOffTimeoutSetting);
3732 proto.write(
3733 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3734 mSleepTimeoutSetting);
3735 proto.write(
3736 PowerServiceSettingsAndConfigurationDumpProto
3737 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003738 // Clamp to int32
3739 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003740 proto.write(
3741 PowerServiceSettingsAndConfigurationDumpProto
3742 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3743 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3744
3745 final long stayOnWhilePluggedInToken =
3746 proto.start(
3747 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3748 proto.write(
3749 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3750 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3751 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3752 proto.write(
3753 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3754 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3755 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3756 proto.write(
3757 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3758 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3759 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3760 != 0));
3761 proto.end(stayOnWhilePluggedInToken);
3762
3763 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003764 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3765 mScreenBrightnessModeSetting);
3766 proto.write(
3767 PowerServiceSettingsAndConfigurationDumpProto
3768 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3769 mScreenBrightnessOverrideFromWindowManager);
3770 proto.write(
3771 PowerServiceSettingsAndConfigurationDumpProto
3772 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3773 mUserActivityTimeoutOverrideFromWindowManager);
3774 proto.write(
3775 PowerServiceSettingsAndConfigurationDumpProto
3776 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
3777 mUserInactiveOverrideFromWindowManager);
3778 proto.write(
3779 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003780 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
3781 mDozeScreenStateOverrideFromDreamManager);
3782 proto.write(
3783 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003784 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
3785 mDrawWakeLockOverrideFromSidekick);
3786 proto.write(
3787 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003788 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
3789 mDozeScreenBrightnessOverrideFromDreamManager);
3790
3791 final long screenBrightnessSettingLimitsToken =
3792 proto.start(
3793 PowerServiceSettingsAndConfigurationDumpProto
3794 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
3795 proto.write(
3796 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3797 .SETTING_MINIMUM,
3798 mScreenBrightnessSettingMinimum);
3799 proto.write(
3800 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3801 .SETTING_MAXIMUM,
3802 mScreenBrightnessSettingMaximum);
3803 proto.write(
3804 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3805 .SETTING_DEFAULT,
3806 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08003807 proto.end(screenBrightnessSettingLimitsToken);
3808
3809 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003810 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
3811 mDoubleTapWakeEnabled);
3812 proto.write(
3813 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
3814 mIsVrModeEnabled);
3815 proto.end(settingsAndConfigurationToken);
3816
Pavel Grafov28939982017-10-03 15:11:52 +01003817 final long sleepTimeout = getSleepTimeoutLocked();
3818 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3819 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003820 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
3821 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
3822 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
3823 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
3824 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08003825
3826 for (int i = 0; i < mUidState.size(); i++) {
3827 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003828 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08003829 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003830 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
3831 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
3832 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
3833 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08003834 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
3835 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08003836 proto.end(uIDToken);
3837 }
3838
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003839 mBatterySaverStateMachine.dumpProto(proto,
3840 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
3841
Kweku Adamse6b00c22017-10-23 16:46:45 -07003842 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08003843
3844 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003845 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003846 }
3847
3848 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003849 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08003850 }
3851 wcd = mWirelessChargerDetector;
3852 }
3853
3854 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003855 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08003856 }
3857 proto.flush();
3858 }
3859
Daichi Hirono82ab9802016-03-02 13:23:29 +09003860 private void incrementBootCount() {
3861 synchronized (mLock) {
3862 int count;
3863 try {
3864 count = Settings.Global.getInt(
3865 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3866 } catch (SettingNotFoundException e) {
3867 count = 0;
3868 }
3869 Settings.Global.putInt(
3870 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3871 }
3872 }
3873
Jeff Brown96307042012-07-27 15:51:34 -07003874 private static WorkSource copyWorkSource(WorkSource workSource) {
3875 return workSource != null ? new WorkSource(workSource) : null;
3876 }
3877
Santos Cordon9b510a22018-08-24 16:42:54 +01003878 @VisibleForTesting
3879 final class BatteryReceiver extends BroadcastReceiver {
Jeff Brown96307042012-07-27 15:51:34 -07003880 @Override
3881 public void onReceive(Context context, Intent intent) {
3882 synchronized (mLock) {
3883 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003884 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003885 }
3886 }
3887
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003888 private final class DreamReceiver extends BroadcastReceiver {
3889 @Override
3890 public void onReceive(Context context, Intent intent) {
3891 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07003892 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003893 }
3894 }
3895 }
3896
Santos Cordon9b510a22018-08-24 16:42:54 +01003897 @VisibleForTesting
3898 final class UserSwitchedReceiver extends BroadcastReceiver {
Jeff Brownd4935962012-09-25 13:27:20 -07003899 @Override
3900 public void onReceive(Context context, Intent intent) {
3901 synchronized (mLock) {
3902 handleSettingsChangedLocked();
3903 }
3904 }
3905 }
3906
Jeff Brownec6aa592012-10-17 20:30:25 -07003907 private final class DockReceiver extends BroadcastReceiver {
3908 @Override
3909 public void onReceive(Context context, Intent intent) {
3910 synchronized (mLock) {
3911 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3912 Intent.EXTRA_DOCK_STATE_UNDOCKED);
3913 if (mDockState != dockState) {
3914 mDockState = dockState;
3915 mDirty |= DIRTY_DOCK_STATE;
3916 updatePowerStateLocked();
3917 }
3918 }
3919 }
3920 }
3921
Jeff Brown96307042012-07-27 15:51:34 -07003922 private final class SettingsObserver extends ContentObserver {
3923 public SettingsObserver(Handler handler) {
3924 super(handler);
3925 }
3926
3927 @Override
3928 public void onChange(boolean selfChange, Uri uri) {
3929 synchronized (mLock) {
3930 handleSettingsChangedLocked();
3931 }
3932 }
3933 }
3934
Ruben Brunkc7be3be2016-04-01 17:07:51 -07003935 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003936 @Override
3937 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07003938 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07003939
3940 synchronized (mLock) {
3941 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003942 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003943 mDirty |= DIRTY_VR_MODE_CHANGED;
3944 updatePowerStateLocked();
3945 }
3946 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003947 }
3948 };
3949
Jeff Brown96307042012-07-27 15:51:34 -07003950 /**
3951 * Handler for asynchronous operations performed by the power manager.
3952 */
3953 private final class PowerManagerHandler extends Handler {
3954 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07003955 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07003956 }
3957
3958 @Override
3959 public void handleMessage(Message msg) {
3960 switch (msg.what) {
3961 case MSG_USER_ACTIVITY_TIMEOUT:
3962 handleUserActivityTimeout();
3963 break;
3964 case MSG_SANDMAN:
3965 handleSandman();
3966 break;
Jeff Browne333e672014-10-28 13:48:55 -07003967 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
3968 handleScreenBrightnessBoostTimeout();
3969 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003970 case MSG_CHECK_FOR_LONG_WAKELOCKS:
3971 checkForLongWakeLocks();
3972 break;
Jeff Brown96307042012-07-27 15:51:34 -07003973 }
3974 }
3975 }
3976
3977 /**
3978 * Represents a wake lock that has been acquired by an application.
3979 */
3980 private final class WakeLock implements IBinder.DeathRecipient {
3981 public final IBinder mLock;
3982 public int mFlags;
3983 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003984 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07003985 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003986 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003987 public final int mOwnerUid;
3988 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003989 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003990 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07003991 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003992 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003993 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07003994
Dianne Hackborn713df152013-05-17 11:27:57 -07003995 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003996 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
3997 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07003998 mLock = lock;
3999 mFlags = flags;
4000 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004001 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07004002 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004003 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004004 mOwnerUid = ownerUid;
4005 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004006 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07004007 }
4008
4009 @Override
4010 public void binderDied() {
4011 PowerManagerService.this.handleWakeLockDeath(this);
4012 }
4013
4014 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4015 int ownerUid, int ownerPid) {
4016 return mFlags == flags
4017 && mTag.equals(tag)
4018 && hasSameWorkSource(workSource)
4019 && mOwnerUid == ownerUid
4020 && mOwnerPid == ownerPid;
4021 }
4022
Dianne Hackborn713df152013-05-17 11:27:57 -07004023 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004024 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07004025 if (!mPackageName.equals(packageName)) {
4026 throw new IllegalStateException("Existing wake lock package name changed: "
4027 + mPackageName + " to " + packageName);
4028 }
4029 if (mOwnerUid != ownerUid) {
4030 throw new IllegalStateException("Existing wake lock uid changed: "
4031 + mOwnerUid + " to " + ownerUid);
4032 }
4033 if (mOwnerPid != ownerPid) {
4034 throw new IllegalStateException("Existing wake lock pid changed: "
4035 + mOwnerPid + " to " + ownerPid);
4036 }
Jeff Brown96307042012-07-27 15:51:34 -07004037 mFlags = flags;
4038 mTag = tag;
4039 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004040 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004041 }
4042
4043 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00004044 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07004045 }
4046
4047 public void updateWorkSource(WorkSource workSource) {
4048 mWorkSource = copyWorkSource(workSource);
4049 }
4050
4051 @Override
4052 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004053 StringBuilder sb = new StringBuilder();
4054 sb.append(getLockLevelString());
4055 sb.append(" '");
4056 sb.append(mTag);
4057 sb.append("'");
4058 sb.append(getLockFlagsString());
4059 if (mDisabled) {
4060 sb.append(" DISABLED");
4061 }
4062 if (mNotifiedAcquired) {
4063 sb.append(" ACQ=");
4064 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4065 }
4066 if (mNotifiedLong) {
4067 sb.append(" LONG");
4068 }
4069 sb.append(" (uid=");
4070 sb.append(mOwnerUid);
4071 if (mOwnerPid != 0) {
4072 sb.append(" pid=");
4073 sb.append(mOwnerPid);
4074 }
4075 if (mWorkSource != null) {
4076 sb.append(" ws=");
4077 sb.append(mWorkSource);
4078 }
4079 sb.append(")");
4080 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004081 }
4082
Netta P958d0a52017-02-07 11:20:55 -08004083 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4084 final long wakeLockToken = proto.start(fieldId);
4085 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4086 proto.write(WakeLockProto.TAG, mTag);
4087
4088 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4089 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4090 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4091 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4092 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4093 proto.end(wakeLockFlagsToken);
4094
4095 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4096 if (mNotifiedAcquired) {
4097 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4098 }
4099 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4100 proto.write(WakeLockProto.UID, mOwnerUid);
4101 proto.write(WakeLockProto.PID, mOwnerPid);
4102
4103 if (mWorkSource != null) {
4104 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4105 }
4106 proto.end(wakeLockToken);
4107 }
4108
Jeff Brown26875502014-01-30 21:47:47 -08004109 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004110 private String getLockLevelString() {
4111 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4112 case PowerManager.FULL_WAKE_LOCK:
4113 return "FULL_WAKE_LOCK ";
4114 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4115 return "SCREEN_BRIGHT_WAKE_LOCK ";
4116 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4117 return "SCREEN_DIM_WAKE_LOCK ";
4118 case PowerManager.PARTIAL_WAKE_LOCK:
4119 return "PARTIAL_WAKE_LOCK ";
4120 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4121 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004122 case PowerManager.DOZE_WAKE_LOCK:
4123 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004124 case PowerManager.DRAW_WAKE_LOCK:
4125 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004126 default:
4127 return "??? ";
4128 }
4129 }
4130
4131 private String getLockFlagsString() {
4132 String result = "";
4133 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4134 result += " ACQUIRE_CAUSES_WAKEUP";
4135 }
4136 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4137 result += " ON_AFTER_RELEASE";
4138 }
4139 return result;
4140 }
4141 }
4142
4143 private final class SuspendBlockerImpl implements SuspendBlocker {
4144 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004145 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004146 private int mReferenceCount;
4147
4148 public SuspendBlockerImpl(String name) {
4149 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004150 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004151 }
4152
4153 @Override
4154 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004155 try {
Jeff Brown96307042012-07-27 15:51:34 -07004156 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004157 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004158 + "\" was finalized without being released!");
4159 mReferenceCount = 0;
Santos Cordon64a6e612018-08-22 19:27:04 +01004160 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004161 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004162 }
4163 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004164 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004165 }
4166 }
4167
Craig Mautner75fc9de2012-06-18 16:53:27 -07004168 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004169 public void acquire() {
4170 synchronized (this) {
4171 mReferenceCount += 1;
4172 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004173 if (DEBUG_SPEW) {
4174 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4175 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004176 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +01004177 mNativeWrapper.nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004178 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004179 }
4180 }
4181
Craig Mautner75fc9de2012-06-18 16:53:27 -07004182 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004183 public void release() {
4184 synchronized (this) {
4185 mReferenceCount -= 1;
4186 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004187 if (DEBUG_SPEW) {
4188 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4189 }
Santos Cordon64a6e612018-08-22 19:27:04 +01004190 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004191 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004192 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004193 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004194 + "\" was released without being acquired!", new Throwable());
4195 mReferenceCount = 0;
4196 }
4197 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004198 }
Jeff Brown96307042012-07-27 15:51:34 -07004199
4200 @Override
4201 public String toString() {
4202 synchronized (this) {
4203 return mName + ": ref count=" + mReferenceCount;
4204 }
4205 }
Netta P958d0a52017-02-07 11:20:55 -08004206
4207 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4208 final long sbToken = proto.start(fieldId);
4209 synchronized (this) {
4210 proto.write(SuspendBlockerProto.NAME, mName);
4211 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4212 }
4213 proto.end(sbToken);
4214 }
Jeff Brown96307042012-07-27 15:51:34 -07004215 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004216
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004217 static final class UidState {
4218 final int mUid;
4219 int mNumWakeLocks;
4220 int mProcState;
4221 boolean mActive;
4222
4223 UidState(int uid) {
4224 mUid = uid;
4225 }
4226 }
4227
Santos Cordon64a6e612018-08-22 19:27:04 +01004228 @VisibleForTesting
4229 final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004230 @Override
4231 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4232 FileDescriptor err, String[] args, ShellCallback callback,
4233 ResultReceiver resultReceiver) {
4234 (new PowerManagerShellCommand(this)).exec(
4235 this, in, out, err, args, callback, resultReceiver);
4236 }
4237
Jeff Brown6f357d32014-01-15 20:40:55 -08004238 @Override // Binder call
4239 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4240 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004241 if (uid < 0) {
4242 uid = Binder.getCallingUid();
4243 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004244 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004245 }
4246
4247 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004248 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004249 if (!mSystemReady) {
4250 // Service not ready yet, so who the heck cares about power hints, bah.
4251 return;
4252 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004254 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004255 }
4256
4257 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004258 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004259 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004260 if (lock == null) {
4261 throw new IllegalArgumentException("lock must not be null");
4262 }
4263 if (packageName == null) {
4264 throw new IllegalArgumentException("packageName must not be null");
4265 }
4266 PowerManager.validateWakeLockParameters(flags, tag);
4267
4268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004269 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4270 mContext.enforceCallingOrSelfPermission(
4271 android.Manifest.permission.DEVICE_POWER, null);
4272 }
Narayan Kamath81822022017-12-08 11:56:01 +00004273 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004274 mContext.enforceCallingOrSelfPermission(
4275 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4276 } else {
4277 ws = null;
4278 }
4279
4280 final int uid = Binder.getCallingUid();
4281 final int pid = Binder.getCallingPid();
4282 final long ident = Binder.clearCallingIdentity();
4283 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004284 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004285 } finally {
4286 Binder.restoreCallingIdentity(ident);
4287 }
4288 }
4289
4290 @Override // Binder call
4291 public void releaseWakeLock(IBinder lock, int flags) {
4292 if (lock == null) {
4293 throw new IllegalArgumentException("lock must not be null");
4294 }
4295
4296 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4297
4298 final long ident = Binder.clearCallingIdentity();
4299 try {
4300 releaseWakeLockInternal(lock, flags);
4301 } finally {
4302 Binder.restoreCallingIdentity(ident);
4303 }
4304 }
4305
4306 @Override // Binder call
4307 public void updateWakeLockUids(IBinder lock, int[] uids) {
4308 WorkSource ws = null;
4309
4310 if (uids != null) {
4311 ws = new WorkSource();
4312 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4313 // one at a time?
4314 for (int i = 0; i < uids.length; i++) {
4315 ws.add(uids[i]);
4316 }
4317 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004318 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004319 }
4320
4321 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004322 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004323 if (lock == null) {
4324 throw new IllegalArgumentException("lock must not be null");
4325 }
4326
4327 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004328 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004329 mContext.enforceCallingOrSelfPermission(
4330 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4331 } else {
4332 ws = null;
4333 }
4334
Dianne Hackbornd953c532014-08-16 18:17:38 -07004335 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004336 final long ident = Binder.clearCallingIdentity();
4337 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004338 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004339 } finally {
4340 Binder.restoreCallingIdentity(ident);
4341 }
4342 }
4343
4344 @Override // Binder call
4345 public boolean isWakeLockLevelSupported(int level) {
4346 final long ident = Binder.clearCallingIdentity();
4347 try {
4348 return isWakeLockLevelSupportedInternal(level);
4349 } finally {
4350 Binder.restoreCallingIdentity(ident);
4351 }
4352 }
4353
4354 @Override // Binder call
4355 public void userActivity(long eventTime, int event, int flags) {
4356 final long now = SystemClock.uptimeMillis();
4357 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004358 != PackageManager.PERMISSION_GRANTED
4359 && mContext.checkCallingOrSelfPermission(
4360 android.Manifest.permission.USER_ACTIVITY)
4361 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004362 // Once upon a time applications could call userActivity().
4363 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4364 // request instead of throwing a SecurityException so we don't break old apps.
4365 synchronized (mLock) {
4366 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4367 mLastWarningAboutUserActivityPermission = now;
4368 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004369 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4370 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004371 + " pid=" + Binder.getCallingPid()
4372 + " uid=" + Binder.getCallingUid());
4373 }
4374 }
4375 return;
4376 }
4377
Jim Millerdca15d22015-06-16 20:55:13 -07004378 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004379 throw new IllegalArgumentException("event time must not be in the future");
4380 }
4381
4382 final int uid = Binder.getCallingUid();
4383 final long ident = Binder.clearCallingIdentity();
4384 try {
4385 userActivityInternal(eventTime, event, flags, uid);
4386 } finally {
4387 Binder.restoreCallingIdentity(ident);
4388 }
4389 }
4390
4391 @Override // Binder call
Michael Wrighte3001042019-02-05 00:13:14 +00004392 public void wakeUp(long eventTime, @WakeReason int reason, String details,
4393 String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004394 if (eventTime > SystemClock.uptimeMillis()) {
4395 throw new IllegalArgumentException("event time must not be in the future");
4396 }
4397
4398 mContext.enforceCallingOrSelfPermission(
4399 android.Manifest.permission.DEVICE_POWER, null);
4400
Jeff Brownc12035c2014-08-13 18:52:25 -07004401 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004402 final long ident = Binder.clearCallingIdentity();
4403 try {
Michael Wrighte3001042019-02-05 00:13:14 +00004404 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004405 } finally {
4406 Binder.restoreCallingIdentity(ident);
4407 }
4408 }
4409
4410 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004411 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004412 if (eventTime > SystemClock.uptimeMillis()) {
4413 throw new IllegalArgumentException("event time must not be in the future");
4414 }
4415
4416 mContext.enforceCallingOrSelfPermission(
4417 android.Manifest.permission.DEVICE_POWER, null);
4418
Jeff Brownc12035c2014-08-13 18:52:25 -07004419 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004420 final long ident = Binder.clearCallingIdentity();
4421 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004422 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004423 } finally {
4424 Binder.restoreCallingIdentity(ident);
4425 }
4426 }
4427
4428 @Override // Binder call
4429 public void nap(long eventTime) {
4430 if (eventTime > SystemClock.uptimeMillis()) {
4431 throw new IllegalArgumentException("event time must not be in the future");
4432 }
4433
4434 mContext.enforceCallingOrSelfPermission(
4435 android.Manifest.permission.DEVICE_POWER, null);
4436
Jeff Brownc12035c2014-08-13 18:52:25 -07004437 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004438 final long ident = Binder.clearCallingIdentity();
4439 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004440 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004441 } finally {
4442 Binder.restoreCallingIdentity(ident);
4443 }
4444 }
4445
4446 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004447 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004448 final long ident = Binder.clearCallingIdentity();
4449 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004450 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004451 } finally {
4452 Binder.restoreCallingIdentity(ident);
4453 }
4454 }
4455
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004456 @Override // Binder call
4457 public boolean isPowerSaveMode() {
4458 final long ident = Binder.clearCallingIdentity();
4459 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004460 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004461 } finally {
4462 Binder.restoreCallingIdentity(ident);
4463 }
4464 }
4465
jackqdyulei455e90a2017-02-09 15:29:16 -08004466 // Binder call
4467 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4468 final long ident = Binder.clearCallingIdentity();
4469 try {
Kweku Adams9f488e22019-01-14 16:25:08 -08004470 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
jackqdyulei455e90a2017-02-09 15:29:16 -08004471 } finally {
4472 Binder.restoreCallingIdentity(ident);
4473 }
4474 }
4475
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004476 @Override // Binder call
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004477 public boolean setPowerSaveMode(boolean enabled) {
Salvador Martineza80bbab2018-09-24 10:36:11 -07004478 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4479 != PackageManager.PERMISSION_GRANTED) {
4480 mContext.enforceCallingOrSelfPermission(
4481 android.Manifest.permission.DEVICE_POWER, null);
4482 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004483 final long ident = Binder.clearCallingIdentity();
4484 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004485 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004486 } finally {
4487 Binder.restoreCallingIdentity(ident);
4488 }
4489 }
4490
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004491 @Override // Binder call
Salvador Martinez812ea752018-10-19 13:03:20 -07004492 public boolean setDynamicPowerSavings(boolean dynamicPowerSavingsEnabled,
4493 int disableThreshold) {
4494 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4495 "updateDynamicPowerSavings");
4496 final long ident = Binder.clearCallingIdentity();
4497 try {
4498 final ContentResolver resolver = mContext.getContentResolver();
4499 boolean success = Settings.Global.putInt(resolver,
4500 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4501 disableThreshold);
4502 if (success) {
4503 // abort updating if we weren't able to succeed on the threshold
4504 success &= Settings.Global.putInt(resolver,
4505 Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
4506 dynamicPowerSavingsEnabled ? 1 : 0);
4507 }
4508 return success;
4509 } finally {
4510 Binder.restoreCallingIdentity(ident);
4511 }
4512 }
4513
4514 @Override // Binder call
Kweku Adams9f488e22019-01-14 16:25:08 -08004515 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4516 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4517 != PackageManager.PERMISSION_GRANTED) {
4518 mContext.enforceCallingOrSelfPermission(
4519 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4520 }
4521 final long ident = Binder.clearCallingIdentity();
4522 try {
4523 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4524 } finally {
4525 Binder.restoreCallingIdentity(ident);
4526 }
4527 }
4528
4529 @Override // Binder call
4530 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4531 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4532 != PackageManager.PERMISSION_GRANTED) {
4533 mContext.enforceCallingOrSelfPermission(
4534 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4535 }
4536 final long ident = Binder.clearCallingIdentity();
4537 try {
4538 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4539 } finally {
4540 Binder.restoreCallingIdentity(ident);
4541 }
4542 }
4543
4544 @Override // Binder call
Salvador Martinez812ea752018-10-19 13:03:20 -07004545 public int getPowerSaveMode() {
4546 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4547 final long ident = Binder.clearCallingIdentity();
4548 try {
4549 return Settings.Global.getInt(mContext.getContentResolver(),
4550 Settings.Global.AUTOMATIC_POWER_SAVER_MODE,
4551 PowerManager.POWER_SAVER_MODE_PERCENTAGE);
4552 } finally {
4553 Binder.restoreCallingIdentity(ident);
4554 }
4555 }
4556
4557 @Override // Binder call
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004558 public boolean isDeviceIdleMode() {
4559 final long ident = Binder.clearCallingIdentity();
4560 try {
4561 return isDeviceIdleModeInternal();
4562 } finally {
4563 Binder.restoreCallingIdentity(ident);
4564 }
4565 }
4566
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004567 @Override // Binder call
4568 public boolean isLightDeviceIdleMode() {
4569 final long ident = Binder.clearCallingIdentity();
4570 try {
4571 return isLightDeviceIdleModeInternal();
4572 } finally {
4573 Binder.restoreCallingIdentity(ident);
4574 }
4575 }
4576
Jeff Brown6f357d32014-01-15 20:40:55 -08004577 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004578 * Gets the reason for the last time the phone had to reboot.
4579 *
4580 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004581 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004582 */
4583 @Override // Binder call
4584 public int getLastShutdownReason() {
4585 mContext.enforceCallingOrSelfPermission(
4586 android.Manifest.permission.DEVICE_POWER, null);
4587
4588 final long ident = Binder.clearCallingIdentity();
4589 try {
Mark Salyzyn74ce8b32018-06-05 09:06:54 -07004590 return getLastShutdownReasonInternal(REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004591 } finally {
4592 Binder.restoreCallingIdentity(ident);
4593 }
4594 }
4595
Calin Tatarua3805722018-08-09 16:41:28 +02004596 @Override // Binder call
4597 public int getLastSleepReason() {
4598 mContext.enforceCallingOrSelfPermission(
4599 android.Manifest.permission.DEVICE_POWER, null);
4600
4601 final long ident = Binder.clearCallingIdentity();
4602 try {
4603 return getLastSleepReasonInternal();
4604 } finally {
4605 Binder.restoreCallingIdentity(ident);
4606 }
4607 }
4608
Salvador Martineza6f7b252017-04-10 10:46:15 -07004609 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004610 * Reboots the device.
4611 *
4612 * @param confirm If true, shows a reboot confirmation dialog.
4613 * @param reason The reason for the reboot, or null if none.
4614 * @param wait If true, this call waits for the reboot to complete and does not return.
4615 */
4616 @Override // Binder call
4617 public void reboot(boolean confirm, String reason, boolean wait) {
4618 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004619 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4620 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004621 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4622 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004623
4624 final long ident = Binder.clearCallingIdentity();
4625 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004626 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4627 } finally {
4628 Binder.restoreCallingIdentity(ident);
4629 }
4630 }
4631
4632 /**
4633 * Reboots the device into safe mode
4634 *
4635 * @param confirm If true, shows a reboot confirmation dialog.
4636 * @param wait If true, this call waits for the reboot to complete and does not return.
4637 */
4638 @Override // Binder call
4639 public void rebootSafeMode(boolean confirm, boolean wait) {
4640 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4641
4642 final long ident = Binder.clearCallingIdentity();
4643 try {
4644 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4645 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004646 } finally {
4647 Binder.restoreCallingIdentity(ident);
4648 }
4649 }
4650
4651 /**
4652 * Shuts down the device.
4653 *
4654 * @param confirm If true, shows a shutdown confirmation dialog.
4655 * @param wait If true, this call waits for the shutdown to complete and does not return.
4656 */
4657 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004658 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004659 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4660
4661 final long ident = Binder.clearCallingIdentity();
4662 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004663 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004664 } finally {
4665 Binder.restoreCallingIdentity(ident);
4666 }
4667 }
4668
4669 /**
4670 * Crash the runtime (causing a complete restart of the Android framework).
4671 * Requires REBOOT permission. Mostly for testing. Should not return.
4672 */
4673 @Override // Binder call
4674 public void crash(String message) {
4675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4676
4677 final long ident = Binder.clearCallingIdentity();
4678 try {
4679 crashInternal(message);
4680 } finally {
4681 Binder.restoreCallingIdentity(ident);
4682 }
4683 }
4684
4685 /**
4686 * Set the setting that determines whether the device stays on when plugged in.
4687 * The argument is a bit string, with each bit specifying a power source that,
4688 * when the device is connected to that source, causes the device to stay on.
4689 * See {@link android.os.BatteryManager} for the list of power sources that
4690 * can be specified. Current values include
4691 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4692 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4693 *
4694 * Used by "adb shell svc power stayon ..."
4695 *
4696 * @param val an {@code int} containing the bits that specify which power sources
4697 * should cause the device to stay on.
4698 */
4699 @Override // Binder call
4700 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004701 int uid = Binder.getCallingUid();
4702 // if uid is of root's, we permit this operation straight away
4703 if (uid != Process.ROOT_UID) {
4704 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4705 Settings.getPackageNameForUid(mContext, uid), true)) {
4706 return;
4707 }
4708 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004709
4710 final long ident = Binder.clearCallingIdentity();
4711 try {
4712 setStayOnSettingInternal(val);
4713 } finally {
4714 Binder.restoreCallingIdentity(ident);
4715 }
4716 }
4717
4718 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004719 * Used by the phone application to make the attention LED flash when ringing.
4720 */
4721 @Override // Binder call
4722 public void setAttentionLight(boolean on, int color) {
4723 mContext.enforceCallingOrSelfPermission(
4724 android.Manifest.permission.DEVICE_POWER, null);
4725
4726 final long ident = Binder.clearCallingIdentity();
4727 try {
4728 setAttentionLightInternal(on, color);
4729 } finally {
4730 Binder.restoreCallingIdentity(ident);
4731 }
4732 }
4733
4734 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08004735 public void setDozeAfterScreenOff(boolean on) {
4736 mContext.enforceCallingOrSelfPermission(
4737 android.Manifest.permission.DEVICE_POWER, null);
4738
4739 final long ident = Binder.clearCallingIdentity();
4740 try {
4741 setDozeAfterScreenOffInternal(on);
4742 } finally {
4743 Binder.restoreCallingIdentity(ident);
4744 }
4745 }
4746
4747 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004748 public void boostScreenBrightness(long eventTime) {
4749 if (eventTime > SystemClock.uptimeMillis()) {
4750 throw new IllegalArgumentException("event time must not be in the future");
4751 }
4752
4753 mContext.enforceCallingOrSelfPermission(
4754 android.Manifest.permission.DEVICE_POWER, null);
4755
4756 final int uid = Binder.getCallingUid();
4757 final long ident = Binder.clearCallingIdentity();
4758 try {
4759 boostScreenBrightnessInternal(eventTime, uid);
4760 } finally {
4761 Binder.restoreCallingIdentity(ident);
4762 }
4763 }
4764
4765 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004766 public boolean isScreenBrightnessBoosted() {
4767 final long ident = Binder.clearCallingIdentity();
4768 try {
4769 return isScreenBrightnessBoostedInternal();
4770 } finally {
4771 Binder.restoreCallingIdentity(ident);
4772 }
4773 }
4774
Santos Cordon12f92eb2019-02-01 21:28:47 +00004775 @Override // binder call
4776 public boolean forceSuspend() {
4777 mContext.enforceCallingOrSelfPermission(
4778 android.Manifest.permission.DEVICE_POWER, null);
4779
4780 final int uid = Binder.getCallingUid();
4781 final long ident = Binder.clearCallingIdentity();
4782 try {
4783 return forceSuspendInternal(uid);
4784 } finally {
4785 Binder.restoreCallingIdentity(ident);
4786 }
4787 }
4788
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004789 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004790 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004791 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08004792
4793 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08004794
4795 boolean isDumpProto = false;
4796 for (String arg : args) {
4797 if (arg.equals("--proto")) {
4798 isDumpProto = true;
4799 }
4800 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004801 try {
Netta P958d0a52017-02-07 11:20:55 -08004802 if (isDumpProto) {
4803 dumpProto(fd);
4804 } else {
4805 dumpInternal(pw);
4806 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004807 } finally {
4808 Binder.restoreCallingIdentity(ident);
4809 }
4810 }
4811 }
4812
Salvador Martineza6f7b252017-04-10 10:46:15 -07004813 @VisibleForTesting
Santos Cordon64a6e612018-08-22 19:27:04 +01004814 BinderService getBinderServiceInstance() {
4815 return mBinderService;
4816 }
4817
4818 @VisibleForTesting
4819 LocalService getLocalServiceInstance() {
4820 return mLocalService;
4821 }
4822
4823 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004824 // lastRebootReasonProperty argument to permit testing
4825 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
4826 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01004827 if (line == null) {
4828 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4829 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07004830 switch (line) {
4831 case REASON_SHUTDOWN:
4832 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
4833 case REASON_REBOOT:
4834 return PowerManager.SHUTDOWN_REASON_REBOOT;
4835 case REASON_USERREQUESTED:
4836 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
4837 case REASON_THERMAL_SHUTDOWN:
4838 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07004839 case REASON_LOW_BATTERY:
4840 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
4841 case REASON_BATTERY_THERMAL_STATE:
4842 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07004843 default:
4844 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4845 }
4846 }
4847
Calin Tatarua3805722018-08-09 16:41:28 +02004848 private int getLastSleepReasonInternal() {
4849 synchronized (mLock) {
4850 return mLastSleepReason;
4851 }
4852 }
4853
Jeff Brown4ccb8232014-01-16 22:16:42 -08004854 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08004855 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004856 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
4857 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4858 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4859 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08004860 }
Jeff Brown970d4132014-07-19 11:33:47 -07004861 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08004862 }
4863
Jeff Brown6f357d32014-01-15 20:40:55 -08004864 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004865 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
4866 switch (screenState) {
4867 case Display.STATE_UNKNOWN:
4868 case Display.STATE_OFF:
4869 case Display.STATE_DOZE:
4870 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07004871 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07004872 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07004873 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07004874 break;
4875 default:
4876 screenState = Display.STATE_UNKNOWN;
4877 break;
4878 }
4879 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4880 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4881 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4882 }
4883 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
4884 }
4885
Jeff Brown6f357d32014-01-15 20:40:55 -08004886 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07004887 public void setUserInactiveOverrideFromWindowManager() {
4888 setUserInactiveOverrideFromWindowManagerInternal();
4889 }
4890
4891 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08004892 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07004893 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08004894 }
4895
4896 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004897 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
4898 setDrawWakeLockOverrideFromSidekickInternal(keepState);
4899 }
4900
4901 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01004902 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
4903 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08004904 }
4905
4906 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08004907 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Kweku Adams9f488e22019-01-14 16:25:08 -08004908 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004909 }
4910
4911 @Override
4912 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08004913 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004914 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004915
4916 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004917 public boolean setDeviceIdleMode(boolean enabled) {
4918 return setDeviceIdleModeInternal(enabled);
4919 }
4920
4921 @Override
4922 public boolean setLightDeviceIdleMode(boolean enabled) {
4923 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004924 }
4925
4926 @Override
4927 public void setDeviceIdleWhitelist(int[] appids) {
4928 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004929 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004930
4931 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004932 public void setDeviceIdleTempWhitelist(int[] appids) {
4933 setDeviceIdleTempWhitelistInternal(appids);
4934 }
4935
4936 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004937 public void startUidChanges() {
4938 startUidChangesInternal();
4939 }
4940
4941 @Override
4942 public void finishUidChanges() {
4943 finishUidChangesInternal();
4944 }
4945
4946 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004947 public void updateUidProcState(int uid, int procState) {
4948 updateUidProcStateInternal(uid, procState);
4949 }
4950
4951 @Override
4952 public void uidGone(int uid) {
4953 uidGoneInternal(uid);
4954 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01004955
4956 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004957 public void uidActive(int uid) {
4958 uidActiveInternal(uid);
4959 }
4960
4961 @Override
4962 public void uidIdle(int uid) {
4963 uidIdleInternal(uid);
4964 }
4965
4966 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01004967 public void powerHint(int hintId, int data) {
4968 powerHintInternal(hintId, data);
4969 }
Alex Kershaw2418ea92018-10-19 17:17:49 +01004970
4971 @Override
4972 public boolean wasDeviceIdleFor(long ms) {
4973 return wasDeviceIdleForInternal(ms);
4974 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004976}