blob: fce7f049107ba4d07f01ad43d3fe02a55437ed19 [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;
Santos Cordon623526b2019-04-09 17:02:38 +010055import android.os.PowerManager.WakeData;
Michael Wrighte3001042019-02-05 00:13:14 +000056import android.os.PowerManager.WakeReason;
Jeff Brown6f357d32014-01-15 20:40:55 -080057import android.os.PowerManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080058import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Process;
60import android.os.RemoteException;
Jocelyn Dangf2c38c12017-03-31 14:03:37 -070061import android.os.ResultReceiver;
62import android.os.ShellCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070064import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070065import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070066import android.os.UserHandle;
Christine Franks732c0432017-06-23 18:12:46 -070067import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070068import android.os.WorkSource;
Narayan Kamath2f916ed2017-12-29 13:02:15 +000069import android.os.WorkSource.WorkChain;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.provider.Settings;
Daichi Hirono82ab9802016-03-02 13:23:29 +090071import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080072import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070073import android.service.vr.IVrManager;
74import android.service.vr.IVrStateCallbacks;
Dianne Hackborn0ef403e2017-01-24 18:22:15 -080075import android.util.KeyValueListParser;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070076import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080077import android.util.Slog;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -070078import android.util.SparseArray;
Jeff Brown96307042012-07-27 15:51:34 -070079import android.util.TimeUtils;
Netta P958d0a52017-02-07 11:20:55 -080080import android.util.proto.ProtoOutputStream;
Jeff Brown037c33e2014-04-09 00:31:55 -070081import android.view.Display;
Makoto Onukiaae89532017-11-08 14:32:03 -080082
jackqdyulei92681e82017-02-28 11:26:28 -080083import com.android.internal.annotations.VisibleForTesting;
Jason Monkafae4bd2015-12-15 14:20:06 -050084import com.android.internal.app.IAppOpsService;
85import com.android.internal.app.IBatteryStats;
86import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060087import com.android.internal.util.DumpUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050088import com.android.server.EventLogTags;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060089import com.android.server.LockGuard;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070090import com.android.server.RescueParty;
Jason Monkafae4bd2015-12-15 14:20:06 -050091import com.android.server.ServiceThread;
92import com.android.server.SystemService;
Michael Wright64c820d2017-03-21 12:36:55 +000093import com.android.server.UiThread;
Jason Monkafae4bd2015-12-15 14:20:06 -050094import com.android.server.Watchdog;
95import com.android.server.am.BatteryStatsService;
96import com.android.server.lights.Light;
97import com.android.server.lights.LightsManager;
Adrian Roose99bc052017-11-20 17:55:31 +010098import com.android.server.policy.WindowManagerPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -080099import com.android.server.power.batterysaver.BatterySaverController;
Kweku Adams7fb72a42019-01-08 16:08:49 -0800100import com.android.server.power.batterysaver.BatterySaverPolicy;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700101import com.android.server.power.batterysaver.BatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700102import com.android.server.power.batterysaver.BatterySavingStats;
Makoto Onuki66a78122017-11-14 15:03:21 -0800103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.io.FileDescriptor;
105import java.io.PrintWriter;
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700106import java.lang.annotation.Retention;
107import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.ArrayList;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700109import java.util.Arrays;
Narayan Kamath607223f2018-02-19 14:09:02 +0000110import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Jeff Brown96307042012-07-27 15:51:34 -0700112/**
113 * The power manager service is responsible for coordinating power management
114 * functions on the device.
115 */
Jeff Brown2175e9c2014-09-12 16:11:07 -0700116public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -0700117 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Santos Cordon4ddb8012017-09-20 15:25:44 -0700120 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700121 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700122
Jeff Brown96307042012-07-27 15:51:34 -0700123 // Message: Sent when a user activity timeout occurs to update the power state.
124 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800125 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700126 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700127 // Message: Sent when the screen brightness boost expires.
128 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700129 // Message: Polling to look for long held wake locks.
130 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Robert Horvath5560f382019-07-10 10:46:38 +0200131 // Message: Sent when an attentive timeout occurs to update the power state.
132 private static final int MSG_ATTENTIVE_TIMEOUT = 5;
Jeff Brown7304c342012-05-11 18:42:42 -0700133
Jeff Brown96307042012-07-27 15:51:34 -0700134 // Dirty bit: mWakeLocks changed
135 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
136 // Dirty bit: mWakefulness changed
137 private static final int DIRTY_WAKEFULNESS = 1 << 1;
138 // Dirty bit: user activity was poked or may have timed out
139 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
140 // Dirty bit: actual display power state was updated asynchronously
141 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
142 // Dirty bit: mBootCompleted changed
143 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
144 // Dirty bit: settings changed
145 private static final int DIRTY_SETTINGS = 1 << 5;
146 // Dirty bit: mIsPowered changed
147 private static final int DIRTY_IS_POWERED = 1 << 6;
148 // Dirty bit: mStayOn changed
149 private static final int DIRTY_STAY_ON = 1 << 7;
150 // Dirty bit: battery state changed
151 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700152 // Dirty bit: proximity state changed
153 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700154 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700155 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700156 // Dirty bit: brightness boost changed
157 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800158 // Dirty bit: sQuiescent changed
159 private static final int DIRTY_QUIESCENT = 1 << 12;
Santos Cordon3107d292016-09-20 15:50:35 -0700160 // Dirty bit: VR Mode enabled changed
161 private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
Robert Horvath5560f382019-07-10 10:46:38 +0200162 // Dirty bit: attentive timer may have timed out
163 private static final int DIRTY_ATTENTIVE = 1 << 14;
Jeff Brown7304c342012-05-11 18:42:42 -0700164
Jeff Brown96307042012-07-27 15:51:34 -0700165 // Summarizes the state of all active wakelocks.
166 private static final int WAKE_LOCK_CPU = 1 << 0;
167 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
168 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
169 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
170 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700171 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800172 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800173 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
Jeff Brown96307042012-07-27 15:51:34 -0700175 // Summarizes the user activity state.
176 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
177 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700178 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Jeff Brown27736f52014-05-20 17:17:10 -0700180 // Default timeout in milliseconds. This is only used until the settings
181 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700182 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700183 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700184
Jeff Browne333e672014-10-28 13:48:55 -0700185 // Screen brightness boost timeout.
186 // Hardcoded for now until we decide what the right policy should be.
187 // This should perhaps be a setting.
188 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
189
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700190 // How long a partial wake lock must be held until we consider it a long wake lock.
191 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
192
Jason Monk27bbb2d2015-03-31 16:46:39 -0400193 // Power features defined in hardware/libhardware/include/hardware/power.h.
194 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
195
196 // Default setting for double tap to wake.
197 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
198
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800199 // System property indicating that the screen should remain off until an explicit user action
200 private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
201
Christine Franks732c0432017-06-23 18:12:46 -0700202 // System Property indicating that retail demo mode is currently enabled.
203 private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
204
Wei Wang72b77cc2019-02-07 14:10:23 -0800205 // Possible reasons for shutting down or reboot for use in REBOOT_PROPERTY(sys.boot.reason)
206 // which is set by bootstat
Salvador Martineza6f7b252017-04-10 10:46:15 -0700207 private static final String REASON_SHUTDOWN = "shutdown";
208 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700209 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
210 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700211 private static final String REASON_LOW_BATTERY = "shutdown,battery";
212 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700213
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700214 private static final String TRACE_SCREEN_ON = "Screen turning on";
215
216 /** If turning screen on takes more than this long, we show a warning on logcat. */
217 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
218
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700219 /** Constants for {@link #shutdownOrRebootInternal} */
220 @Retention(RetentionPolicy.SOURCE)
221 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
222 public @interface HaltMode {}
223 private static final int HALT_MODE_SHUTDOWN = 0;
224 private static final int HALT_MODE_REBOOT = 1;
225 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
226
Mark Salyzyn74ce8b32018-06-05 09:06:54 -0700227 // property for last reboot reason
228 private static final String REBOOT_PROPERTY = "sys.boot.reason";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700229
Jeff Brownb880d882014-02-10 19:47:07 -0800230 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700231 private final ServiceThread mHandlerThread;
232 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100233 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800234 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800235 private final BatterySaverController mBatterySaverController;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700236 private final BatterySaverStateMachine mBatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700237 private final BatterySavingStats mBatterySavingStats;
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800238 private final AttentionDetector mAttentionDetector;
Santos Cordon64a6e612018-08-22 19:27:04 +0100239 private final BinderService mBinderService;
240 private final LocalService mLocalService;
241 private final NativeWrapper mNativeWrapper;
242 private final Injector mInjector;
Jeff Brown2c43c332014-06-12 22:38:59 -0700243
Adam Lesinski182f73f2013-12-05 16:48:06 -0800244 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700245 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800246 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700247 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700248 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700249 private WindowManagerPolicy mPolicy;
250 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800251 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700252 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800253 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800254 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700255
Robert Horvath5560f382019-07-10 10:46:38 +0200256 private InattentiveSleepWarningController mInattentiveSleepWarningOverlayController;
257
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600258 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700259
260 // A bitfield that indicates what parts of the power state have
261 // changed and need to be recalculated.
262 private int mDirty;
263
264 // Indicates whether the device is awake or asleep or somewhere in between.
265 // This is distinct from the screen power state, which is managed separately.
266 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800267 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700268
Jeff Brown26875502014-01-30 21:47:47 -0800269 // True if the sandman has just been summoned for the first time since entering the
270 // dreaming or dozing state. Indicates whether a new dream should begin.
271 private boolean mSandmanSummoned;
272
Jeff Brown96307042012-07-27 15:51:34 -0700273 // True if MSG_SANDMAN has been scheduled.
274 private boolean mSandmanScheduled;
275
276 // Table of all suspend blockers.
277 // There should only be a few of these.
278 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
279
280 // Table of all wake locks acquired by applications.
281 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
282
283 // A bitfield that summarizes the state of all active wakelocks.
284 private int mWakeLockSummary;
285
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700286 // Have we scheduled a message to check for long wake locks? This is when we will check.
287 private long mNotifyLongScheduled;
288
289 // Last time we checked for long wake locks.
290 private long mNotifyLongDispatched;
291
292 // The time we decided to do next long check.
293 private long mNotifyLongNextCheck;
294
Jeff Brown96307042012-07-27 15:51:34 -0700295 // If true, instructs the display controller to wait for the proximity sensor to
296 // go negative before turning the screen on.
297 private boolean mRequestWaitForNegativeProximity;
298
299 // Timestamp of the last time the device was awoken or put to sleep.
300 private long mLastWakeTime;
301 private long mLastSleepTime;
302
Calin Tatarua3805722018-08-09 16:41:28 +0200303 // Last reason the device went to sleep.
Michael Wrighte3001042019-02-05 00:13:14 +0000304 private @WakeReason int mLastWakeReason;
Calin Tatarua3805722018-08-09 16:41:28 +0200305 private int mLastSleepReason;
306
Jeff Brown96307042012-07-27 15:51:34 -0700307 // Timestamp of the last call to user activity.
308 private long mLastUserActivityTime;
309 private long mLastUserActivityTimeNoChangeLights;
310
Jeff Brown0a571122014-08-21 21:50:43 -0700311 // Timestamp of last interactive power hint.
312 private long mLastInteractivePowerHintTime;
313
Jeff Browne333e672014-10-28 13:48:55 -0700314 // Timestamp of the last screen brightness boost.
315 private long mLastScreenBrightnessBoostTime;
316 private boolean mScreenBrightnessBoostInProgress;
317
Jeff Brown96307042012-07-27 15:51:34 -0700318 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700319 private int mUserActivitySummary;
320
321 // The desired display power state. The actual state may lag behind the
322 // requested because it is updated asynchronously by the display power controller.
323 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
324
Jeff Brown96307042012-07-27 15:51:34 -0700325 // True if the display power state has been fully applied, which means the display
326 // is actually on or actually off or whatever was requested.
327 private boolean mDisplayReady;
328
Jeff Brown27f7a862012-12-12 15:43:31 -0800329 // The suspend blocker used to keep the CPU alive when an application has acquired
330 // a wake lock.
331 private final SuspendBlocker mWakeLockSuspendBlocker;
332
333 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700334 private boolean mHoldingWakeLockSuspendBlocker;
335
Jeff Brown27f7a862012-12-12 15:43:31 -0800336 // The suspend blocker used to keep the CPU alive when the display is on, the
337 // display is getting ready or there is user activity (in which case the display
338 // must be on).
339 private final SuspendBlocker mDisplaySuspendBlocker;
340
341 // True if the display suspend blocker has been acquired.
342 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700343
344 // True if systemReady() has been called.
345 private boolean mSystemReady;
346
347 // True if boot completed occurred. We keep the screen on until this happens.
348 private boolean mBootCompleted;
349
Jeff Brown26875502014-01-30 21:47:47 -0800350 // True if auto-suspend mode is enabled.
351 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700352 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800353
354 // True if interactive mode is enabled.
355 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700356 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800357
Jeff Brown96307042012-07-27 15:51:34 -0700358 // True if the device is plugged into a power source.
359 private boolean mIsPowered;
360
Jeff Brownf3fb8952012-10-02 20:57:05 -0700361 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
362 private int mPlugType;
363
Jeff Brown016ff142012-10-15 16:47:22 -0700364 // The current battery level percentage.
365 private int mBatteryLevel;
366
367 // The battery level percentage at the time the dream started.
368 // This is used to terminate a dream and go to sleep if the battery is
369 // draining faster than it is charging and the user activity timeout has expired.
370 private int mBatteryLevelWhenDreamStarted;
371
Jeff Brownec6aa592012-10-17 20:30:25 -0700372 // The current dock state.
373 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
374
Jeff Brown26875502014-01-30 21:47:47 -0800375 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700376 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800377
378 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700379 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800380
Jeff Brown96307042012-07-27 15:51:34 -0700381 // True if the device should wake up when plugged or unplugged.
382 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
383
Bryce Lee584a4452014-10-21 15:55:55 -0700384 // True if the device should wake up when plugged or unplugged in theater mode.
385 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
386
Jeff Brownec083212013-09-11 20:45:25 -0700387 // True if the device should suspend when the screen is off due to proximity.
388 private boolean mSuspendWhenScreenOffDueToProximityConfig;
389
Robert Horvath5560f382019-07-10 10:46:38 +0200390 // Default value for attentive timeout.
391 private int mAttentiveTimeoutConfig;
392
Jeff Brown96307042012-07-27 15:51:34 -0700393 // True if dreams are supported on this device.
394 private boolean mDreamsSupportedConfig;
395
John Spurlocked108f32012-10-18 16:49:24 -0400396 // Default value for dreams enabled
397 private boolean mDreamsEnabledByDefaultConfig;
398
399 // Default value for dreams activate-on-sleep
400 private boolean mDreamsActivatedOnSleepByDefaultConfig;
401
402 // Default value for dreams activate-on-dock
403 private boolean mDreamsActivatedOnDockByDefaultConfig;
404
Jeff Brown26875502014-01-30 21:47:47 -0800405 // True if dreams can run while not plugged in.
406 private boolean mDreamsEnabledOnBatteryConfig;
407
408 // Minimum battery level to allow dreaming when powered.
409 // Use -1 to disable this safety feature.
410 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
411
412 // Minimum battery level to allow dreaming when not powered.
413 // Use -1 to disable this safety feature.
414 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
415
416 // If the battery level drops by this percentage and the user activity timeout
417 // has expired, then assume the device is receiving insufficient current to charge
418 // effectively and terminate the dream. Use -1 to disable this safety feature.
419 private int mDreamsBatteryLevelDrainCutoffConfig;
420
Jeff Brown96307042012-07-27 15:51:34 -0700421 // True if dreams are enabled by the user.
422 private boolean mDreamsEnabledSetting;
423
John Spurlock1a868b72012-08-22 09:56:51 -0400424 // True if dreams should be activated on sleep.
425 private boolean mDreamsActivateOnSleepSetting;
426
Jeff Brownec6aa592012-10-17 20:30:25 -0700427 // True if dreams should be activated on dock.
428 private boolean mDreamsActivateOnDockSetting;
429
Jeff Brown2175e9c2014-09-12 16:11:07 -0700430 // True if doze should not be started until after the screen off transition.
Lucas Dupin16cfe452018-02-08 13:14:50 -0800431 private boolean mDozeAfterScreenOff;
Jeff Brown2175e9c2014-09-12 16:11:07 -0700432
Jeff Brown27736f52014-05-20 17:17:10 -0700433 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100434 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700435
436 // The screen dim duration, in milliseconds.
437 // This is subtracted from the end of the screen off timeout so the
438 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100439 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700440
441 // The maximum screen dim time expressed as a ratio relative to the screen
442 // off timeout. If the screen off timeout is very short then we want the
443 // dim timeout to also be quite short so that most of the time is spent on.
444 // Otherwise the user won't get much screen on time before dimming occurs.
445 private float mMaximumScreenDimRatioConfig;
446
Jason Monk27bbb2d2015-03-31 16:46:39 -0400447 // Whether device supports double tap to wake.
448 private boolean mSupportsDoubleTapWakeConfig;
449
Jeff Brown96307042012-07-27 15:51:34 -0700450 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100451 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700452
Robert Horvath5560f382019-07-10 10:46:38 +0200453 // Default for attentive warning duration.
454 private long mAttentiveWarningDurationConfig;
455
Jeff Brown05af6ad2014-09-30 20:54:30 -0700456 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100457 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700458
Robert Horvath5560f382019-07-10 10:46:38 +0200459 // How long to show a warning message to user before the device goes to sleep
460 // after long user inactivity, even if wakelocks are held.
461 private long mAttentiveTimeoutSetting;
462
Jeff Brown96307042012-07-27 15:51:34 -0700463 // The maximum allowable screen off timeout according to the device
464 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100465 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700466
467 // The stay on while plugged in setting.
468 // A bitfield of battery conditions under which to make the screen stay on.
469 private int mStayOnWhilePluggedInSetting;
470
471 // True if the device should stay on.
472 private boolean mStayOn;
473
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800474 // True if the lights should stay off until an explicit user action.
475 private static boolean sQuiescent;
476
Jeff Brown93cbbb22012-10-04 13:18:36 -0700477 // True if the proximity sensor reads a positive result.
478 private boolean mProximityPositive;
479
Jeff Brown96307042012-07-27 15:51:34 -0700480 // Screen brightness setting limits.
481 private int mScreenBrightnessSettingMinimum;
482 private int mScreenBrightnessSettingMaximum;
483 private int mScreenBrightnessSettingDefault;
484
485 // The screen brightness setting, from 0 to 255.
486 // Use -1 if no value has been set.
487 private int mScreenBrightnessSetting;
488
489 // The screen brightness mode.
490 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
491 private int mScreenBrightnessModeSetting;
492
493 // The screen brightness setting override from the window manager
494 // to allow the current foreground activity to override the brightness.
495 // Use -1 to disable.
496 private int mScreenBrightnessOverrideFromWindowManager = -1;
497
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700498 // The window manager has determined the user to be inactive via other means.
499 // Set this to false to disable.
500 private boolean mUserInactiveOverrideFromWindowManager;
501
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700502 // The next possible user activity timeout after being explicitly told the user is inactive.
503 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
504 private long mOverriddenTimeout = -1;
505
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700506 // The user activity timeout override from the window manager
507 // to allow the current foreground activity to override the user activity timeout.
508 // Use -1 to disable.
509 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
510
Jeff Brown970d4132014-07-19 11:33:47 -0700511 // The screen state to use while dozing.
512 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
513
514 // The screen brightness to use while dozing.
515 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
516
Ivan Podogov56bc6d02018-02-26 16:04:24 +0000517 // Keep display state when dozing.
518 private boolean mDrawWakeLockOverrideFromSidekick;
519
Jeff Brown9ba8d782012-10-01 16:38:23 -0700520 // Time when we last logged a warning about calling userActivity() without permission.
521 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
522
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700523 // True if the battery level is currently considered low.
524 private boolean mBatteryLevelLow;
525
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700526 // True if we are currently in device idle mode.
527 private boolean mDeviceIdleMode;
528
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700529 // True if we are currently in light device idle mode.
530 private boolean mLightDeviceIdleMode;
531
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700532 // Set of app ids that we will always respect the wake locks for.
533 int[] mDeviceIdleWhitelist = new int[0];
534
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700535 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
536 int[] mDeviceIdleTempWhitelist = new int[0];
537
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700538 private final SparseArray<UidState> mUidState = new SparseArray<>();
539
540 // We are currently in the middle of a batch change of uids.
541 private boolean mUidsChanging;
542
543 // Some uids have actually changed while mUidsChanging was true.
544 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700545
Bryce Lee584a4452014-10-21 15:55:55 -0700546 // True if theater mode is enabled
547 private boolean mTheaterModeEnabled;
548
Adrian Roos56021892017-02-27 20:25:09 +0100549 // True if always on display is enabled
550 private boolean mAlwaysOnEnabled;
551
Jason Monk27bbb2d2015-03-31 16:46:39 -0400552 // True if double tap to wake is enabled
553 private boolean mDoubleTapWakeEnabled;
554
Santos Cordon3107d292016-09-20 15:50:35 -0700555 // True if we are currently in VR Mode.
556 private boolean mIsVrModeEnabled;
557
Santos Cordon12f92eb2019-02-01 21:28:47 +0000558 // True if we in the process of performing a forceSuspend
559 private boolean mForceSuspendActive;
560
Santos Cordon03044382019-09-19 16:59:01 +0100561 // Transition to Doze is in progress. We have transitioned to WAKEFULNESS_DOZING,
562 // but the DreamService has not yet been told to start (it's an async process).
563 private boolean mDozeStartInProgress;
564
Pavel Grafov28939982017-10-03 15:11:52 +0100565 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
566 @Override
Beverly478722e2019-10-14 11:16:57 -0400567 public void onUserSwitching(@UserIdInt int newUserId) throws RemoteException {
568 synchronized (mLock) {
569 mUserId = newUserId;
570 }
571 }
Pavel Grafov28939982017-10-03 15:11:52 +0100572
573 @Override
574 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
575 final long now = SystemClock.uptimeMillis();
Beverly478722e2019-10-14 11:16:57 -0400576 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +0100577 mForegroundProfile = newProfileId;
578 maybeUpdateForegroundProfileLastActivityLocked(now);
579 }
580 }
581 }
582
583 // User id corresponding to activity the user is currently interacting with.
584 private @UserIdInt int mForegroundProfile;
Beverly478722e2019-10-14 11:16:57 -0400585 // User id of main profile for the current user (doesn't include managed profiles)
586 private @UserIdInt int mUserId;
Pavel Grafov28939982017-10-03 15:11:52 +0100587
588 // Per-profile state to track when a profile should be locked.
589 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
590
591 private static final class ProfilePowerState {
592 // Profile user id.
593 final @UserIdInt int mUserId;
594 // Maximum time to lock set by admin.
595 long mScreenOffTimeout;
596 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
597 int mWakeLockSummary;
598 // Last user activity that happened in an app running in the profile.
599 long mLastUserActivityTime;
600 // Whether profile has been locked last time it timed out.
601 boolean mLockingNotified;
602
603 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
604 mUserId = userId;
605 mScreenOffTimeout = screenOffTimeout;
606 // Not accurate but at least won't cause immediate locking of the profile.
607 mLastUserActivityTime = SystemClock.uptimeMillis();
608 }
609 }
610
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800611 /**
612 * All times are in milliseconds. These constants are kept synchronized with the system
613 * global Settings. Any access to this class or its fields should be done while
614 * holding the PowerManagerService.mLock lock.
615 */
616 private final class Constants extends ContentObserver {
617 // Key names stored in the settings value.
618 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
619
620 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
621
622 // Prevent processes that are cached from holding wake locks?
623 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
624
625 private ContentResolver mResolver;
626 private final KeyValueListParser mParser = new KeyValueListParser(',');
627
628 public Constants(Handler handler) {
629 super(handler);
630 }
631
632 public void start(ContentResolver resolver) {
633 mResolver = resolver;
634 mResolver.registerContentObserver(Settings.Global.getUriFor(
635 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
636 updateConstants();
637 }
638
639 @Override
640 public void onChange(boolean selfChange, Uri uri) {
641 updateConstants();
642 }
643
644 private void updateConstants() {
645 synchronized (mLock) {
646 try {
647 mParser.setString(Settings.Global.getString(mResolver,
648 Settings.Global.POWER_MANAGER_CONSTANTS));
649 } catch (IllegalArgumentException e) {
650 // Failed to parse the settings string, log this and move on
651 // with defaults.
652 Slog.e(TAG, "Bad alarm manager settings", e);
653 }
654
655 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
656 DEFAULT_NO_CACHED_WAKE_LOCKS);
657 }
658 }
659
660 void dump(PrintWriter pw) {
661 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
662
663 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
664 pw.println(NO_CACHED_WAKE_LOCKS);
665 }
Netta P958d0a52017-02-07 11:20:55 -0800666
667 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700668 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
669 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800670 NO_CACHED_WAKE_LOCKS);
671 proto.end(constantsToken);
672 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800673 }
674
Santos Cordon64a6e612018-08-22 19:27:04 +0100675 /**
676 * Wrapper around the static-native methods of PowerManagerService.
677 *
678 * This class exists to allow us to mock static native methods in our tests. If mocking static
679 * methods becomes easier than this in the future, we can delete this class.
680 */
681 @VisibleForTesting
682 public static class NativeWrapper {
683 /** Wrapper for PowerManager.nativeInit */
684 public void nativeInit(PowerManagerService service) {
685 service.nativeInit();
686 }
687
688 /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
689 public void nativeAcquireSuspendBlocker(String name) {
690 PowerManagerService.nativeAcquireSuspendBlocker(name);
691 }
692
693 /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
694 public void nativeReleaseSuspendBlocker(String name) {
695 PowerManagerService.nativeReleaseSuspendBlocker(name);
696 }
697
698 /** Wrapper for PowerManager.nativeSetInteractive */
699 public void nativeSetInteractive(boolean enable) {
700 PowerManagerService.nativeSetInteractive(enable);
701 }
702
703 /** Wrapper for PowerManager.nativeSetAutoSuspend */
704 public void nativeSetAutoSuspend(boolean enable) {
705 PowerManagerService.nativeSetAutoSuspend(enable);
706 }
707
708 /** Wrapper for PowerManager.nativeSendPowerHint */
709 public void nativeSendPowerHint(int hintId, int data) {
710 PowerManagerService.nativeSendPowerHint(hintId, data);
711 }
712
713 /** Wrapper for PowerManager.nativeSetFeature */
714 public void nativeSetFeature(int featureId, int data) {
715 PowerManagerService.nativeSetFeature(featureId, data);
716 }
Santos Cordon12f92eb2019-02-01 21:28:47 +0000717
718 /** Wrapper for PowerManager.nativeForceSuspend */
719 public boolean nativeForceSuspend() {
720 return PowerManagerService.nativeForceSuspend();
721 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100722 }
723
724 @VisibleForTesting
725 static class Injector {
726 Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
727 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
728 return new Notifier(looper, context, batteryStats, suspendBlocker, policy);
729 }
730
731 SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
732 SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
733 service.mSuspendBlockers.add(suspendBlocker);
734 return suspendBlocker;
735 }
736
737 BatterySaverPolicy createBatterySaverPolicy(
738 Object lock, Context context, BatterySavingStats batterySavingStats) {
739 return new BatterySaverPolicy(lock, context, batterySavingStats);
740 }
741
742 NativeWrapper createNativeWrapper() {
743 return new NativeWrapper();
744 }
Santos Cordon9b510a22018-08-24 16:42:54 +0100745
746 WirelessChargerDetector createWirelessChargerDetector(
747 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
748 return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
749 }
750
751 AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
752 return new AmbientDisplayConfiguration(context);
753 }
Robert Horvath5560f382019-07-10 10:46:38 +0200754
755 InattentiveSleepWarningController createInattentiveSleepWarningController() {
756 return new InattentiveSleepWarningController();
757 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100758 }
759
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800760 final Constants mConstants;
761
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700762 private native void nativeInit();
Jeff Brown96307042012-07-27 15:51:34 -0700763 private static native void nativeAcquireSuspendBlocker(String name);
764 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700765 private static native void nativeSetInteractive(boolean enable);
766 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700767 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400768 private static native void nativeSetFeature(int featureId, int data);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000769 private static native boolean nativeForceSuspend();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800770
Jeff Brownb880d882014-02-10 19:47:07 -0800771 public PowerManagerService(Context context) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100772 this(context, new Injector());
773 }
774
775 @VisibleForTesting
776 PowerManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800777 super(context);
Santos Cordon64a6e612018-08-22 19:27:04 +0100778
Jeff Brownb880d882014-02-10 19:47:07 -0800779 mContext = context;
Santos Cordon64a6e612018-08-22 19:27:04 +0100780 mBinderService = new BinderService();
781 mLocalService = new LocalService();
782 mNativeWrapper = injector.createNativeWrapper();
783 mInjector = injector;
784
Jeff Brown2c43c332014-06-12 22:38:59 -0700785 mHandlerThread = new ServiceThread(TAG,
786 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
787 mHandlerThread.start();
788 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800789 mConstants = new Constants(mHandler);
Santos Cordon9b510a22018-08-24 16:42:54 +0100790 mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800791 mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800792
Makoto Onukibd7a6252018-05-10 13:41:39 -0700793 mBatterySavingStats = new BatterySavingStats(mLock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100794 mBatterySaverPolicy =
795 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700796 mBatterySaverController = new BatterySaverController(mLock, mContext,
Santos Cordon64a6e612018-08-22 19:27:04 +0100797 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
798 mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700799 mBatterySaverStateMachine = new BatterySaverStateMachine(
800 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700801
Robert Horvath5560f382019-07-10 10:46:38 +0200802 mInattentiveSleepWarningOverlayController =
803 mInjector.createInattentiveSleepWarningController();
804
Jeff Brown96307042012-07-27 15:51:34 -0700805 synchronized (mLock) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100806 mWakeLockSuspendBlocker =
807 mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
808 mDisplaySuspendBlocker =
809 mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
810 if (mDisplaySuspendBlocker != null) {
811 mDisplaySuspendBlocker.acquire();
812 mHoldingDisplaySuspendBlocker = true;
813 }
Jeff Brown037c33e2014-04-09 00:31:55 -0700814 mHalAutoSuspendModeEnabled = false;
815 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800816
Jeff Brown96307042012-07-27 15:51:34 -0700817 mWakefulness = WAKEFULNESS_AWAKE;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800818 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
819
Santos Cordon64a6e612018-08-22 19:27:04 +0100820 mNativeWrapper.nativeInit(this);
821 mNativeWrapper.nativeSetAutoSuspend(false);
822 mNativeWrapper.nativeSetInteractive(true);
823 mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700824 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800825 }
826
Jeff Brown6f357d32014-01-15 20:40:55 -0800827 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800828 public void onStart() {
Santos Cordon64a6e612018-08-22 19:27:04 +0100829 publishBinderService(Context.POWER_SERVICE, mBinderService);
830 publishLocalService(PowerManagerInternal.class, mLocalService);
Jeff Brown9e316a12012-10-08 19:17:06 -0700831
832 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800833 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700834 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800835
Jeff Brown6d2a9492014-08-07 19:06:49 -0700836 @Override
837 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700838 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600839 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
840 incrementBootCount();
841
842 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700843 final long now = SystemClock.uptimeMillis();
844 mBootCompleted = true;
845 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700846
847 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700848 userActivityNoUpdateLocked(
849 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
850 updatePowerStateLocked();
851 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700852 }
853 }
854
Jeff Brown21392762014-06-13 19:00:36 -0700855 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700856 synchronized (mLock) {
857 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700858 mAppOps = appOps;
859 mDreamManager = getLocalService(DreamManagerInternal.class);
860 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
861 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700862 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800863 mAttentionDetector.systemReady(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800864
Adam Lesinski182f73f2013-12-05 16:48:06 -0800865 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700866 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
867 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
868 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800869
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700870 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800871
Jeff Brownc38c9be2012-10-04 13:16:19 -0700872 // The notifier runs on the system server's main looper so as not to interfere
873 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700874 mBatteryStats = BatteryStatsService.getService();
Santos Cordon64a6e612018-08-22 19:27:04 +0100875 mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
876 mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
877 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700878
Santos Cordon9b510a22018-08-24 16:42:54 +0100879 mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
Santos Cordon64a6e612018-08-22 19:27:04 +0100880 mInjector.createSuspendBlocker(
881 this, "PowerManagerService.WirelessChargerDetector"),
Jeff Browndbcc8a22013-10-01 16:16:44 -0700882 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700883 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700884
885 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800886 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400887
Jeff Brown131206b2014-04-08 17:27:14 -0700888 // Initialize display power management.
889 mDisplayManagerInternal.initPowerManagement(
890 mDisplayPowerCallbacks, mHandler, sensorManager);
891
Pavel Grafov28939982017-10-03 15:11:52 +0100892 try {
893 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
894 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
895 } catch (RemoteException e) {
896 // Shouldn't happen since in-process.
897 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800898
Jeff Brown96307042012-07-27 15:51:34 -0700899 // Go.
900 readConfigurationLocked();
901 updateSettingsLocked();
902 mDirty |= DIRTY_BATTERY_STATE;
903 updatePowerStateLocked();
904 }
Shibin George43f5de02016-07-06 02:12:10 +0530905
Jeff Sharkey6e544612017-02-20 11:02:26 -0700906 final ContentResolver resolver = mContext.getContentResolver();
907 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800908
909 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -0700910 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -0700911
912 // Register for settings changes.
913 resolver.registerContentObserver(Settings.Secure.getUriFor(
914 Settings.Secure.SCREENSAVER_ENABLED),
915 false, mSettingsObserver, UserHandle.USER_ALL);
916 resolver.registerContentObserver(Settings.Secure.getUriFor(
917 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
918 false, mSettingsObserver, UserHandle.USER_ALL);
919 resolver.registerContentObserver(Settings.Secure.getUriFor(
920 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
921 false, mSettingsObserver, UserHandle.USER_ALL);
922 resolver.registerContentObserver(Settings.System.getUriFor(
923 Settings.System.SCREEN_OFF_TIMEOUT),
924 false, mSettingsObserver, UserHandle.USER_ALL);
925 resolver.registerContentObserver(Settings.Secure.getUriFor(
926 Settings.Secure.SLEEP_TIMEOUT),
927 false, mSettingsObserver, UserHandle.USER_ALL);
Robert Horvath5560f382019-07-10 10:46:38 +0200928 resolver.registerContentObserver(Settings.Secure.getUriFor(
929 Settings.Secure.ATTENTIVE_TIMEOUT),
930 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Sharkey6e544612017-02-20 11:02:26 -0700931 resolver.registerContentObserver(Settings.Global.getUriFor(
932 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
933 false, mSettingsObserver, UserHandle.USER_ALL);
934 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700935 Settings.System.SCREEN_BRIGHTNESS_MODE),
936 false, mSettingsObserver, UserHandle.USER_ALL);
937 resolver.registerContentObserver(Settings.System.getUriFor(
938 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
939 false, mSettingsObserver, UserHandle.USER_ALL);
940 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700941 Settings.Global.THEATER_MODE_ON),
942 false, mSettingsObserver, UserHandle.USER_ALL);
943 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100944 Settings.Secure.DOZE_ALWAYS_ON),
945 false, mSettingsObserver, UserHandle.USER_ALL);
946 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700947 Settings.Secure.DOUBLE_TAP_TO_WAKE),
948 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700949 resolver.registerContentObserver(Settings.Global.getUriFor(
950 Settings.Global.DEVICE_DEMO_MODE),
951 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Santos Cordon64a6e612018-08-22 19:27:04 +0100952 IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
Jeff Sharkey6e544612017-02-20 11:02:26 -0700953 if (vrManager != null) {
954 try {
955 vrManager.registerListener(mVrStateCallbacks);
956 } catch (RemoteException e) {
957 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
958 }
959 }
960
Shibin George43f5de02016-07-06 02:12:10 +0530961 // Register for broadcasts from other components of the system.
962 IntentFilter filter = new IntentFilter();
963 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
964 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
965 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
966
967 filter = new IntentFilter();
968 filter.addAction(Intent.ACTION_DREAMING_STARTED);
969 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
970 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
971
972 filter = new IntentFilter();
973 filter.addAction(Intent.ACTION_USER_SWITCHED);
974 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
975
976 filter = new IntentFilter();
977 filter.addAction(Intent.ACTION_DOCK_EVENT);
978 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700979 }
980
Santos Cordon9b510a22018-08-24 16:42:54 +0100981 @VisibleForTesting
982 void readConfigurationLocked() {
Jeff Brown96307042012-07-27 15:51:34 -0700983 final Resources resources = mContext.getResources();
984
Jeff Brown037c33e2014-04-09 00:31:55 -0700985 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800986 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700987 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800988 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700989 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700990 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700991 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
992 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700993 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
994 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Robert Horvath5560f382019-07-10 10:46:38 +0200995 mAttentiveTimeoutConfig = resources.getInteger(
996 com.android.internal.R.integer.config_attentiveTimeout);
997 mAttentiveWarningDurationConfig = resources.getInteger(
998 com.android.internal.R.integer.config_attentiveWarningDuration);
Jeff Brown96307042012-07-27 15:51:34 -0700999 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -04001000 com.android.internal.R.bool.config_dreamsSupported);
1001 mDreamsEnabledByDefaultConfig = resources.getBoolean(
1002 com.android.internal.R.bool.config_dreamsEnabledByDefault);
1003 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
1004 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
1005 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
1006 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -08001007 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
1008 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
1009 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
1010 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
1011 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
1012 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
1013 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
1014 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -08001015 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -07001016 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -07001017 mMinimumScreenOffTimeoutConfig = resources.getInteger(
1018 com.android.internal.R.integer.config_minimumScreenOffTimeout);
1019 mMaximumScreenDimDurationConfig = resources.getInteger(
1020 com.android.internal.R.integer.config_maximumScreenDimDuration);
1021 mMaximumScreenDimRatioConfig = resources.getFraction(
1022 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001023 mSupportsDoubleTapWakeConfig = resources.getBoolean(
1024 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026
Jeff Brown96307042012-07-27 15:51:34 -07001027 private void updateSettingsLocked() {
1028 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -07001029
Jeff Brownd4935962012-09-25 13:27:20 -07001030 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001031 Settings.Secure.SCREENSAVER_ENABLED,
1032 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001033 UserHandle.USER_CURRENT) != 0);
1034 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001035 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
1036 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001037 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -07001038 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001039 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1040 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -07001041 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -07001042 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1043 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1044 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -07001045 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1046 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1047 UserHandle.USER_CURRENT);
Robert Horvath5560f382019-07-10 10:46:38 +02001048 mAttentiveTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1049 Settings.Secure.ATTENTIVE_TIMEOUT, mAttentiveTimeoutConfig,
1050 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -07001051 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -07001052 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -07001053 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1054 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +01001055 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -07001056
Jason Monk27bbb2d2015-03-31 16:46:39 -04001057 if (mSupportsDoubleTapWakeConfig) {
1058 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1059 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1060 UserHandle.USER_CURRENT) != 0;
1061 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1062 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
Santos Cordon64a6e612018-08-22 19:27:04 +01001063 mNativeWrapper.nativeSetFeature(
1064 POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001065 }
1066 }
1067
Christine Franks732c0432017-06-23 18:12:46 -07001068 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1069 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
1070 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1071 }
1072
Jeff Brownd4935962012-09-25 13:27:20 -07001073 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -07001074 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -07001075 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -07001076
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001077 mDirty |= DIRTY_SETTINGS;
1078 }
1079
Jeff Brown96307042012-07-27 15:51:34 -07001080 private void handleSettingsChangedLocked() {
1081 updateSettingsLocked();
1082 updatePowerStateLocked();
1083 }
1084
Dianne Hackborn713df152013-05-17 11:27:57 -07001085 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001086 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001087 synchronized (mLock) {
1088 if (DEBUG_SPEW) {
1089 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1090 + ", flags=0x" + Integer.toHexString(flags)
1091 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093
Jeff Brown96307042012-07-27 15:51:34 -07001094 WakeLock wakeLock;
1095 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001096 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001097 if (index >= 0) {
1098 wakeLock = mWakeLocks.get(index);
1099 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1100 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001101 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1102 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001103 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001104 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001105 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001106 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001107 UidState state = mUidState.get(uid);
1108 if (state == null) {
1109 state = new UidState(uid);
1110 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1111 mUidState.put(uid, state);
1112 }
1113 state.mNumWakeLocks++;
1114 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1115 state);
Jeff Brown96307042012-07-27 15:51:34 -07001116 try {
1117 lock.linkToDeath(wakeLock, 0);
1118 } catch (RemoteException ex) {
1119 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 }
Jeff Brown96307042012-07-27 15:51:34 -07001121 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001122 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001123 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125
Jeff Brownc12035c2014-08-13 18:52:25 -07001126 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001127 mDirty |= DIRTY_WAKE_LOCKS;
1128 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001129 if (notifyAcquire) {
1130 // This needs to be done last so we are sure we have acquired the
1131 // kernel wake lock. Otherwise we have a race where the system may
1132 // go to sleep between the time we start the accounting in battery
1133 // stats and when we actually get around to telling the kernel to
1134 // stay awake.
1135 notifyWakeLockAcquiredLocked(wakeLock);
1136 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001137 }
1138 }
1139
Jeff Brownec083212013-09-11 20:45:25 -07001140 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001141 private static boolean isScreenLock(final WakeLock wakeLock) {
1142 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1143 case PowerManager.FULL_WAKE_LOCK:
1144 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1145 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1146 return true;
1147 }
1148 return false;
1149 }
1150
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001151 private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1152 if (workSource.getWorkChains() == null) {
1153 return null;
1154 }
1155
1156 for (WorkChain workChain: workSource.getWorkChains()) {
1157 if (workChain.getSize() > 0) {
1158 return workChain;
1159 }
1160 }
1161
1162 return null;
1163 }
1164
Jeff Brownc12035c2014-08-13 18:52:25 -07001165 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001166 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1167 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001168 String opPackageName;
1169 int opUid;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001170 if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1171 WorkSource workSource = wakeLock.mWorkSource;
1172 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1173 if (workChain != null) {
1174 opPackageName = workChain.getAttributionTag();
1175 opUid = workChain.getAttributionUid();
1176 } else {
1177 opPackageName = workSource.getName(0) != null
1178 ? workSource.getName(0) : wakeLock.mPackageName;
1179 opUid = workSource.get(0);
1180 }
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001181 } else {
1182 opPackageName = wakeLock.mPackageName;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001183 opUid = wakeLock.mOwnerUid;
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001184 }
Michael Wrighte3001042019-02-05 00:13:14 +00001185 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1186 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1187 opUid, opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001188 }
1189 }
1190
Jeff Brown96307042012-07-27 15:51:34 -07001191 private void releaseWakeLockInternal(IBinder lock, int flags) {
1192 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001193 int index = findWakeLockIndexLocked(lock);
1194 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001195 if (DEBUG_SPEW) {
1196 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1197 + " [not found], flags=0x" + Integer.toHexString(flags));
1198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 return;
1200 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001201
Jeff Brown96307042012-07-27 15:51:34 -07001202 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001203 if (DEBUG_SPEW) {
1204 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1205 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1206 }
1207
Michael Wright1208e272014-09-08 19:57:50 -07001208 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001209 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
1211
Jeff Brown3edf5272014-08-14 19:25:14 -07001212 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1213 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 }
1215 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001216
Jeff Brown96307042012-07-27 15:51:34 -07001217 private void handleWakeLockDeath(WakeLock wakeLock) {
1218 synchronized (mLock) {
1219 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001220 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1221 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001222 }
1223
1224 int index = mWakeLocks.indexOf(wakeLock);
1225 if (index < 0) {
1226 return;
1227 }
1228
Jeff Brown3edf5272014-08-14 19:25:14 -07001229 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001230 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001231 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001232
Jeff Brown3edf5272014-08-14 19:25:14 -07001233 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1234 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001235 UidState state = wakeLock.mUidState;
1236 state.mNumWakeLocks--;
1237 if (state.mNumWakeLocks <= 0 &&
1238 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1239 mUidState.remove(state.mUid);
1240 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001241 notifyWakeLockReleasedLocked(wakeLock);
1242
1243 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1244 mDirty |= DIRTY_WAKE_LOCKS;
1245 updatePowerStateLocked();
1246 }
1247
Jeff Brown96307042012-07-27 15:51:34 -07001248 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001249 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1250 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001251 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1252 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1253 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1254 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
1257
Dianne Hackbornd953c532014-08-16 18:17:38 -07001258 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1259 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001260 synchronized (mLock) {
1261 int index = findWakeLockIndexLocked(lock);
1262 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001263 if (DEBUG_SPEW) {
1264 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1265 + " [not found], ws=" + ws);
1266 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001267 throw new IllegalArgumentException("Wake lock not active: " + lock
1268 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001269 }
1270
1271 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001272 if (DEBUG_SPEW) {
1273 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1274 + " [" + wakeLock.mTag + "], ws=" + ws);
1275 }
1276
Jeff Brown96307042012-07-27 15:51:34 -07001277 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001278 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1279 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001280 ws, historyTag);
1281 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001282 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001283 }
1284 }
1285 }
1286
1287 private int findWakeLockIndexLocked(IBinder lock) {
1288 final int count = mWakeLocks.size();
1289 for (int i = 0; i < count; i++) {
1290 if (mWakeLocks.get(i).mLock == lock) {
1291 return i;
1292 }
1293 }
1294 return -1;
1295 }
1296
1297 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001298 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001299 wakeLock.mNotifiedAcquired = true;
1300 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001301 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1302 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001303 restartNofifyLongTimerLocked(wakeLock);
1304 }
1305 }
1306
1307 private void enqueueNotifyLongMsgLocked(long time) {
1308 mNotifyLongScheduled = time;
1309 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1310 msg.setAsynchronous(true);
1311 mHandler.sendMessageAtTime(msg, time);
1312 }
1313
1314 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1315 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1316 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1317 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1318 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1319 }
1320 }
1321
1322 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1323 if (mSystemReady && !wakeLock.mDisabled) {
1324 wakeLock.mNotifiedLong = true;
1325 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1326 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1327 }
1328 }
1329
1330 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1331 if (wakeLock.mNotifiedLong) {
1332 wakeLock.mNotifiedLong = false;
1333 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1334 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001335 }
1336 }
1337
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001338 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1339 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1340 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1341 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1342 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1343 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001344 notifyWakeLockLongFinishedLocked(wakeLock);
1345 // Changing the wake lock will count as releasing the old wake lock(s) and
1346 // acquiring the new ones... we do this because otherwise once a wakelock
1347 // becomes long, if we just continued to treat it as long we can get in to
1348 // situations where we spam battery stats with every following change to it.
1349 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001350 }
1351 }
1352
Jeff Brown96307042012-07-27 15:51:34 -07001353 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001354 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1355 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001356 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001357 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1358 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1359 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001360 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001361 }
1362 }
1363
Jeff Brownec083212013-09-11 20:45:25 -07001364 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001365 private boolean isWakeLockLevelSupportedInternal(int level) {
1366 synchronized (mLock) {
1367 switch (level) {
1368 case PowerManager.PARTIAL_WAKE_LOCK:
1369 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1370 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1371 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001372 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001373 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001374 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001375
1376 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001377 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001378
1379 default:
1380 return false;
1381 }
1382 }
1383 }
1384
Jeff Brown96307042012-07-27 15:51:34 -07001385 // Called from native code.
1386 private void userActivityFromNative(long eventTime, int event, int flags) {
1387 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1388 }
1389
1390 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1391 synchronized (mLock) {
1392 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1393 updatePowerStateLocked();
1394 }
1395 }
1396 }
1397
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001398 private void onUserAttention() {
1399 synchronized (mLock) {
1400 if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1401 PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1402 Process.SYSTEM_UID)) {
1403 updatePowerStateLocked();
1404 }
1405 }
1406 }
1407
Jeff Brown96307042012-07-27 15:51:34 -07001408 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1409 if (DEBUG_SPEW) {
1410 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1411 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1412 + ", uid=" + uid);
1413 }
1414
1415 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001416 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001417 return false;
1418 }
1419
Jeff Brown3edf5272014-08-14 19:25:14 -07001420 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1421 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001422 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001423 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001424 mLastInteractivePowerHintTime = eventTime;
1425 }
1426
Jeff Brown3edf5272014-08-14 19:25:14 -07001427 mNotifier.onUserActivity(event, uid);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001428 mAttentionDetector.onUserActivity(eventTime, event);
Jeff Brown96307042012-07-27 15:51:34 -07001429
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001430 if (mUserInactiveOverrideFromWindowManager) {
1431 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001432 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001433 }
1434
Jeff Brown0a571122014-08-21 21:50:43 -07001435 if (mWakefulness == WAKEFULNESS_ASLEEP
1436 || mWakefulness == WAKEFULNESS_DOZING
1437 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1438 return false;
1439 }
1440
Pavel Grafov28939982017-10-03 15:11:52 +01001441 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1442
Jeff Brown3edf5272014-08-14 19:25:14 -07001443 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1444 if (eventTime > mLastUserActivityTimeNoChangeLights
1445 && eventTime > mLastUserActivityTime) {
1446 mLastUserActivityTimeNoChangeLights = eventTime;
1447 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001448 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1449 mDirty |= DIRTY_QUIESCENT;
1450 }
1451
Jeff Brown3edf5272014-08-14 19:25:14 -07001452 return true;
1453 }
1454 } else {
1455 if (eventTime > mLastUserActivityTime) {
1456 mLastUserActivityTime = eventTime;
1457 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001458 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1459 mDirty |= DIRTY_QUIESCENT;
1460 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001461 return true;
1462 }
Jeff Brown96307042012-07-27 15:51:34 -07001463 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001464 } finally {
1465 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001466 }
1467 return false;
1468 }
1469
Pavel Grafov28939982017-10-03 15:11:52 +01001470 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1471 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1472 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1473 profile.mLastUserActivityTime = eventTime;
1474 }
1475 }
1476
Michael Wrighte3001042019-02-05 00:13:14 +00001477 private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1478 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001479 synchronized (mLock) {
Michael Wrighte3001042019-02-05 00:13:14 +00001480 if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001481 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001482 }
1483 }
Jeff Brown96307042012-07-27 15:51:34 -07001484 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001485
Michael Wrighte3001042019-02-05 00:13:14 +00001486 private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1487 int reasonUid, String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001488 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001489 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001490 }
Jeff Brown96307042012-07-27 15:51:34 -07001491
1492 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
Santos Cordon12f92eb2019-02-01 21:28:47 +00001493 || !mBootCompleted || !mSystemReady || mForceSuspendActive) {
Jeff Brown96307042012-07-27 15:51:34 -07001494 return false;
1495 }
1496
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001497 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1498
Jeff Brown3edf5272014-08-14 19:25:14 -07001499 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1500 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001501 Slog.i(TAG, "Waking up from "
1502 + PowerManagerInternal.wakefulnessToString(mWakefulness)
1503 + " (uid=" + reasonUid
1504 + ", reason=" + PowerManager.wakeReasonToString(reason)
1505 + ", details=" + details
1506 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001507
1508 mLastWakeTime = eventTime;
Michael Wrighte3001042019-02-05 00:13:14 +00001509 mLastWakeReason = reason;
1510 setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001511
Michael Wrighte3001042019-02-05 00:13:14 +00001512 mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001513 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001514 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001515 } finally {
1516 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001517 }
Jeff Brown96307042012-07-27 15:51:34 -07001518 return true;
1519 }
1520
Jeff Brownc12035c2014-08-13 18:52:25 -07001521 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001522 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001523 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001524 updatePowerStateLocked();
1525 }
1526 }
1527 }
1528
Santos Cordon12f92eb2019-02-01 21:28:47 +00001529 /**
1530 * Puts the system in doze.
1531 *
1532 * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1533 * and only tucks itself in to SLEEP if requested with the flag
1534 * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1535 */
Jeff Brownec083212013-09-11 20:45:25 -07001536 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001537 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001538 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001539 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001540 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001541 }
1542
Jeff Brown26875502014-01-30 21:47:47 -08001543 if (eventTime < mLastWakeTime
1544 || mWakefulness == WAKEFULNESS_ASLEEP
1545 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001546 || !mBootCompleted || !mSystemReady) {
1547 return false;
1548 }
1549
Jeff Brown3edf5272014-08-14 19:25:14 -07001550 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1551 try {
Santos Cordon12f92eb2019-02-01 21:28:47 +00001552 reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1553 Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1554 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1555 + " (uid " + uid + ")...");
Jeff Brown6d8fd272014-05-20 21:24:38 -07001556
Jeff Brown3edf5272014-08-14 19:25:14 -07001557 mLastSleepTime = eventTime;
Calin Tatarua3805722018-08-09 16:41:28 +02001558 mLastSleepReason = reason;
Jeff Brown3edf5272014-08-14 19:25:14 -07001559 mSandmanSummoned = true;
Santos Cordon03044382019-09-19 16:59:01 +01001560 mDozeStartInProgress = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001561 setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001562
1563 // Report the number of wake locks that will be cleared by going to sleep.
1564 int numWakeLocksCleared = 0;
1565 final int numWakeLocks = mWakeLocks.size();
1566 for (int i = 0; i < numWakeLocks; i++) {
1567 final WakeLock wakeLock = mWakeLocks.get(i);
1568 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1569 case PowerManager.FULL_WAKE_LOCK:
1570 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1571 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1572 numWakeLocksCleared += 1;
1573 break;
1574 }
1575 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001576 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001577
1578 // Skip dozing if requested.
1579 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1580 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1581 }
1582 } finally {
1583 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001584 }
Jeff Brown96307042012-07-27 15:51:34 -07001585 return true;
1586 }
1587
Jeff Brownc12035c2014-08-13 18:52:25 -07001588 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001589 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001590 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001591 updatePowerStateLocked();
1592 }
1593 }
1594 }
1595
Jeff Brownc12035c2014-08-13 18:52:25 -07001596 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001597 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001598 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001599 }
1600
1601 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1602 || !mBootCompleted || !mSystemReady) {
1603 return false;
1604 }
1605
Jeff Brown3edf5272014-08-14 19:25:14 -07001606 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1607 try {
1608 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001609
Jeff Brown3edf5272014-08-14 19:25:14 -07001610 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001611 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001612 } finally {
1613 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1614 }
Jeff Brown26875502014-01-30 21:47:47 -08001615 return true;
1616 }
1617
1618 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001619 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001620 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001621 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1622 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001623 }
1624
1625 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1626 || !mBootCompleted || !mSystemReady) {
1627 return false;
1628 }
1629
Jeff Brown3edf5272014-08-14 19:25:14 -07001630 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1631 try {
1632 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001633
Michael Wrighte3001042019-02-05 00:13:14 +00001634 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1635 eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001636 } finally {
1637 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1638 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001639 return true;
1640 }
1641
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001642 @VisibleForTesting
Michael Wrighte3001042019-02-05 00:13:14 +00001643 void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001644 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001645 mWakefulness = wakefulness;
1646 mWakefulnessChanging = true;
1647 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon03044382019-09-19 16:59:01 +01001648
1649 // This is only valid while we are in wakefulness dozing. Set to false otherwise.
1650 mDozeStartInProgress &= (mWakefulness == WAKEFULNESS_DOZING);
1651
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001652 if (mNotifier != null) {
Michael Wrighte3001042019-02-05 00:13:14 +00001653 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001654 }
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001655 mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
Jeff Brown037c33e2014-04-09 00:31:55 -07001656 }
1657 }
1658
Santos Cordon64a6e612018-08-22 19:27:04 +01001659 @VisibleForTesting
1660 int getWakefulness() {
1661 return mWakefulness;
1662 }
1663
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001664 /**
1665 * Logs the time the device would have spent awake before user activity timeout,
1666 * had the system not been told the user was inactive.
1667 */
1668 private void logSleepTimeoutRecapturedLocked() {
1669 final long now = SystemClock.uptimeMillis();
1670 final long savedWakeTimeMs = mOverriddenTimeout - now;
1671 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001672 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001673 mOverriddenTimeout = -1;
1674 }
1675 }
1676
Jeff Brown416c49c2015-05-26 19:50:18 -07001677 private void finishWakefulnessChangeIfNeededLocked() {
1678 if (mWakefulnessChanging && mDisplayReady) {
1679 if (mWakefulness == WAKEFULNESS_DOZING
1680 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1681 return; // wait until dream has enabled dozing
Santos Cordon03044382019-09-19 16:59:01 +01001682 } else {
1683 // Doze wakelock acquired (doze started) or device is no longer dozing.
1684 mDozeStartInProgress = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001685 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001686 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1687 logSleepTimeoutRecapturedLocked();
1688 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001689 if (mWakefulness == WAKEFULNESS_AWAKE) {
Michael Wrighte3001042019-02-05 00:13:14 +00001690 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1691 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1692 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1693 Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1694 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001695 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001696 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001697 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001698 }
1699 }
1700
Jeff Brown96307042012-07-27 15:51:34 -07001701 /**
1702 * Updates the global power state based on dirty bits recorded in mDirty.
1703 *
1704 * This is the main function that performs power state transitions.
1705 * We centralize them here so that we can recompute the power state completely
1706 * each time something important changes, and ensure that we do it the same
1707 * way each time. The point is to gather all of the transition logic here.
1708 */
1709 private void updatePowerStateLocked() {
1710 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001711 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001712 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001713 if (!Thread.holdsLock(mLock)) {
1714 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1715 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001716
Jeff Brown3edf5272014-08-14 19:25:14 -07001717 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1718 try {
1719 // Phase 0: Basic state updates.
1720 updateIsPoweredLocked(mDirty);
1721 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001722 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001723
Jeff Brown3edf5272014-08-14 19:25:14 -07001724 // Phase 1: Update wakefulness.
1725 // Loop because the wake lock and user activity computations are influenced
1726 // by changes in wakefulness.
1727 final long now = SystemClock.uptimeMillis();
1728 int dirtyPhase2 = 0;
1729 for (;;) {
1730 int dirtyPhase1 = mDirty;
1731 dirtyPhase2 |= dirtyPhase1;
1732 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001733
Jeff Brown3edf5272014-08-14 19:25:14 -07001734 updateWakeLockSummaryLocked(dirtyPhase1);
1735 updateUserActivitySummaryLocked(now, dirtyPhase1);
Robert Horvath5560f382019-07-10 10:46:38 +02001736 updateAttentiveStateLocked(now, dirtyPhase1);
Jeff Brown3edf5272014-08-14 19:25:14 -07001737 if (!updateWakefulnessLocked(dirtyPhase1)) {
1738 break;
1739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001741
Pavel Grafov28939982017-10-03 15:11:52 +01001742 // Phase 2: Lock profiles that became inactive/not kept awake.
1743 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001744
Pavel Grafov28939982017-10-03 15:11:52 +01001745 // Phase 3: Update display power state.
1746 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1747
1748 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001749 updateDreamLocked(dirtyPhase2, displayBecameReady);
1750
Pavel Grafov28939982017-10-03 15:11:52 +01001751 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001752 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001753
Pavel Grafov28939982017-10-03 15:11:52 +01001754 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001755 // Because we might release the last suspend blocker here, we need to make sure
1756 // we finished everything else first!
1757 updateSuspendBlockerLocked();
1758 } finally {
1759 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
Jeff Brown96307042012-07-27 15:51:34 -07001761 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001762
Jim Miller92e66dd2012-02-21 18:57:12 -08001763 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001764 * Check profile timeouts and notify profiles that should be locked.
1765 */
1766 private void updateProfilesLocked(long now) {
1767 final int numProfiles = mProfilePowerState.size();
1768 for (int i = 0; i < numProfiles; i++) {
1769 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1770 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1771 profile.mLockingNotified = false;
1772 } else if (!profile.mLockingNotified) {
1773 profile.mLockingNotified = true;
1774 mNotifier.onProfileTimeout(profile.mUserId);
1775 }
1776 }
1777 }
1778
1779 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1780 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1781 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1782 || (mProximityPositive &&
1783 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1784 }
1785
1786 /**
Jeff Brown96307042012-07-27 15:51:34 -07001787 * Updates the value of mIsPowered.
1788 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001789 */
Jeff Brown96307042012-07-27 15:51:34 -07001790 private void updateIsPoweredLocked(int dirty) {
1791 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001792 final boolean wasPowered = mIsPowered;
1793 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001794 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001795 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1796 mPlugType = mBatteryManagerInternal.getPlugType();
1797 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1798 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001799
Jeff Brown26875502014-01-30 21:47:47 -08001800 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001801 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001802 + ", mIsPowered=" + mIsPowered
1803 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001804 + ", mPlugType=" + mPlugType
1805 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001806 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001807
Jeff Brownf3fb8952012-10-02 20:57:05 -07001808 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001809 mDirty |= DIRTY_IS_POWERED;
1810
Jeff Brown3b971592013-01-09 18:46:37 -08001811 // Update wireless dock detection state.
1812 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001813 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001814
Jeff Brown96307042012-07-27 15:51:34 -07001815 // Treat plugging and unplugging the devices as a user activity.
1816 // Users find it disconcerting when they plug or unplug the device
1817 // and it shuts off right away.
1818 // Some devices also wake the device when plugged or unplugged because
1819 // they don't have a charging LED.
1820 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001821 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1822 dockedOnWirelessCharger)) {
Michael Wrighte3001042019-02-05 00:13:14 +00001823 wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1824 "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001825 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001826 }
1827 userActivityNoUpdateLocked(
1828 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001829
Beverlyac32c9a2018-01-31 16:10:41 -05001830 // only play charging sounds if boot is completed so charging sounds don't play
1831 // with potential notification sounds
1832 if (mBootCompleted) {
1833 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1834 && BatteryManager.isPlugWired(mPlugType)) {
Beverly478722e2019-10-14 11:16:57 -04001835 mNotifier.onWiredChargingStarted(mUserId);
Beverlyac32c9a2018-01-31 16:10:41 -05001836 } else if (dockedOnWirelessCharger) {
Beverly478722e2019-10-14 11:16:57 -04001837 mNotifier.onWirelessChargingStarted(mBatteryLevel, mUserId);
Beverlyac32c9a2018-01-31 16:10:41 -05001838 }
Jeff Brown84e27562012-12-07 13:56:34 -08001839 }
Jeff Brown96307042012-07-27 15:51:34 -07001840 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001841
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001842 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001843 }
1844 }
1845
Jeff Brown3b971592013-01-09 18:46:37 -08001846 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1847 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001848 // Don't wake when powered unless configured to do so.
1849 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1850 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001851 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001852
Jeff Brown3b971592013-01-09 18:46:37 -08001853 // Don't wake when undocked from wireless charger.
1854 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001855 if (wasPowered && !mIsPowered
1856 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1857 return false;
1858 }
Jeff Brown3b971592013-01-09 18:46:37 -08001859
1860 // Don't wake when docked on wireless charger unless we are certain of it.
1861 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001862 if (!wasPowered && mIsPowered
1863 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001864 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001865 return false;
1866 }
1867
1868 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001869 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001870 return false;
1871 }
1872
Bryce Lee584a4452014-10-21 15:55:55 -07001873 // Don't wake while theater mode is enabled.
1874 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1875 return false;
1876 }
1877
Adrian Roos56021892017-02-27 20:25:09 +01001878 // On Always On Display, SystemUI shows the charging indicator
1879 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1880 return false;
1881 }
1882
Jeff Brown9fca9e92012-10-05 14:42:56 -07001883 // Otherwise wake up!
1884 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001885 }
1886
Jeff Brown96307042012-07-27 15:51:34 -07001887 /**
1888 * Updates the value of mStayOn.
1889 * Sets DIRTY_STAY_ON if a change occurred.
1890 */
1891 private void updateStayOnLocked(int dirty) {
1892 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001893 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001894 if (mStayOnWhilePluggedInSetting != 0
1895 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001896 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001897 } else {
1898 mStayOn = false;
1899 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001900
1901 if (mStayOn != wasStayOn) {
1902 mDirty |= DIRTY_STAY_ON;
1903 }
Jeff Brown96307042012-07-27 15:51:34 -07001904 }
1905 }
1906
1907 /**
1908 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1909 * Note that most wake-locks are ignored when the system is asleep.
1910 *
1911 * This function must have no other side-effects.
1912 */
Jeff Brownec083212013-09-11 20:45:25 -07001913 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001914 private void updateWakeLockSummaryLocked(int dirty) {
1915 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1916 mWakeLockSummary = 0;
1917
Pavel Grafov28939982017-10-03 15:11:52 +01001918 final int numProfiles = mProfilePowerState.size();
1919 for (int i = 0; i < numProfiles; i++) {
1920 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1921 }
1922
Jeff Brown96307042012-07-27 15:51:34 -07001923 final int numWakeLocks = mWakeLocks.size();
1924 for (int i = 0; i < numWakeLocks; i++) {
1925 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001926 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1927 mWakeLockSummary |= wakeLockFlags;
1928 for (int j = 0; j < numProfiles; j++) {
1929 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1930 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1931 profile.mWakeLockSummary |= wakeLockFlags;
1932 }
Jeff Brown96307042012-07-27 15:51:34 -07001933 }
1934 }
1935
Pavel Grafov28939982017-10-03 15:11:52 +01001936 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1937 for (int i = 0; i < numProfiles; i++) {
1938 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1939 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001940 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001941
Jeff Brown96307042012-07-27 15:51:34 -07001942 if (DEBUG_SPEW) {
1943 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001944 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001945 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1946 }
1947 }
1948 }
1949
Pavel Grafov28939982017-10-03 15:11:52 +01001950 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1951 // Cancel wake locks that make no sense based on the current state.
1952 if (mWakefulness != WAKEFULNESS_DOZING) {
1953 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1954 }
1955 if (mWakefulness == WAKEFULNESS_ASLEEP
1956 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1957 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1958 | WAKE_LOCK_BUTTON_BRIGHT);
1959 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1960 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1961 }
1962 }
1963
1964 // Infer implied wake locks where necessary based on the current state.
1965 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1966 if (mWakefulness == WAKEFULNESS_AWAKE) {
1967 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1968 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1969 wakeLockSummary |= WAKE_LOCK_CPU;
1970 }
1971 }
1972 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1973 wakeLockSummary |= WAKE_LOCK_CPU;
1974 }
1975
1976 return wakeLockSummary;
1977 }
1978
1979 /** Get wake lock summary flags that correspond to the given wake lock. */
1980 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1981 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1982 case PowerManager.PARTIAL_WAKE_LOCK:
1983 if (!wakeLock.mDisabled) {
1984 // We only respect this if the wake lock is not disabled.
1985 return WAKE_LOCK_CPU;
1986 }
1987 break;
1988 case PowerManager.FULL_WAKE_LOCK:
1989 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1990 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1991 return WAKE_LOCK_SCREEN_BRIGHT;
1992 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1993 return WAKE_LOCK_SCREEN_DIM;
1994 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1995 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1996 case PowerManager.DOZE_WAKE_LOCK:
1997 return WAKE_LOCK_DOZE;
1998 case PowerManager.DRAW_WAKE_LOCK:
1999 return WAKE_LOCK_DRAW;
2000 }
2001 return 0;
2002 }
2003
2004 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
2005 if (wakeLock.mWorkSource != null) {
2006 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
2007 final int uid = wakeLock.mWorkSource.get(k);
2008 if (userId == UserHandle.getUserId(uid)) {
2009 return true;
2010 }
2011 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00002012
2013 final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
2014 if (workChains != null) {
2015 for (int k = 0; k < workChains.size(); k++) {
2016 final int uid = workChains.get(k).getAttributionUid();
2017 if (userId == UserHandle.getUserId(uid)) {
2018 return true;
2019 }
2020 }
2021 }
Pavel Grafov28939982017-10-03 15:11:52 +01002022 }
2023 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
2024 }
2025
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07002026 void checkForLongWakeLocks() {
2027 synchronized (mLock) {
2028 final long now = SystemClock.uptimeMillis();
2029 mNotifyLongDispatched = now;
2030 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
2031 long nextCheckTime = Long.MAX_VALUE;
2032 final int numWakeLocks = mWakeLocks.size();
2033 for (int i = 0; i < numWakeLocks; i++) {
2034 final WakeLock wakeLock = mWakeLocks.get(i);
2035 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2036 == PowerManager.PARTIAL_WAKE_LOCK) {
2037 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
2038 if (wakeLock.mAcquireTime < when) {
2039 // This wake lock has exceeded the long acquire time, report!
2040 notifyWakeLockLongStartedLocked(wakeLock);
2041 } else {
2042 // This wake lock could still become a long one, at this time.
2043 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
2044 if (checkTime < nextCheckTime) {
2045 nextCheckTime = checkTime;
2046 }
2047 }
2048 }
2049 }
2050 }
2051 mNotifyLongScheduled = 0;
2052 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2053 if (nextCheckTime != Long.MAX_VALUE) {
2054 mNotifyLongNextCheck = nextCheckTime;
2055 enqueueNotifyLongMsgLocked(nextCheckTime);
2056 } else {
2057 mNotifyLongNextCheck = 0;
2058 }
2059 }
2060 }
2061
Jeff Brown96307042012-07-27 15:51:34 -07002062 /**
2063 * Updates the value of mUserActivitySummary to summarize the user requested
2064 * state of the system such as whether the screen should be bright or dim.
2065 * Note that user activity is ignored when the system is asleep.
2066 *
2067 * This function must have no other side-effects.
2068 */
2069 private void updateUserActivitySummaryLocked(long now, int dirty) {
2070 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07002071 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08002072 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002073 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2074
2075 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08002076 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002077 || mWakefulness == WAKEFULNESS_DREAMING
2078 || mWakefulness == WAKEFULNESS_DOZING) {
Robert Horvath5560f382019-07-10 10:46:38 +02002079 final long attentiveTimeout = getAttentiveTimeoutLocked();
2080 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
2081 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout,
2082 attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01002083 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002084 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002085 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002086
2087 mUserActivitySummary = 0;
2088 if (mLastUserActivityTime >= mLastWakeTime) {
2089 nextTimeout = mLastUserActivityTime
2090 + screenOffTimeout - screenDimDuration;
2091 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002092 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002093 } else {
2094 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2095 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002096 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002097 }
2098 }
2099 }
2100 if (mUserActivitySummary == 0
2101 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2102 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002103 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002104 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2105 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002106 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2107 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2108 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2109 }
Jeff Brown96307042012-07-27 15:51:34 -07002110 }
2111 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002112
Jeff Brown05af6ad2014-09-30 20:54:30 -07002113 if (mUserActivitySummary == 0) {
2114 if (sleepTimeout >= 0) {
2115 final long anyUserActivity = Math.max(mLastUserActivityTime,
2116 mLastUserActivityTimeNoChangeLights);
2117 if (anyUserActivity >= mLastWakeTime) {
2118 nextTimeout = anyUserActivity + sleepTimeout;
2119 if (now < nextTimeout) {
2120 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2121 }
2122 }
2123 } else {
2124 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2125 nextTimeout = -1;
2126 }
2127 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002128
2129 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002130 if ((mUserActivitySummary &
2131 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002132 // Device is being kept awake by recent user activity
2133 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2134 // Save when the next timeout would have occurred
2135 mOverriddenTimeout = nextTimeout;
2136 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002137 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002138 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2139 nextTimeout = -1;
2140 }
2141
Alex Salo9e242232019-05-14 19:27:17 -07002142 if ((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
2143 && (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) == 0) {
Lucas Dupin0a5d7972019-01-16 18:52:30 -08002144 nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout);
2145 }
2146
Pavel Grafov28939982017-10-03 15:11:52 +01002147 if (nextProfileTimeout > 0) {
2148 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2149 }
2150
Jeff Brown05af6ad2014-09-30 20:54:30 -07002151 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002152 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002153 }
2154 } else {
2155 mUserActivitySummary = 0;
2156 }
2157
2158 if (DEBUG_SPEW) {
2159 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002160 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002161 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2162 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2163 }
2164 }
2165 }
2166
Pavel Grafov28939982017-10-03 15:11:52 +01002167 private void scheduleUserInactivityTimeout(long timeMs) {
2168 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2169 msg.setAsynchronous(true);
2170 mHandler.sendMessageAtTime(msg, timeMs);
2171 }
2172
Robert Horvath5560f382019-07-10 10:46:38 +02002173 private void scheduleAttentiveTimeout(long timeMs) {
2174 final Message msg = mHandler.obtainMessage(MSG_ATTENTIVE_TIMEOUT);
2175 msg.setAsynchronous(true);
2176 mHandler.sendMessageAtTime(msg, timeMs);
2177 }
2178
Pavel Grafov28939982017-10-03 15:11:52 +01002179 /**
2180 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2181 */
2182 private long getNextProfileTimeoutLocked(long now) {
2183 long nextTimeout = -1;
2184 final int numProfiles = mProfilePowerState.size();
2185 for (int i = 0; i < numProfiles; i++) {
2186 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2187 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2188 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2189 nextTimeout = timeout;
2190 }
2191 }
2192 return nextTimeout;
2193 }
2194
Robert Horvath5560f382019-07-10 10:46:38 +02002195 private void updateAttentiveStateLocked(long now, int dirty) {
2196 long attentiveTimeout = getAttentiveTimeoutLocked();
2197 long goToSleepTime = mLastUserActivityTime + attentiveTimeout;
2198 long showWarningTime = goToSleepTime - mAttentiveWarningDurationConfig;
2199
2200 boolean warningDismissed = maybeHideInattentiveSleepWarningLocked(now, showWarningTime);
2201
2202 if (attentiveTimeout >= 0 && (warningDismissed
2203 || (dirty & (DIRTY_ATTENTIVE | DIRTY_STAY_ON | DIRTY_SCREEN_BRIGHTNESS_BOOST
2204 | DIRTY_PROXIMITY_POSITIVE | DIRTY_WAKEFULNESS | DIRTY_BOOT_COMPLETED
2205 | DIRTY_SETTINGS)) != 0)) {
2206 if (DEBUG_SPEW) {
2207 Slog.d(TAG, "Updating attentive state");
2208 }
2209
2210 mHandler.removeMessages(MSG_ATTENTIVE_TIMEOUT);
2211
2212 if (isBeingKeptFromShowingInattentiveSleepWarningLocked()) {
2213 return;
2214 }
2215
2216 long nextTimeout = -1;
2217
2218 if (now < showWarningTime) {
2219 nextTimeout = showWarningTime;
2220 } else if (now < goToSleepTime) {
2221 if (DEBUG) {
2222 long timeToSleep = goToSleepTime - now;
2223 Slog.d(TAG, "Going to sleep in " + timeToSleep
2224 + "ms if there is no user activity");
2225 }
2226 mInattentiveSleepWarningOverlayController.show();
2227 nextTimeout = goToSleepTime;
2228 } else {
2229 if (DEBUG && mWakefulness != WAKEFULNESS_ASLEEP) {
2230 Slog.i(TAG, "Going to sleep now due to long user inactivity");
2231 }
2232 }
2233
2234 if (nextTimeout >= 0) {
2235 scheduleAttentiveTimeout(nextTimeout);
2236 }
2237 }
2238 }
2239
2240 private boolean maybeHideInattentiveSleepWarningLocked(long now, long showWarningTime) {
2241 long attentiveTimeout = getAttentiveTimeoutLocked();
2242
Robert Horvath60e51fe2019-08-20 13:10:34 +02002243 if (!mInattentiveSleepWarningOverlayController.isShown()) {
2244 return false;
2245 }
2246
2247 if (mWakefulness != WAKEFULNESS_AWAKE) {
2248 mInattentiveSleepWarningOverlayController.dismiss(false);
2249 return true;
2250 } else if (attentiveTimeout < 0 || isBeingKeptFromShowingInattentiveSleepWarningLocked()
2251 || now < showWarningTime) {
2252 mInattentiveSleepWarningOverlayController.dismiss(true);
Robert Horvath5560f382019-07-10 10:46:38 +02002253 return true;
2254 }
2255
2256 return false;
2257 }
2258
2259 private boolean isAttentiveTimeoutExpired(long now) {
2260 long attentiveTimeout = getAttentiveTimeoutLocked();
2261 return attentiveTimeout >= 0 && now > mLastUserActivityTime + attentiveTimeout;
2262 }
2263
Jeff Brown96307042012-07-27 15:51:34 -07002264 /**
2265 * Called when a user activity timeout has occurred.
2266 * Simply indicates that something about user activity has changed so that the new
2267 * state can be recomputed when the power state is updated.
2268 *
2269 * This function must have no other side-effects besides setting the dirty
2270 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2271 */
2272 private void handleUserActivityTimeout() { // runs on handler thread
2273 synchronized (mLock) {
2274 if (DEBUG_SPEW) {
2275 Slog.d(TAG, "handleUserActivityTimeout");
2276 }
2277
2278 mDirty |= DIRTY_USER_ACTIVITY;
2279 updatePowerStateLocked();
2280 }
2281 }
2282
Robert Horvath5560f382019-07-10 10:46:38 +02002283 private void handleAttentiveTimeout() { // runs on handler thread
2284 synchronized (mLock) {
2285 if (DEBUG_SPEW) {
2286 Slog.d(TAG, "handleAttentiveTimeout");
2287 }
2288
2289 mDirty |= DIRTY_ATTENTIVE;
2290 updatePowerStateLocked();
2291 }
2292 }
2293
2294 private long getAttentiveTimeoutLocked() {
2295 long timeout = mAttentiveTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002296 if (timeout <= 0) {
2297 return -1;
2298 }
Robert Horvath5560f382019-07-10 10:46:38 +02002299
2300 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2301 }
2302
2303 private long getSleepTimeoutLocked(long attentiveTimeout) {
2304 long timeout = mSleepTimeoutSetting;
2305 if (timeout <= 0) {
2306 return -1;
2307 }
2308 if (attentiveTimeout >= 0) {
2309 timeout = Math.min(timeout, attentiveTimeout);
2310 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002311 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2312 }
2313
Robert Horvath5560f382019-07-10 10:46:38 +02002314 private long getScreenOffTimeoutLocked(long sleepTimeout, long attentiveTimeout) {
Pavel Grafov28939982017-10-03 15:11:52 +01002315 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002316 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2317 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2318 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002319 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002320 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002321 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002322 if (sleepTimeout >= 0) {
2323 timeout = Math.min(timeout, sleepTimeout);
2324 }
Robert Horvath5560f382019-07-10 10:46:38 +02002325 if (attentiveTimeout >= 0) {
2326 timeout = Math.min(timeout, attentiveTimeout);
2327 }
Jeff Brown27736f52014-05-20 17:17:10 -07002328 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002329 }
2330
Pavel Grafov28939982017-10-03 15:11:52 +01002331 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002332 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002333 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002334 }
2335
2336 /**
2337 * Updates the wakefulness of the device.
2338 *
Jeff Brown26875502014-01-30 21:47:47 -08002339 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002340 * based on the current wake locks and user activity state. It may modify mDirty
2341 * if the wakefulness changes.
2342 *
2343 * Returns true if the wakefulness changed and we need to restart power state calculation.
2344 */
2345 private boolean updateWakefulnessLocked(int dirty) {
2346 boolean changed = false;
2347 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002348 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
Robert Horvath5560f382019-07-10 10:46:38 +02002349 | DIRTY_DOCK_STATE | DIRTY_ATTENTIVE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002350 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2351 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002352 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002353 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002354 final long time = SystemClock.uptimeMillis();
Robert Horvath5560f382019-07-10 10:46:38 +02002355 if (isAttentiveTimeoutExpired(time)) {
2356 changed = goToSleepNoUpdateLocked(time, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
2357 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, Process.SYSTEM_UID);
2358 } else if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002359 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002360 } else {
2361 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002362 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002363 }
Jeff Brown96307042012-07-27 15:51:34 -07002364 }
2365 }
2366 return changed;
2367 }
2368
Jeff Brown645832d2012-10-03 14:57:03 -07002369 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002370 * Returns true if the device should automatically nap and start dreaming when the user
2371 * activity timeout has expired and it's bedtime.
2372 */
2373 private boolean shouldNapAtBedTimeLocked() {
2374 return mDreamsActivateOnSleepSetting
2375 || (mDreamsActivateOnDockSetting
2376 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2377 }
2378
2379 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002380 * Returns true if the device should go to sleep now.
2381 * Also used when exiting a dream to determine whether we should go back
2382 * to being fully awake or else go to sleep for good.
2383 */
Jeff Brown96307042012-07-27 15:51:34 -07002384 private boolean isItBedTimeYetLocked() {
Robert Horvath5560f382019-07-10 10:46:38 +02002385 if (!mBootCompleted) {
2386 return false;
2387 }
2388
2389 long now = SystemClock.uptimeMillis();
2390 if (isAttentiveTimeoutExpired(now)) {
2391 return !isBeingKeptFromInattentiveSleepLocked();
2392 } else {
2393 return !isBeingKeptAwakeLocked();
2394 }
Jeff Brown645832d2012-10-03 14:57:03 -07002395 }
2396
2397 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002398 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002399 * or the stay on while powered setting. We also keep the phone awake when
2400 * the proximity sensor returns a positive result so that the device does not
2401 * lock while in a phone call. This function only controls whether the device
2402 * will go to sleep or dream which is independent of whether it will be allowed
2403 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002404 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002405 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002406 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002407 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002408 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002409 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002410 | USER_ACTIVITY_SCREEN_DIM)) != 0
2411 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002412 }
2413
2414 /**
Robert Horvath5560f382019-07-10 10:46:38 +02002415 * Returns true if the device is prevented from going into inattentive sleep by the stay on
2416 * while powered setting. We also keep the device awake when the proximity sensor returns a
2417 * positive result so that the device does not lock while in a phone call. This function only
2418 * controls whether the device will go to sleep which is independent of whether it will be
2419 * allowed to suspend.
2420 */
2421 private boolean isBeingKeptFromInattentiveSleepLocked() {
2422 return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive
2423 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2424 | USER_ACTIVITY_SCREEN_DIM)) != 0;
2425 }
2426
2427 private boolean isBeingKeptFromShowingInattentiveSleepWarningLocked() {
2428 return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive || !mBootCompleted;
2429 }
2430
2431 /**
Jeff Brown96307042012-07-27 15:51:34 -07002432 * Determines whether to post a message to the sandman to update the dream state.
2433 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002434 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002435 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002436 | DIRTY_USER_ACTIVITY
Robert Horvath5560f382019-07-10 10:46:38 +02002437 | DIRTY_ATTENTIVE
Jeff Brown645832d2012-10-03 14:57:03 -07002438 | DIRTY_WAKE_LOCKS
2439 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002440 | DIRTY_SETTINGS
2441 | DIRTY_IS_POWERED
2442 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002443 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002444 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2445 if (mDisplayReady) {
2446 scheduleSandmanLocked();
2447 }
Jeff Brown96307042012-07-27 15:51:34 -07002448 }
2449 }
2450
2451 private void scheduleSandmanLocked() {
2452 if (!mSandmanScheduled) {
2453 mSandmanScheduled = true;
2454 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2455 msg.setAsynchronous(true);
2456 mHandler.sendMessage(msg);
2457 }
2458 }
2459
2460 /**
Jeff Brown26875502014-01-30 21:47:47 -08002461 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002462 *
2463 * We do this asynchronously because we must call out of the power manager to start
2464 * the dream and we don't want to hold our lock while doing so. There is a risk that
2465 * the device will wake or go to sleep in the meantime so we have to handle that case.
2466 */
2467 private void handleSandman() { // runs on handler thread
2468 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002469 final boolean startDreaming;
2470 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002471 synchronized (mLock) {
2472 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002473 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002474 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002475 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002476 mSandmanSummoned = false;
2477 } else {
2478 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002479 }
2480 }
2481
Jeff Brown96307042012-07-27 15:51:34 -07002482 // Start dreaming if needed.
2483 // We only control the dream on the handler thread, so we don't need to worry about
2484 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002485 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002486 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002487 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002488 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002489 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002490 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002491 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002492 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002493 } else {
2494 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002495 }
2496
Santos Cordon03044382019-09-19 16:59:01 +01002497 // At this point, we either attempted to start the dream or no attempt will be made,
2498 // so stop holding the display suspend blocker for Doze.
2499 mDozeStartInProgress = false;
2500
Jeff Brown96307042012-07-27 15:51:34 -07002501 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002502 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002503 // Remember the initial battery level when the dream started.
2504 if (startDreaming && isDreaming) {
2505 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2506 if (wakefulness == WAKEFULNESS_DOZING) {
2507 Slog.i(TAG, "Dozing...");
2508 } else {
2509 Slog.i(TAG, "Dreaming...");
2510 }
2511 }
2512
2513 // If preconditions changed, wait for the next iteration to determine
2514 // whether the dream should continue (or be restarted).
2515 if (mSandmanSummoned || mWakefulness != wakefulness) {
2516 return; // wait for next cycle
2517 }
2518
2519 // Determine whether the dream should continue.
Robert Horvath5560f382019-07-10 10:46:38 +02002520 long now = SystemClock.uptimeMillis();
Jeff Brown26875502014-01-30 21:47:47 -08002521 if (wakefulness == WAKEFULNESS_DREAMING) {
2522 if (isDreaming && canDreamLocked()) {
2523 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002524 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002525 - mDreamsBatteryLevelDrainCutoffConfig
2526 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002527 // If the user activity timeout expired and the battery appears
2528 // to be draining faster than it is charging then stop dreaming
2529 // and go to sleep.
2530 Slog.i(TAG, "Stopping dream because the battery appears to "
2531 + "be draining faster than it is charging. "
2532 + "Battery level when dream started: "
2533 + mBatteryLevelWhenDreamStarted + "%. "
2534 + "Battery level now: " + mBatteryLevel + "%.");
2535 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002536 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002537 }
Jeff Brown96307042012-07-27 15:51:34 -07002538 }
Jeff Brown26875502014-01-30 21:47:47 -08002539
2540 // Dream has ended or will be stopped. Update the power state.
2541 if (isItBedTimeYetLocked()) {
Robert Horvath5560f382019-07-10 10:46:38 +02002542 int flags = 0;
2543 if (isAttentiveTimeoutExpired(now)) {
2544 flags |= PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE;
2545 }
2546 goToSleepNoUpdateLocked(now, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, flags,
2547 Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002548 updatePowerStateLocked();
2549 } else {
Robert Horvath5560f382019-07-10 10:46:38 +02002550 wakeUpNoUpdateLocked(now,
Michael Wrighte3001042019-02-05 00:13:14 +00002551 PowerManager.WAKE_REASON_UNKNOWN,
2552 "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2553 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002554 updatePowerStateLocked();
2555 }
2556 } else if (wakefulness == WAKEFULNESS_DOZING) {
2557 if (isDreaming) {
2558 return; // continue dozing
2559 }
2560
2561 // Doze has ended or will be stopped. Update the power state.
Robert Horvath5560f382019-07-10 10:46:38 +02002562 reallyGoToSleepNoUpdateLocked(now, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002563 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002564 }
Jeff Brown96307042012-07-27 15:51:34 -07002565 }
2566
Jeff Brown26875502014-01-30 21:47:47 -08002567 // Stop dream.
2568 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002569 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002570 }
2571 }
2572
2573 /**
Jeff Brown26875502014-01-30 21:47:47 -08002574 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002575 */
2576 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002577 if (mWakefulness != WAKEFULNESS_DREAMING
2578 || !mDreamsSupportedConfig
2579 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002580 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002581 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002582 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2583 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002584 || !mBootCompleted) {
2585 return false;
2586 }
2587 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002588 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002589 return false;
2590 }
2591 if (!mIsPowered
2592 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2593 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2594 return false;
2595 }
2596 if (mIsPowered
2597 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2598 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2599 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002600 }
2601 }
Jeff Brown26875502014-01-30 21:47:47 -08002602 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002603 }
2604
Jeff Brown96307042012-07-27 15:51:34 -07002605 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002606 * Returns true if the device is allowed to doze in its current state.
2607 */
2608 private boolean canDozeLocked() {
2609 return mWakefulness == WAKEFULNESS_DOZING;
2610 }
2611
2612 /**
Jeff Brown96307042012-07-27 15:51:34 -07002613 * Updates the display power state asynchronously.
2614 * When the update is finished, mDisplayReady will be set to true. The display
2615 * controller posts a message to tell us when the actual display power state
2616 * has been updated so we come back here to double-check and finish up.
2617 *
2618 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002619 *
2620 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002621 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002622 private boolean updateDisplayPowerStateLocked(int dirty) {
2623 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002624 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2625 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002626 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2627 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002628 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002629
Jeff Browne333e672014-10-28 13:48:55 -07002630 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002631 final boolean autoBrightness;
2632 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002633 if (!mBootCompleted) {
2634 // Keep the brightness steady during boot. This requires the
2635 // bootloader brightness and the default brightness to be identical.
2636 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002637 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002638 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002639 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002640 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2641 } else {
2642 autoBrightness = (mScreenBrightnessModeSetting ==
2643 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2644 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002645 }
Jeff Browne333e672014-10-28 13:48:55 -07002646
2647 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002648 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002649 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002650 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002651 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002652
jackqdyulei92681e82017-02-28 11:26:28 -08002653 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2654
Jeff Brown970d4132014-07-19 11:33:47 -07002655 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2656 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002657 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2658 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002659 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2660 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2661 }
2662 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2663 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2664 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002665 }
Jeff Brown970d4132014-07-19 11:33:47 -07002666 mDisplayPowerRequest.dozeScreenBrightness =
2667 mDozeScreenBrightnessOverrideFromDreamManager;
2668 } else {
2669 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2670 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2671 }
2672
Jeff Brown131206b2014-04-08 17:27:14 -07002673 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002674 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002675 mRequestWaitForNegativeProximity = false;
2676
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002677 if ((dirty & DIRTY_QUIESCENT) != 0) {
2678 sQuiescent = false;
2679 }
Jeff Brown96307042012-07-27 15:51:34 -07002680 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002681 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002682 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002683 + ", mWakefulness=" + mWakefulness
2684 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2685 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002686 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002687 + ", screenBrightnessOverride=" + screenBrightnessOverride
2688 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002689 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002690 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002691 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002692 }
2693 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002694 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002695 }
2696
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002697 private void updateScreenBrightnessBoostLocked(int dirty) {
2698 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2699 if (mScreenBrightnessBoostInProgress) {
2700 final long now = SystemClock.uptimeMillis();
2701 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2702 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2703 final long boostTimeout = mLastScreenBrightnessBoostTime +
2704 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2705 if (boostTimeout > now) {
2706 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2707 msg.setAsynchronous(true);
2708 mHandler.sendMessageAtTime(msg, boostTimeout);
2709 return;
2710 }
Jeff Browne333e672014-10-28 13:48:55 -07002711 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002712 mScreenBrightnessBoostInProgress = false;
2713 userActivityNoUpdateLocked(now,
2714 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002715 }
Jeff Browne333e672014-10-28 13:48:55 -07002716 }
2717 }
2718
Santos Cordon3107d292016-09-20 15:50:35 -07002719 private boolean shouldBoostScreenBrightness() {
2720 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2721 }
2722
Jeff Brown96307042012-07-27 15:51:34 -07002723 private static boolean isValidBrightness(int value) {
2724 return value >= 0 && value <= 255;
2725 }
2726
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002727 @VisibleForTesting
2728 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002729 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002730 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002731 }
2732
Jeff Brown2175e9c2014-09-12 16:11:07 -07002733 if (mWakefulness == WAKEFULNESS_DOZING) {
2734 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2735 return DisplayPowerRequest.POLICY_DOZE;
2736 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002737 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002738 return DisplayPowerRequest.POLICY_OFF;
2739 }
2740 // Fall through and preserve the current screen policy if not configured to
2741 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002742 }
2743
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002744 // It is important that POLICY_VR check happens after the wakefulness checks above so
2745 // that VR-mode does not prevent displays from transitioning to the correct state when
2746 // dozing or sleeping.
2747 if (mIsVrModeEnabled) {
2748 return DisplayPowerRequest.POLICY_VR;
2749 }
2750
Jeff Brown96307042012-07-27 15:51:34 -07002751 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2752 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002753 || !mBootCompleted
2754 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002755 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002756 }
2757
Jeff Brown970d4132014-07-19 11:33:47 -07002758 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002759 }
2760
Jeff Brown131206b2014-04-08 17:27:14 -07002761 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2762 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002763 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002764
Jeff Brown96307042012-07-27 15:51:34 -07002765 @Override
2766 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002767 synchronized (mLock) {
2768 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2769 updatePowerStateLocked();
2770 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002771 }
2772
2773 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002774 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002775 synchronized (mLock) {
2776 mProximityPositive = true;
2777 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2778 updatePowerStateLocked();
2779 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002780 }
2781
2782 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002783 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002784 synchronized (mLock) {
2785 mProximityPositive = false;
2786 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2787 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2788 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2789 updatePowerStateLocked();
2790 }
Jeff Brown96307042012-07-27 15:51:34 -07002791 }
Jeff Brown131206b2014-04-08 17:27:14 -07002792
2793 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002794 public void onDisplayStateChange(int state) {
2795 // This method is only needed to support legacy display blanking behavior
2796 // where the display's power state is coupled to suspend or to the power HAL.
2797 // The order of operations matters here.
2798 synchronized (mLock) {
2799 if (mDisplayState != state) {
2800 mDisplayState = state;
2801 if (state == Display.STATE_OFF) {
2802 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2803 setHalInteractiveModeLocked(false);
2804 }
2805 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2806 setHalAutoSuspendModeLocked(true);
2807 }
2808 } else {
2809 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2810 setHalAutoSuspendModeLocked(false);
2811 }
2812 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2813 setHalInteractiveModeLocked(true);
2814 }
2815 }
2816 }
2817 }
2818 }
2819
2820 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002821 public void acquireSuspendBlocker() {
2822 mDisplaySuspendBlocker.acquire();
2823 }
2824
2825 @Override
2826 public void releaseSuspendBlocker() {
2827 mDisplaySuspendBlocker.release();
2828 }
2829
2830 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002831 public String toString() {
2832 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002833 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002834 }
2835 }
Jeff Brown96307042012-07-27 15:51:34 -07002836 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002837
Jeff Brown96307042012-07-27 15:51:34 -07002838 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002839 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002840 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002841
Jeff Brown96307042012-07-27 15:51:34 -07002842 /**
2843 * Updates the suspend blocker that keeps the CPU alive.
2844 *
2845 * This function must have no other side-effects.
2846 */
2847 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002848 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002849 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2850 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002851 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002852
2853 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002854 // FIXME We should consider just leaving auto-suspend enabled forever since
2855 // we already hold the necessary wakelocks.
2856 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2857 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002858 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002859
2860 // First acquire suspend blockers if needed.
2861 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2862 mWakeLockSuspendBlocker.acquire();
2863 mHoldingWakeLockSuspendBlocker = true;
2864 }
2865 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2866 mDisplaySuspendBlocker.acquire();
2867 mHoldingDisplaySuspendBlocker = true;
2868 }
2869
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002870 // Inform the power HAL about interactive mode.
2871 // Although we could set interactive strictly based on the wakefulness
2872 // as reported by isInteractive(), it is actually more desirable to track
2873 // the display policy state instead so that the interactive state observed
2874 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2875 // Refer to getDesiredScreenPolicyLocked() for details.
2876 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2877 // When becoming non-interactive, we want to defer sending this signal
2878 // until the display is actually ready so that all transitions have
2879 // completed. This is probably a good sign that things have gotten
2880 // too tangled over here...
2881 if (interactive || mDisplayReady) {
2882 setHalInteractiveModeLocked(interactive);
2883 }
2884 }
2885
Jeff Brown27f7a862012-12-12 15:43:31 -08002886 // Then release suspend blockers if needed.
2887 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2888 mWakeLockSuspendBlocker.release();
2889 mHoldingWakeLockSuspendBlocker = false;
2890 }
2891 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2892 mDisplaySuspendBlocker.release();
2893 mHoldingDisplaySuspendBlocker = false;
2894 }
Jeff Brown26875502014-01-30 21:47:47 -08002895
2896 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002897 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2898 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002899 }
Jeff Brown96307042012-07-27 15:51:34 -07002900 }
2901
Jeff Brownec083212013-09-11 20:45:25 -07002902 /**
2903 * Return true if we must keep a suspend blocker active on behalf of the display.
2904 * We do so if the screen is on or is in transition between states.
2905 */
Jeff Brown26875502014-01-30 21:47:47 -08002906 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002907 if (!mDisplayReady) {
2908 return true;
2909 }
Jeff Brown970d4132014-07-19 11:33:47 -07002910 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002911 // If we asked for the screen to be on but it is off due to the proximity
2912 // sensor then we may suspend but only if the configuration allows it.
2913 // On some hardware it may not be safe to suspend because the proximity
2914 // sensor may not be correctly configured as a wake-up source.
2915 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2916 || !mSuspendWhenScreenOffDueToProximityConfig) {
2917 return true;
2918 }
2919 }
Santos Cordond9701ab2019-08-01 18:33:20 +01002920
2921 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE
2922 && mDisplayPowerRequest.dozeScreenState == Display.STATE_ON) {
2923 // Although we are in DOZE and would normally allow the device to suspend,
2924 // the doze service has explicitly requested the display to remain in the ON
2925 // state which means we should hold the display suspend blocker.
2926 return true;
2927 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002928 if (mScreenBrightnessBoostInProgress) {
2929 return true;
2930 }
Santos Cordon03044382019-09-19 16:59:01 +01002931
2932 // When we transition to DOZING, we have to keep the display suspend blocker
2933 // up until the Doze service has a change to acquire the DOZE wakelock.
2934 // Here we wait for mWakefulnessChanging to become false since the wakefulness
2935 // transition to DOZING isn't considered "changed" until the doze wake lock is
2936 // acquired.
2937 if (mWakefulness == WAKEFULNESS_DOZING && mDozeStartInProgress) {
2938 return true;
2939 }
2940
Jeff Brown26875502014-01-30 21:47:47 -08002941 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002942 return false;
2943 }
2944
Jeff Brown037c33e2014-04-09 00:31:55 -07002945 private void setHalAutoSuspendModeLocked(boolean enable) {
2946 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002947 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002948 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002949 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002950 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002951 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2952 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002953 mNativeWrapper.nativeSetAutoSuspend(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002954 } finally {
2955 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2956 }
Jeff Brown26875502014-01-30 21:47:47 -08002957 }
2958 }
2959
Jeff Brown037c33e2014-04-09 00:31:55 -07002960 private void setHalInteractiveModeLocked(boolean enable) {
2961 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002962 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002963 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002964 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002965 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002966 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2967 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002968 mNativeWrapper.nativeSetInteractive(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002969 } finally {
2970 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2971 }
Jeff Brown26875502014-01-30 21:47:47 -08002972 }
2973 }
2974
Jeff Brown037c33e2014-04-09 00:31:55 -07002975 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002976 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002977 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002978 }
2979 }
2980
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002981 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002982 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002983 if (DEBUG) {
2984 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2985 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002986 if (mIsPowered) {
2987 return false;
2988 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002989
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002990 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002991
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002992 return true;
2993 }
2994 }
2995
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002996 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002997 synchronized (mLock) {
2998 return mDeviceIdleMode;
2999 }
3000 }
3001
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003002 boolean isLightDeviceIdleModeInternal() {
3003 synchronized (mLock) {
3004 return mLightDeviceIdleMode;
3005 }
3006 }
3007
Jeff Brown96307042012-07-27 15:51:34 -07003008 private void handleBatteryStateChangedLocked() {
3009 mDirty |= DIRTY_BATTERY_STATE;
3010 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003011 }
3012
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003013 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003014 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07003015 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07003016 if (RescueParty.isAttemptingFactoryReset()) {
3017 // If we're stuck in a really low-level reboot loop, and a
3018 // rescue party is trying to prompt the user for a factory data
3019 // reset, we must GET TO DA CHOPPA!
3020 PowerManagerService.lowLevelReboot(reason);
3021 } else {
3022 throw new IllegalStateException("Too early to call shutdown() or reboot()");
3023 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003024 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003025
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003026 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07003027 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003028 public void run() {
3029 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003030 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003031 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003032 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003033 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003034 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003035 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003036 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003037 }
San Mehat1e512792010-01-07 10:40:29 -08003038 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003039 };
Jeff Brown96307042012-07-27 15:51:34 -07003040
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003041 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00003042 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07003043 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00003044 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003045
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003046 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003047 if (wait) {
3048 synchronized (runnable) {
3049 while (true) {
3050 try {
3051 runnable.wait();
3052 } catch (InterruptedException e) {
3053 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003054 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003055 }
Doug Zongker50a21f42009-11-19 12:49:53 -08003056 }
3057 }
3058
Jeff Brown96307042012-07-27 15:51:34 -07003059 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08003060 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07003061 @Override
Jeff Brown96307042012-07-27 15:51:34 -07003062 public void run() {
3063 throw new RuntimeException(message);
3064 }
Dan Egnor60d87622009-12-16 16:32:58 -08003065 };
3066 try {
3067 t.start();
3068 t.join();
3069 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07003070 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08003071 }
3072 }
3073
jackqdyulei92681e82017-02-28 11:26:28 -08003074 @VisibleForTesting
3075 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
3076 PowerSaveState state = mBatterySaverPolicy.
Kweku Adams9f488e22019-01-14 16:25:08 -08003077 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
jackqdyulei92681e82017-02-28 11:26:28 -08003078 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
3079 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
3080 }
3081
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003082 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07003083 Settings.Global.putInt(mContext.getContentResolver(),
3084 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003085 }
3086
Pavel Grafov28939982017-10-03 15:11:52 +01003087 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
3088 if (userId < 0) {
3089 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
3090 return;
3091 }
Jeff Brown96307042012-07-27 15:51:34 -07003092 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01003093 // System-wide timeout
3094 if (userId == UserHandle.USER_SYSTEM) {
3095 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
3096 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
3097 mProfilePowerState.delete(userId);
3098 } else {
3099 final ProfilePowerState profile = mProfilePowerState.get(userId);
3100 if (profile != null) {
3101 profile.mScreenOffTimeout = timeMs;
3102 } else {
3103 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
3104 // We need to recalculate wake locks for the new profile state.
3105 mDirty |= DIRTY_WAKE_LOCKS;
3106 }
3107 }
Jeff Brown96307042012-07-27 15:51:34 -07003108 mDirty |= DIRTY_SETTINGS;
3109 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 }
3111 }
3112
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003113 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003114 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07003115 if (mDeviceIdleMode == enabled) {
3116 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003117 }
Felipe Lemeea014392016-09-06 13:59:54 -07003118 mDeviceIdleMode = enabled;
3119 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003120 }
Felipe Lemeea014392016-09-06 13:59:54 -07003121 if (enabled) {
3122 EventLogTags.writeDeviceIdleOnPhase("power");
3123 } else {
3124 EventLogTags.writeDeviceIdleOffPhase("power");
3125 }
3126 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003127 }
3128
3129 boolean setLightDeviceIdleModeInternal(boolean enabled) {
3130 synchronized (mLock) {
3131 if (mLightDeviceIdleMode != enabled) {
3132 mLightDeviceIdleMode = enabled;
3133 return true;
3134 }
3135 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003136 }
3137 }
3138
3139 void setDeviceIdleWhitelistInternal(int[] appids) {
3140 synchronized (mLock) {
3141 mDeviceIdleWhitelist = appids;
3142 if (mDeviceIdleMode) {
3143 updateWakeLockDisabledStatesLocked();
3144 }
3145 }
3146 }
3147
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003148 void setDeviceIdleTempWhitelistInternal(int[] appids) {
3149 synchronized (mLock) {
3150 mDeviceIdleTempWhitelist = appids;
3151 if (mDeviceIdleMode) {
3152 updateWakeLockDisabledStatesLocked();
3153 }
3154 }
3155 }
3156
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003157 void startUidChangesInternal() {
3158 synchronized (mLock) {
3159 mUidsChanging = true;
3160 }
3161 }
3162
3163 void finishUidChangesInternal() {
3164 synchronized (mLock) {
3165 mUidsChanging = false;
3166 if (mUidsChanged) {
3167 updateWakeLockDisabledStatesLocked();
3168 mUidsChanged = false;
3169 }
3170 }
3171 }
3172
3173 private void handleUidStateChangeLocked() {
3174 if (mUidsChanging) {
3175 mUidsChanged = true;
3176 } else {
3177 updateWakeLockDisabledStatesLocked();
3178 }
3179 }
3180
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003181 void updateUidProcStateInternal(int uid, int procState) {
3182 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003183 UidState state = mUidState.get(uid);
3184 if (state == null) {
3185 state = new UidState(uid);
3186 mUidState.put(uid, state);
3187 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07003188 final boolean oldShouldAllow = state.mProcState
3189 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003190 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07003191 if (state.mNumWakeLocks > 0) {
3192 if (mDeviceIdleMode) {
3193 handleUidStateChangeLocked();
3194 } else if (!state.mActive && oldShouldAllow !=
3195 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
3196 // If this uid is not active, but the process state has changed such
3197 // that we may still want to allow it to hold a wake lock, then take care of it.
3198 handleUidStateChangeLocked();
3199 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003200 }
3201 }
3202 }
3203
3204 void uidGoneInternal(int uid) {
3205 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003206 final int index = mUidState.indexOfKey(uid);
3207 if (index >= 0) {
3208 UidState state = mUidState.valueAt(index);
3209 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
3210 state.mActive = false;
3211 mUidState.removeAt(index);
3212 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
3213 handleUidStateChangeLocked();
3214 }
3215 }
3216 }
3217 }
3218
3219 void uidActiveInternal(int uid) {
3220 synchronized (mLock) {
3221 UidState state = mUidState.get(uid);
3222 if (state == null) {
3223 state = new UidState(uid);
3224 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3225 mUidState.put(uid, state);
3226 }
3227 state.mActive = true;
3228 if (state.mNumWakeLocks > 0) {
3229 handleUidStateChangeLocked();
3230 }
3231 }
3232 }
3233
3234 void uidIdleInternal(int uid) {
3235 synchronized (mLock) {
3236 UidState state = mUidState.get(uid);
3237 if (state != null) {
3238 state.mActive = false;
3239 if (state.mNumWakeLocks > 0) {
3240 handleUidStateChangeLocked();
3241 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003242 }
3243 }
3244 }
3245
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003246 private void updateWakeLockDisabledStatesLocked() {
3247 boolean changed = false;
3248 final int numWakeLocks = mWakeLocks.size();
3249 for (int i = 0; i < numWakeLocks; i++) {
3250 final WakeLock wakeLock = mWakeLocks.get(i);
3251 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003252 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003253 if (setWakeLockDisabledStateLocked(wakeLock)) {
3254 changed = true;
3255 if (wakeLock.mDisabled) {
3256 // This wake lock is no longer being respected.
3257 notifyWakeLockReleasedLocked(wakeLock);
3258 } else {
3259 notifyWakeLockAcquiredLocked(wakeLock);
3260 }
3261 }
3262 }
3263 }
3264 if (changed) {
3265 mDirty |= DIRTY_WAKE_LOCKS;
3266 updatePowerStateLocked();
3267 }
3268 }
3269
3270 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3271 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3272 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003273 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003274 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3275 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003276 // Cached inactive processes are never allowed to hold wake locks.
3277 if (mConstants.NO_CACHED_WAKE_LOCKS) {
Santos Cordon12f92eb2019-02-01 21:28:47 +00003278 disabled = mForceSuspendActive
3279 || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003280 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Santos Cordon12f92eb2019-02-01 21:28:47 +00003281 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003282 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003283 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003284 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003285 // for application uids that are not whitelisted.
3286 final UidState state = wakeLock.mUidState;
3287 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3288 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3289 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003290 state.mProcState >
3291 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003292 disabled = true;
3293 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003294 }
3295 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003296 if (wakeLock.mDisabled != disabled) {
3297 wakeLock.mDisabled = disabled;
3298 return true;
3299 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003300 }
3301 return false;
3302 }
3303
Jeff Brown96307042012-07-27 15:51:34 -07003304 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3305 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003306 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003308
Jeff Brown96307042012-07-27 15:51:34 -07003309 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003310 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003311 synchronized (mLock) {
3312 if (!mSystemReady) {
3313 return;
3314 }
3315 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003316 }
Jeff Brown96307042012-07-27 15:51:34 -07003317
3318 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003319 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003320 }
3321
Lucas Dupin16cfe452018-02-08 13:14:50 -08003322 private void setDozeAfterScreenOffInternal(boolean on) {
3323 synchronized (mLock) {
3324 mDozeAfterScreenOff = on;
3325 }
3326 }
3327
Jeff Browne333e672014-10-28 13:48:55 -07003328 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3329 synchronized (mLock) {
3330 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3331 || eventTime < mLastScreenBrightnessBoostTime) {
3332 return;
3333 }
3334
3335 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3336 mLastScreenBrightnessBoostTime = eventTime;
Kweku Adamsf94be8a2019-06-14 13:39:14 -07003337 mScreenBrightnessBoostInProgress = true;
Jeff Browne333e672014-10-28 13:48:55 -07003338 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3339
3340 userActivityNoUpdateLocked(eventTime,
3341 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3342 updatePowerStateLocked();
3343 }
3344 }
3345
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003346 private boolean isScreenBrightnessBoostedInternal() {
3347 synchronized (mLock) {
3348 return mScreenBrightnessBoostInProgress;
3349 }
3350 }
3351
Jeff Browne333e672014-10-28 13:48:55 -07003352 /**
3353 * Called when a screen brightness boost timeout has occurred.
3354 *
3355 * This function must have no other side-effects besides setting the dirty
3356 * bit and calling update power state.
3357 */
3358 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3359 synchronized (mLock) {
3360 if (DEBUG_SPEW) {
3361 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3362 }
3363
3364 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3365 updatePowerStateLocked();
3366 }
3367 }
3368
Jeff Brown96307042012-07-27 15:51:34 -07003369 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3370 synchronized (mLock) {
3371 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3372 mScreenBrightnessOverrideFromWindowManager = brightness;
3373 mDirty |= DIRTY_SETTINGS;
3374 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003375 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003376 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003377 }
3378
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003379 private void setUserInactiveOverrideFromWindowManagerInternal() {
3380 synchronized (mLock) {
3381 mUserInactiveOverrideFromWindowManager = true;
3382 mDirty |= DIRTY_USER_ACTIVITY;
3383 updatePowerStateLocked();
3384 }
3385 }
3386
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003387 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3388 synchronized (mLock) {
3389 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3390 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003391 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003392 mDirty |= DIRTY_SETTINGS;
3393 updatePowerStateLocked();
3394 }
3395 }
3396 }
3397
Jeff Brown970d4132014-07-19 11:33:47 -07003398 private void setDozeOverrideFromDreamManagerInternal(
3399 int screenState, int screenBrightness) {
3400 synchronized (mLock) {
3401 if (mDozeScreenStateOverrideFromDreamManager != screenState
3402 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3403 mDozeScreenStateOverrideFromDreamManager = screenState;
3404 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3405 mDirty |= DIRTY_SETTINGS;
3406 updatePowerStateLocked();
3407 }
3408 }
3409 }
3410
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003411 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3412 synchronized (mLock) {
3413 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3414 mDrawWakeLockOverrideFromSidekick = keepState;
3415 mDirty |= DIRTY_SETTINGS;
3416 updatePowerStateLocked();
3417 }
3418 }
3419 }
3420
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003421 @VisibleForTesting
3422 void setVrModeEnabled(boolean enabled) {
3423 mIsVrModeEnabled = enabled;
3424 }
3425
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003426 private void powerHintInternal(int hintId, int data) {
3427 // Maybe filter the event.
3428 switch (hintId) {
3429 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3430 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3431 return;
3432 }
3433 break;
3434 }
3435
Santos Cordon64a6e612018-08-22 19:27:04 +01003436 mNativeWrapper.nativeSendPowerHint(hintId, data);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003437 }
3438
Alex Kershaw2418ea92018-10-19 17:17:49 +01003439 @VisibleForTesting
3440 boolean wasDeviceIdleForInternal(long ms) {
3441 synchronized (mLock) {
3442 return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3443 }
3444 }
3445
3446 @VisibleForTesting
3447 void onUserActivity() {
3448 synchronized (mLock) {
3449 mLastUserActivityTime = SystemClock.uptimeMillis();
3450 }
3451 }
3452
Santos Cordon12f92eb2019-02-01 21:28:47 +00003453 private boolean forceSuspendInternal(int uid) {
3454 try {
3455 synchronized (mLock) {
3456 mForceSuspendActive = true;
3457 // Place the system in an non-interactive state
3458 goToSleepInternal(SystemClock.uptimeMillis(),
3459 PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3460 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3461
3462 // Disable all the partial wake locks as well
3463 updateWakeLockDisabledStatesLocked();
3464 }
3465
3466 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3467 boolean success = mNativeWrapper.nativeForceSuspend();
3468 if (!success) {
3469 Slog.i(TAG, "Force-Suspending failed in native.");
3470 }
3471 return success;
3472 } finally {
3473 synchronized (mLock) {
3474 mForceSuspendActive = false;
3475 // Re-enable wake locks once again.
3476 updateWakeLockDisabledStatesLocked();
3477 }
3478 }
3479 }
3480
Jeff Brown96307042012-07-27 15:51:34 -07003481 /**
3482 * Low-level function turn the device off immediately, without trying
3483 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003484 *
3485 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003486 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003487 public static void lowLevelShutdown(String reason) {
3488 if (reason == null) {
3489 reason = "";
3490 }
3491 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003492 }
3493
3494 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003495 * Low-level function to reboot the device. On success, this
3496 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003497 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003498 *
3499 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003500 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003501 public static void lowLevelReboot(String reason) {
3502 if (reason == null) {
3503 reason = "";
3504 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003505
3506 // If the reason is "quiescent", it means that the boot process should proceed
3507 // without turning on the screen/lights.
3508 // The "quiescent" property is sticky, meaning that any number
3509 // of subsequent reboots should honor the property until it is reset.
3510 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3511 sQuiescent = true;
3512 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003513 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3514 sQuiescent = true;
3515 reason = reason.substring(0,
3516 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3517 }
3518
3519 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3520 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3521 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003522 }
3523
3524 if (sQuiescent) {
3525 // Pass the optional "quiescent" argument to the bootloader to let it know
3526 // that it should not turn the screen/lights on.
3527 reason = reason + ",quiescent";
3528 }
3529
3530 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003531 try {
Tao Bao90237f72015-05-21 16:25:19 -07003532 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003533 } catch (InterruptedException e) {
3534 Thread.currentThread().interrupt();
3535 }
Tao Bao90237f72015-05-21 16:25:19 -07003536 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003537 }
3538
3539 @Override // Watchdog.Monitor implementation
3540 public void monitor() {
3541 // Grab and release lock for watchdog monitor to detect deadlocks.
3542 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003543 }
Jeff Brown96307042012-07-27 15:51:34 -07003544 }
3545
Jeff Brown6f357d32014-01-15 20:40:55 -08003546 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003547 pw.println("POWER MANAGER (dumpsys power)\n");
3548
Jeff Brown3b971592013-01-09 18:46:37 -08003549 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003550 synchronized (mLock) {
3551 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003552 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003553 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003554 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3555 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003556 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003557 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003558 pw.println(" mBatteryLevel=" + mBatteryLevel);
3559 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003560 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003561 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003562 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003563 pw.println(" mBootCompleted=" + mBootCompleted);
3564 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003565 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3566 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003567 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003568 pw.print(" mNotifyLongScheduled=");
3569 if (mNotifyLongScheduled == 0) {
3570 pw.print("(none)");
3571 } else {
3572 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3573 }
3574 pw.println();
3575 pw.print(" mNotifyLongDispatched=");
3576 if (mNotifyLongDispatched == 0) {
3577 pw.print("(none)");
3578 } else {
3579 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3580 }
3581 pw.println();
3582 pw.print(" mNotifyLongNextCheck=");
3583 if (mNotifyLongNextCheck == 0) {
3584 pw.print("(none)");
3585 } else {
3586 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3587 }
3588 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003589 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3590 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3591 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003592 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003593 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003594 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003595 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3596 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003597 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003598 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3599 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Calin Tatarua3805722018-08-09 16:41:28 +02003600 pw.println(" mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
Jeff Brown96307042012-07-27 15:51:34 -07003601 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3602 pw.println(" mLastUserActivityTimeNoChangeLights="
3603 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003604 pw.println(" mLastInteractivePowerHintTime="
3605 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003606 pw.println(" mLastScreenBrightnessBoostTime="
3607 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3608 pw.println(" mScreenBrightnessBoostInProgress="
3609 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003610 pw.println(" mDisplayReady=" + mDisplayReady);
3611 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003612 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003613
3614 pw.println();
3615 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003616 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3617 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3618 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3619 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003620 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3621 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003622 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3623 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3624 pw.println(" mTheaterModeEnabled="
3625 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003626 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3627 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003628 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003629 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3630 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3631 + mDreamsActivatedOnSleepByDefaultConfig);
3632 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3633 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003634 pw.println(" mDreamsEnabledOnBatteryConfig="
3635 + mDreamsEnabledOnBatteryConfig);
3636 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3637 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3638 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3639 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3640 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3641 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003642 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003643 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003644 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003645 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003646 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3647 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3648 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Robert Horvath5560f382019-07-10 10:46:38 +02003649 pw.println(" mAttentiveTimeoutConfig=" + mAttentiveTimeoutConfig);
3650 pw.println(" mAttentiveTimeoutSetting=" + mAttentiveTimeoutSetting);
3651 pw.println(" mAttentiveWarningDurationConfig=" + mAttentiveWarningDurationConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003652 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003653 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003654 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3655 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3656 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3657 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3658 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3659 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3660 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3661 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003662 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3663 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003664 pw.println(" mUserInactiveOverrideFromWindowManager="
3665 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003666 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3667 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003668 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003669 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3670 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003671 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3672 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3673 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003674 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003675 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003676 pw.println(" mForegroundProfile=" + mForegroundProfile);
Beverly478722e2019-10-14 11:16:57 -04003677 pw.println(" mUserId=" + mUserId);
Jeff Brown96307042012-07-27 15:51:34 -07003678
Robert Horvath5560f382019-07-10 10:46:38 +02003679 final long attentiveTimeout = getAttentiveTimeoutLocked();
3680 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
3681 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01003682 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003683 pw.println();
Robert Horvath5560f382019-07-10 10:46:38 +02003684 pw.println("Attentive timeout: " + attentiveTimeout + " ms");
Jeff Brown05af6ad2014-09-30 20:54:30 -07003685 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003686 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3687 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3688
Jeff Brown96307042012-07-27 15:51:34 -07003689 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003690 pw.print("UID states (changing=");
3691 pw.print(mUidsChanging);
3692 pw.print(" changed=");
3693 pw.print(mUidsChanged);
3694 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003695 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003696 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003697 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003698 pw.print(": ");
3699 if (state.mActive) pw.print(" ACTIVE ");
3700 else pw.print("INACTIVE ");
3701 pw.print(" count=");
3702 pw.print(state.mNumWakeLocks);
3703 pw.print(" state=");
3704 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003705 }
3706
3707 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003708 pw.println("Looper state:");
3709 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3710
3711 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003712 pw.println("Wake Locks: size=" + mWakeLocks.size());
3713 for (WakeLock wl : mWakeLocks) {
3714 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003715 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003716
Jeff Brown96307042012-07-27 15:51:34 -07003717 pw.println();
3718 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3719 for (SuspendBlocker sb : mSuspendBlockers) {
3720 pw.println(" " + sb);
3721 }
3722
Jeff Brownc38c9be2012-10-04 13:16:19 -07003723 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003724 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003725
jackqdyulei455e90a2017-02-09 15:29:16 -08003726 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003727 mBatterySaverStateMachine.dump(pw);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08003728 mAttentionDetector.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003729
Pavel Grafov28939982017-10-03 15:11:52 +01003730 pw.println();
3731 final int numProfiles = mProfilePowerState.size();
3732 pw.println("Profile power states: size=" + numProfiles);
3733 for (int i = 0; i < numProfiles; i++) {
3734 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3735 pw.print(" mUserId=");
3736 pw.print(profile.mUserId);
3737 pw.print(" mScreenOffTimeout=");
3738 pw.print(profile.mScreenOffTimeout);
3739 pw.print(" mWakeLockSummary=");
3740 pw.print(profile.mWakeLockSummary);
3741 pw.print(" mLastUserActivityTime=");
3742 pw.print(profile.mLastUserActivityTime);
3743 pw.print(" mLockingNotified=");
3744 pw.println(profile.mLockingNotified);
3745 }
3746
Jeff Brown3b971592013-01-09 18:46:37 -08003747 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003748 }
3749
Jeff Brown3b971592013-01-09 18:46:37 -08003750 if (wcd != null) {
3751 wcd.dump(pw);
3752 }
Jeff Brown96307042012-07-27 15:51:34 -07003753 }
3754
Netta P958d0a52017-02-07 11:20:55 -08003755 private void dumpProto(FileDescriptor fd) {
3756 final WirelessChargerDetector wcd;
3757 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3758
3759 synchronized (mLock) {
3760 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003761 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3762 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3763 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3764 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3765 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3766 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003767 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003768 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003769 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003770 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3771 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3772 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3773 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3774 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003775 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003776 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003777 mHalAutoSuspendModeEnabled);
3778 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003779 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003780 mHalInteractiveModeEnabled);
3781
Kweku Adamse6b00c22017-10-23 16:46:45 -07003782 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003783 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003784 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003785 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3786 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003787 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003788 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3789 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003790 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003791 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3792 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003793 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003794 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3795 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003796 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003797 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3798 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003799 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003800 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3801 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003802 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003803 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3804 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003805 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003806 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3807 proto.end(activeWakeLocksToken);
3808
Kweku Adamse6b00c22017-10-23 16:46:45 -07003809 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3810 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3811 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003812
Kweku Adamse6b00c22017-10-23 16:46:45 -07003813 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003814 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003815 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003816 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3817 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003818 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003819 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3820 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003821 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003822 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3823 proto.end(userActivityToken);
3824
3825 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003826 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003827 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003828 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3829 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003830 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3831 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3832 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003833
3834 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003835 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003836 }
3837 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003838 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003839 }
3840
Kweku Adamse6b00c22017-10-23 16:46:45 -07003841 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3842 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3843 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003844 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003845 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003846 mLastUserActivityTimeNoChangeLights);
3847 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003848 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003849 mLastInteractivePowerHintTime);
3850 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003851 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003852 mLastScreenBrightnessBoostTime);
3853 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003854 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003855 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003856 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003857 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003858 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003859 mHoldingWakeLockSuspendBlocker);
3860 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003861 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003862 mHoldingDisplaySuspendBlocker);
3863
3864 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003865 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003866 proto.write(
3867 PowerServiceSettingsAndConfigurationDumpProto
3868 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3869 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3870 proto.write(
3871 PowerServiceSettingsAndConfigurationDumpProto
3872 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3873 mDecoupleHalInteractiveModeFromDisplayConfig);
3874 proto.write(
3875 PowerServiceSettingsAndConfigurationDumpProto
3876 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3877 mWakeUpWhenPluggedOrUnpluggedConfig);
3878 proto.write(
3879 PowerServiceSettingsAndConfigurationDumpProto
3880 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3881 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3882 proto.write(
3883 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3884 mTheaterModeEnabled);
3885 proto.write(
3886 PowerServiceSettingsAndConfigurationDumpProto
3887 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3888 mSuspendWhenScreenOffDueToProximityConfig);
3889 proto.write(
3890 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3891 mDreamsSupportedConfig);
3892 proto.write(
3893 PowerServiceSettingsAndConfigurationDumpProto
3894 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3895 mDreamsEnabledByDefaultConfig);
3896 proto.write(
3897 PowerServiceSettingsAndConfigurationDumpProto
3898 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3899 mDreamsActivatedOnSleepByDefaultConfig);
3900 proto.write(
3901 PowerServiceSettingsAndConfigurationDumpProto
3902 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3903 mDreamsActivatedOnDockByDefaultConfig);
3904 proto.write(
3905 PowerServiceSettingsAndConfigurationDumpProto
3906 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3907 mDreamsEnabledOnBatteryConfig);
3908 proto.write(
3909 PowerServiceSettingsAndConfigurationDumpProto
3910 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3911 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3912 proto.write(
3913 PowerServiceSettingsAndConfigurationDumpProto
3914 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3915 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3916 proto.write(
3917 PowerServiceSettingsAndConfigurationDumpProto
3918 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3919 mDreamsBatteryLevelDrainCutoffConfig);
3920 proto.write(
3921 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3922 mDreamsEnabledSetting);
3923 proto.write(
3924 PowerServiceSettingsAndConfigurationDumpProto
3925 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3926 mDreamsActivateOnSleepSetting);
3927 proto.write(
3928 PowerServiceSettingsAndConfigurationDumpProto
3929 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3930 mDreamsActivateOnDockSetting);
3931 proto.write(
3932 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08003933 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08003934 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003935 PowerServiceSettingsAndConfigurationDumpProto
3936 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3937 mMinimumScreenOffTimeoutConfig);
3938 proto.write(
3939 PowerServiceSettingsAndConfigurationDumpProto
3940 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3941 mMaximumScreenDimDurationConfig);
3942 proto.write(
3943 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3944 mMaximumScreenDimRatioConfig);
3945 proto.write(
3946 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3947 mScreenOffTimeoutSetting);
3948 proto.write(
3949 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3950 mSleepTimeoutSetting);
3951 proto.write(
Robert Horvath5560f382019-07-10 10:46:38 +02003952 PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_SETTING_MS,
3953 mAttentiveTimeoutSetting);
3954 proto.write(
3955 PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_CONFIG_MS,
3956 mAttentiveTimeoutConfig);
3957 proto.write(
3958 PowerServiceSettingsAndConfigurationDumpProto
3959 .ATTENTIVE_WARNING_DURATION_CONFIG_MS,
3960 mAttentiveWarningDurationConfig);
3961 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003962 PowerServiceSettingsAndConfigurationDumpProto
3963 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003964 // Clamp to int32
3965 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003966 proto.write(
3967 PowerServiceSettingsAndConfigurationDumpProto
3968 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3969 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3970
3971 final long stayOnWhilePluggedInToken =
3972 proto.start(
3973 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3974 proto.write(
3975 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3976 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3977 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3978 proto.write(
3979 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3980 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3981 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3982 proto.write(
3983 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3984 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3985 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3986 != 0));
3987 proto.end(stayOnWhilePluggedInToken);
3988
3989 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003990 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3991 mScreenBrightnessModeSetting);
3992 proto.write(
3993 PowerServiceSettingsAndConfigurationDumpProto
3994 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3995 mScreenBrightnessOverrideFromWindowManager);
3996 proto.write(
3997 PowerServiceSettingsAndConfigurationDumpProto
3998 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3999 mUserActivityTimeoutOverrideFromWindowManager);
4000 proto.write(
4001 PowerServiceSettingsAndConfigurationDumpProto
4002 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
4003 mUserInactiveOverrideFromWindowManager);
4004 proto.write(
4005 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08004006 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
4007 mDozeScreenStateOverrideFromDreamManager);
4008 proto.write(
4009 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004010 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
4011 mDrawWakeLockOverrideFromSidekick);
4012 proto.write(
4013 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08004014 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
4015 mDozeScreenBrightnessOverrideFromDreamManager);
4016
4017 final long screenBrightnessSettingLimitsToken =
4018 proto.start(
4019 PowerServiceSettingsAndConfigurationDumpProto
4020 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
4021 proto.write(
4022 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4023 .SETTING_MINIMUM,
4024 mScreenBrightnessSettingMinimum);
4025 proto.write(
4026 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4027 .SETTING_MAXIMUM,
4028 mScreenBrightnessSettingMaximum);
4029 proto.write(
4030 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4031 .SETTING_DEFAULT,
4032 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08004033 proto.end(screenBrightnessSettingLimitsToken);
4034
4035 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08004036 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
4037 mDoubleTapWakeEnabled);
4038 proto.write(
4039 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
4040 mIsVrModeEnabled);
4041 proto.end(settingsAndConfigurationToken);
4042
Robert Horvath5560f382019-07-10 10:46:38 +02004043 final long attentiveTimeout = getAttentiveTimeoutLocked();
4044 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
4045 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01004046 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Robert Horvath5560f382019-07-10 10:46:38 +02004047 proto.write(PowerManagerServiceDumpProto.ATTENTIVE_TIMEOUT_MS, attentiveTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07004048 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
4049 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
4050 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
4051 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
4052 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08004053
4054 for (int i = 0; i < mUidState.size(); i++) {
4055 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07004056 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08004057 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07004058 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
4059 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
4060 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
4061 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08004062 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
4063 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08004064 proto.end(uIDToken);
4065 }
4066
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004067 mBatterySaverStateMachine.dumpProto(proto,
4068 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
4069
Kweku Adamse6b00c22017-10-23 16:46:45 -07004070 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08004071
4072 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004073 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08004074 }
4075
4076 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004077 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08004078 }
4079 wcd = mWirelessChargerDetector;
4080 }
4081
4082 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004083 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08004084 }
4085 proto.flush();
4086 }
4087
Daichi Hirono82ab9802016-03-02 13:23:29 +09004088 private void incrementBootCount() {
4089 synchronized (mLock) {
4090 int count;
4091 try {
4092 count = Settings.Global.getInt(
4093 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
4094 } catch (SettingNotFoundException e) {
4095 count = 0;
4096 }
4097 Settings.Global.putInt(
4098 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
4099 }
4100 }
4101
Jeff Brown96307042012-07-27 15:51:34 -07004102 private static WorkSource copyWorkSource(WorkSource workSource) {
4103 return workSource != null ? new WorkSource(workSource) : null;
4104 }
4105
Santos Cordon9b510a22018-08-24 16:42:54 +01004106 @VisibleForTesting
4107 final class BatteryReceiver extends BroadcastReceiver {
Jeff Brown96307042012-07-27 15:51:34 -07004108 @Override
4109 public void onReceive(Context context, Intent intent) {
4110 synchronized (mLock) {
4111 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05004112 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05004113 }
4114 }
4115
John Spurlockf4f6b4c2012-08-25 12:08:03 -04004116 private final class DreamReceiver extends BroadcastReceiver {
4117 @Override
4118 public void onReceive(Context context, Intent intent) {
4119 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07004120 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04004121 }
4122 }
4123 }
4124
Santos Cordon9b510a22018-08-24 16:42:54 +01004125 @VisibleForTesting
4126 final class UserSwitchedReceiver extends BroadcastReceiver {
Jeff Brownd4935962012-09-25 13:27:20 -07004127 @Override
4128 public void onReceive(Context context, Intent intent) {
4129 synchronized (mLock) {
4130 handleSettingsChangedLocked();
4131 }
4132 }
4133 }
4134
Jeff Brownec6aa592012-10-17 20:30:25 -07004135 private final class DockReceiver extends BroadcastReceiver {
4136 @Override
4137 public void onReceive(Context context, Intent intent) {
4138 synchronized (mLock) {
4139 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4140 Intent.EXTRA_DOCK_STATE_UNDOCKED);
4141 if (mDockState != dockState) {
4142 mDockState = dockState;
4143 mDirty |= DIRTY_DOCK_STATE;
4144 updatePowerStateLocked();
4145 }
4146 }
4147 }
4148 }
4149
Jeff Brown96307042012-07-27 15:51:34 -07004150 private final class SettingsObserver extends ContentObserver {
4151 public SettingsObserver(Handler handler) {
4152 super(handler);
4153 }
4154
4155 @Override
4156 public void onChange(boolean selfChange, Uri uri) {
4157 synchronized (mLock) {
4158 handleSettingsChangedLocked();
4159 }
4160 }
4161 }
4162
Ruben Brunkc7be3be2016-04-01 17:07:51 -07004163 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07004164 @Override
4165 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07004166 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07004167
4168 synchronized (mLock) {
4169 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07004170 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07004171 mDirty |= DIRTY_VR_MODE_CHANGED;
4172 updatePowerStateLocked();
4173 }
4174 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07004175 }
4176 };
4177
Jeff Brown96307042012-07-27 15:51:34 -07004178 /**
4179 * Handler for asynchronous operations performed by the power manager.
4180 */
4181 private final class PowerManagerHandler extends Handler {
4182 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07004183 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07004184 }
4185
4186 @Override
4187 public void handleMessage(Message msg) {
4188 switch (msg.what) {
4189 case MSG_USER_ACTIVITY_TIMEOUT:
4190 handleUserActivityTimeout();
4191 break;
4192 case MSG_SANDMAN:
4193 handleSandman();
4194 break;
Jeff Browne333e672014-10-28 13:48:55 -07004195 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
4196 handleScreenBrightnessBoostTimeout();
4197 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004198 case MSG_CHECK_FOR_LONG_WAKELOCKS:
4199 checkForLongWakeLocks();
4200 break;
Robert Horvath5560f382019-07-10 10:46:38 +02004201 case MSG_ATTENTIVE_TIMEOUT:
4202 handleAttentiveTimeout();
4203 break;
Jeff Brown96307042012-07-27 15:51:34 -07004204 }
4205 }
4206 }
4207
4208 /**
4209 * Represents a wake lock that has been acquired by an application.
4210 */
4211 private final class WakeLock implements IBinder.DeathRecipient {
4212 public final IBinder mLock;
4213 public int mFlags;
4214 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004215 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07004216 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004217 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004218 public final int mOwnerUid;
4219 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004220 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004221 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07004222 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004223 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004224 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07004225
Dianne Hackborn713df152013-05-17 11:27:57 -07004226 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004227 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
4228 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07004229 mLock = lock;
4230 mFlags = flags;
4231 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004232 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07004233 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004234 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004235 mOwnerUid = ownerUid;
4236 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004237 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07004238 }
4239
4240 @Override
4241 public void binderDied() {
4242 PowerManagerService.this.handleWakeLockDeath(this);
4243 }
4244
4245 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4246 int ownerUid, int ownerPid) {
4247 return mFlags == flags
4248 && mTag.equals(tag)
4249 && hasSameWorkSource(workSource)
4250 && mOwnerUid == ownerUid
4251 && mOwnerPid == ownerPid;
4252 }
4253
Dianne Hackborn713df152013-05-17 11:27:57 -07004254 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004255 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07004256 if (!mPackageName.equals(packageName)) {
4257 throw new IllegalStateException("Existing wake lock package name changed: "
4258 + mPackageName + " to " + packageName);
4259 }
4260 if (mOwnerUid != ownerUid) {
4261 throw new IllegalStateException("Existing wake lock uid changed: "
4262 + mOwnerUid + " to " + ownerUid);
4263 }
4264 if (mOwnerPid != ownerPid) {
4265 throw new IllegalStateException("Existing wake lock pid changed: "
4266 + mOwnerPid + " to " + ownerPid);
4267 }
Jeff Brown96307042012-07-27 15:51:34 -07004268 mFlags = flags;
4269 mTag = tag;
4270 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004271 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004272 }
4273
4274 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00004275 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07004276 }
4277
4278 public void updateWorkSource(WorkSource workSource) {
4279 mWorkSource = copyWorkSource(workSource);
4280 }
4281
4282 @Override
4283 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004284 StringBuilder sb = new StringBuilder();
4285 sb.append(getLockLevelString());
4286 sb.append(" '");
4287 sb.append(mTag);
4288 sb.append("'");
4289 sb.append(getLockFlagsString());
4290 if (mDisabled) {
4291 sb.append(" DISABLED");
4292 }
4293 if (mNotifiedAcquired) {
4294 sb.append(" ACQ=");
4295 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4296 }
4297 if (mNotifiedLong) {
4298 sb.append(" LONG");
4299 }
4300 sb.append(" (uid=");
4301 sb.append(mOwnerUid);
4302 if (mOwnerPid != 0) {
4303 sb.append(" pid=");
4304 sb.append(mOwnerPid);
4305 }
4306 if (mWorkSource != null) {
4307 sb.append(" ws=");
4308 sb.append(mWorkSource);
4309 }
4310 sb.append(")");
4311 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004312 }
4313
Netta P958d0a52017-02-07 11:20:55 -08004314 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4315 final long wakeLockToken = proto.start(fieldId);
4316 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4317 proto.write(WakeLockProto.TAG, mTag);
4318
4319 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4320 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4321 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4322 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4323 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4324 proto.end(wakeLockFlagsToken);
4325
4326 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4327 if (mNotifiedAcquired) {
4328 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4329 }
4330 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4331 proto.write(WakeLockProto.UID, mOwnerUid);
4332 proto.write(WakeLockProto.PID, mOwnerPid);
4333
4334 if (mWorkSource != null) {
4335 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4336 }
4337 proto.end(wakeLockToken);
4338 }
4339
Jeff Brown26875502014-01-30 21:47:47 -08004340 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004341 private String getLockLevelString() {
4342 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4343 case PowerManager.FULL_WAKE_LOCK:
4344 return "FULL_WAKE_LOCK ";
4345 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4346 return "SCREEN_BRIGHT_WAKE_LOCK ";
4347 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4348 return "SCREEN_DIM_WAKE_LOCK ";
4349 case PowerManager.PARTIAL_WAKE_LOCK:
4350 return "PARTIAL_WAKE_LOCK ";
4351 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4352 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004353 case PowerManager.DOZE_WAKE_LOCK:
4354 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004355 case PowerManager.DRAW_WAKE_LOCK:
4356 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004357 default:
4358 return "??? ";
4359 }
4360 }
4361
4362 private String getLockFlagsString() {
4363 String result = "";
4364 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4365 result += " ACQUIRE_CAUSES_WAKEUP";
4366 }
4367 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4368 result += " ON_AFTER_RELEASE";
4369 }
4370 return result;
4371 }
4372 }
4373
4374 private final class SuspendBlockerImpl implements SuspendBlocker {
4375 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004376 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004377 private int mReferenceCount;
4378
4379 public SuspendBlockerImpl(String name) {
4380 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004381 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004382 }
4383
4384 @Override
4385 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004386 try {
Jeff Brown96307042012-07-27 15:51:34 -07004387 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004388 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004389 + "\" was finalized without being released!");
4390 mReferenceCount = 0;
Santos Cordon64a6e612018-08-22 19:27:04 +01004391 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004392 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004393 }
4394 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004395 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004396 }
4397 }
4398
Craig Mautner75fc9de2012-06-18 16:53:27 -07004399 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004400 public void acquire() {
4401 synchronized (this) {
4402 mReferenceCount += 1;
4403 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004404 if (DEBUG_SPEW) {
4405 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4406 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004407 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +01004408 mNativeWrapper.nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004409 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004410 }
4411 }
4412
Craig Mautner75fc9de2012-06-18 16:53:27 -07004413 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004414 public void release() {
4415 synchronized (this) {
4416 mReferenceCount -= 1;
4417 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004418 if (DEBUG_SPEW) {
4419 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4420 }
Santos Cordon64a6e612018-08-22 19:27:04 +01004421 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004422 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004423 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004424 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004425 + "\" was released without being acquired!", new Throwable());
4426 mReferenceCount = 0;
4427 }
4428 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004429 }
Jeff Brown96307042012-07-27 15:51:34 -07004430
4431 @Override
4432 public String toString() {
4433 synchronized (this) {
4434 return mName + ": ref count=" + mReferenceCount;
4435 }
4436 }
Netta P958d0a52017-02-07 11:20:55 -08004437
4438 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4439 final long sbToken = proto.start(fieldId);
4440 synchronized (this) {
4441 proto.write(SuspendBlockerProto.NAME, mName);
4442 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4443 }
4444 proto.end(sbToken);
4445 }
Jeff Brown96307042012-07-27 15:51:34 -07004446 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004447
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004448 static final class UidState {
4449 final int mUid;
4450 int mNumWakeLocks;
4451 int mProcState;
4452 boolean mActive;
4453
4454 UidState(int uid) {
4455 mUid = uid;
4456 }
4457 }
4458
Santos Cordon64a6e612018-08-22 19:27:04 +01004459 @VisibleForTesting
4460 final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004461 @Override
4462 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4463 FileDescriptor err, String[] args, ShellCallback callback,
4464 ResultReceiver resultReceiver) {
4465 (new PowerManagerShellCommand(this)).exec(
4466 this, in, out, err, args, callback, resultReceiver);
4467 }
4468
Jeff Brown6f357d32014-01-15 20:40:55 -08004469 @Override // Binder call
4470 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4471 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004472 if (uid < 0) {
4473 uid = Binder.getCallingUid();
4474 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004475 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004476 }
4477
4478 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004479 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004480 if (!mSystemReady) {
4481 // Service not ready yet, so who the heck cares about power hints, bah.
4482 return;
4483 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004484 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004485 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004486 }
4487
4488 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004489 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004490 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004491 if (lock == null) {
4492 throw new IllegalArgumentException("lock must not be null");
4493 }
4494 if (packageName == null) {
4495 throw new IllegalArgumentException("packageName must not be null");
4496 }
4497 PowerManager.validateWakeLockParameters(flags, tag);
4498
4499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004500 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4501 mContext.enforceCallingOrSelfPermission(
4502 android.Manifest.permission.DEVICE_POWER, null);
4503 }
Narayan Kamath81822022017-12-08 11:56:01 +00004504 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004505 mContext.enforceCallingOrSelfPermission(
4506 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4507 } else {
4508 ws = null;
4509 }
4510
4511 final int uid = Binder.getCallingUid();
4512 final int pid = Binder.getCallingPid();
4513 final long ident = Binder.clearCallingIdentity();
4514 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004515 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004516 } finally {
4517 Binder.restoreCallingIdentity(ident);
4518 }
4519 }
4520
4521 @Override // Binder call
4522 public void releaseWakeLock(IBinder lock, int flags) {
4523 if (lock == null) {
4524 throw new IllegalArgumentException("lock must not be null");
4525 }
4526
4527 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4528
4529 final long ident = Binder.clearCallingIdentity();
4530 try {
4531 releaseWakeLockInternal(lock, flags);
4532 } finally {
4533 Binder.restoreCallingIdentity(ident);
4534 }
4535 }
4536
4537 @Override // Binder call
4538 public void updateWakeLockUids(IBinder lock, int[] uids) {
4539 WorkSource ws = null;
4540
4541 if (uids != null) {
4542 ws = new WorkSource();
4543 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4544 // one at a time?
4545 for (int i = 0; i < uids.length; i++) {
4546 ws.add(uids[i]);
4547 }
4548 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004549 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004550 }
4551
4552 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004553 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004554 if (lock == null) {
4555 throw new IllegalArgumentException("lock must not be null");
4556 }
4557
4558 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004559 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004560 mContext.enforceCallingOrSelfPermission(
4561 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4562 } else {
4563 ws = null;
4564 }
4565
Dianne Hackbornd953c532014-08-16 18:17:38 -07004566 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004567 final long ident = Binder.clearCallingIdentity();
4568 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004569 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004570 } finally {
4571 Binder.restoreCallingIdentity(ident);
4572 }
4573 }
4574
4575 @Override // Binder call
4576 public boolean isWakeLockLevelSupported(int level) {
4577 final long ident = Binder.clearCallingIdentity();
4578 try {
4579 return isWakeLockLevelSupportedInternal(level);
4580 } finally {
4581 Binder.restoreCallingIdentity(ident);
4582 }
4583 }
4584
4585 @Override // Binder call
4586 public void userActivity(long eventTime, int event, int flags) {
4587 final long now = SystemClock.uptimeMillis();
4588 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004589 != PackageManager.PERMISSION_GRANTED
4590 && mContext.checkCallingOrSelfPermission(
4591 android.Manifest.permission.USER_ACTIVITY)
4592 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004593 // Once upon a time applications could call userActivity().
4594 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4595 // request instead of throwing a SecurityException so we don't break old apps.
4596 synchronized (mLock) {
4597 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4598 mLastWarningAboutUserActivityPermission = now;
4599 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004600 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4601 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004602 + " pid=" + Binder.getCallingPid()
4603 + " uid=" + Binder.getCallingUid());
4604 }
4605 }
4606 return;
4607 }
4608
Jim Millerdca15d22015-06-16 20:55:13 -07004609 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004610 throw new IllegalArgumentException("event time must not be in the future");
4611 }
4612
4613 final int uid = Binder.getCallingUid();
4614 final long ident = Binder.clearCallingIdentity();
4615 try {
4616 userActivityInternal(eventTime, event, flags, uid);
4617 } finally {
4618 Binder.restoreCallingIdentity(ident);
4619 }
4620 }
4621
4622 @Override // Binder call
Michael Wrighte3001042019-02-05 00:13:14 +00004623 public void wakeUp(long eventTime, @WakeReason int reason, String details,
4624 String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004625 if (eventTime > SystemClock.uptimeMillis()) {
4626 throw new IllegalArgumentException("event time must not be in the future");
4627 }
4628
4629 mContext.enforceCallingOrSelfPermission(
4630 android.Manifest.permission.DEVICE_POWER, null);
4631
Jeff Brownc12035c2014-08-13 18:52:25 -07004632 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004633 final long ident = Binder.clearCallingIdentity();
4634 try {
Michael Wrighte3001042019-02-05 00:13:14 +00004635 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004636 } finally {
4637 Binder.restoreCallingIdentity(ident);
4638 }
4639 }
4640
4641 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004642 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004643 if (eventTime > SystemClock.uptimeMillis()) {
4644 throw new IllegalArgumentException("event time must not be in the future");
4645 }
4646
4647 mContext.enforceCallingOrSelfPermission(
4648 android.Manifest.permission.DEVICE_POWER, null);
4649
Jeff Brownc12035c2014-08-13 18:52:25 -07004650 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004651 final long ident = Binder.clearCallingIdentity();
4652 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004653 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004654 } finally {
4655 Binder.restoreCallingIdentity(ident);
4656 }
4657 }
4658
4659 @Override // Binder call
4660 public void nap(long eventTime) {
4661 if (eventTime > SystemClock.uptimeMillis()) {
4662 throw new IllegalArgumentException("event time must not be in the future");
4663 }
4664
4665 mContext.enforceCallingOrSelfPermission(
4666 android.Manifest.permission.DEVICE_POWER, null);
4667
Jeff Brownc12035c2014-08-13 18:52:25 -07004668 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004669 final long ident = Binder.clearCallingIdentity();
4670 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004671 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004672 } finally {
4673 Binder.restoreCallingIdentity(ident);
4674 }
4675 }
4676
4677 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004678 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004679 final long ident = Binder.clearCallingIdentity();
4680 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004681 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004682 } finally {
4683 Binder.restoreCallingIdentity(ident);
4684 }
4685 }
4686
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004687 @Override // Binder call
4688 public boolean isPowerSaveMode() {
4689 final long ident = Binder.clearCallingIdentity();
4690 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004691 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004692 } finally {
4693 Binder.restoreCallingIdentity(ident);
4694 }
4695 }
4696
jackqdyulei455e90a2017-02-09 15:29:16 -08004697 // Binder call
4698 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4699 final long ident = Binder.clearCallingIdentity();
4700 try {
Kweku Adams9f488e22019-01-14 16:25:08 -08004701 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
jackqdyulei455e90a2017-02-09 15:29:16 -08004702 } finally {
4703 Binder.restoreCallingIdentity(ident);
4704 }
4705 }
4706
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004707 @Override // Binder call
Salvador Martinezc8c4c5d2019-03-11 11:11:37 -07004708 public boolean setPowerSaveModeEnabled(boolean enabled) {
Salvador Martineza80bbab2018-09-24 10:36:11 -07004709 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4710 != PackageManager.PERMISSION_GRANTED) {
4711 mContext.enforceCallingOrSelfPermission(
4712 android.Manifest.permission.DEVICE_POWER, null);
4713 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004714 final long ident = Binder.clearCallingIdentity();
4715 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004716 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004717 } finally {
4718 Binder.restoreCallingIdentity(ident);
4719 }
4720 }
4721
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004722 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004723 public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
Salvador Martinez812ea752018-10-19 13:03:20 -07004724 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4725 "updateDynamicPowerSavings");
4726 final long ident = Binder.clearCallingIdentity();
4727 try {
4728 final ContentResolver resolver = mContext.getContentResolver();
4729 boolean success = Settings.Global.putInt(resolver,
4730 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4731 disableThreshold);
4732 if (success) {
4733 // abort updating if we weren't able to succeed on the threshold
4734 success &= Settings.Global.putInt(resolver,
4735 Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004736 powerSaveHint ? 1 : 0);
Salvador Martinez812ea752018-10-19 13:03:20 -07004737 }
4738 return success;
4739 } finally {
4740 Binder.restoreCallingIdentity(ident);
4741 }
4742 }
4743
4744 @Override // Binder call
Kweku Adams9f488e22019-01-14 16:25:08 -08004745 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4746 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4747 != PackageManager.PERMISSION_GRANTED) {
4748 mContext.enforceCallingOrSelfPermission(
4749 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4750 }
4751 final long ident = Binder.clearCallingIdentity();
4752 try {
4753 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4754 } finally {
4755 Binder.restoreCallingIdentity(ident);
4756 }
4757 }
4758
4759 @Override // Binder call
4760 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4761 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4762 != PackageManager.PERMISSION_GRANTED) {
4763 mContext.enforceCallingOrSelfPermission(
4764 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4765 }
4766 final long ident = Binder.clearCallingIdentity();
4767 try {
4768 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4769 } finally {
4770 Binder.restoreCallingIdentity(ident);
4771 }
4772 }
4773
4774 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004775 public int getPowerSaveModeTrigger() {
Salvador Martinez812ea752018-10-19 13:03:20 -07004776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4777 final long ident = Binder.clearCallingIdentity();
4778 try {
4779 return Settings.Global.getInt(mContext.getContentResolver(),
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004780 Settings.Global.AUTOMATIC_POWER_SAVE_MODE,
4781 PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE);
Salvador Martinez812ea752018-10-19 13:03:20 -07004782 } finally {
4783 Binder.restoreCallingIdentity(ident);
4784 }
4785 }
4786
4787 @Override // Binder call
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004788 public boolean isDeviceIdleMode() {
4789 final long ident = Binder.clearCallingIdentity();
4790 try {
4791 return isDeviceIdleModeInternal();
4792 } finally {
4793 Binder.restoreCallingIdentity(ident);
4794 }
4795 }
4796
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004797 @Override // Binder call
4798 public boolean isLightDeviceIdleMode() {
4799 final long ident = Binder.clearCallingIdentity();
4800 try {
4801 return isLightDeviceIdleModeInternal();
4802 } finally {
4803 Binder.restoreCallingIdentity(ident);
4804 }
4805 }
4806
Jeff Brown6f357d32014-01-15 20:40:55 -08004807 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004808 * Gets the reason for the last time the phone had to reboot.
4809 *
4810 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004811 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004812 */
4813 @Override // Binder call
4814 public int getLastShutdownReason() {
4815 mContext.enforceCallingOrSelfPermission(
4816 android.Manifest.permission.DEVICE_POWER, null);
4817
4818 final long ident = Binder.clearCallingIdentity();
4819 try {
Mark Salyzyn74ce8b32018-06-05 09:06:54 -07004820 return getLastShutdownReasonInternal(REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004821 } finally {
4822 Binder.restoreCallingIdentity(ident);
4823 }
4824 }
4825
Calin Tatarua3805722018-08-09 16:41:28 +02004826 @Override // Binder call
4827 public int getLastSleepReason() {
4828 mContext.enforceCallingOrSelfPermission(
4829 android.Manifest.permission.DEVICE_POWER, null);
4830
4831 final long ident = Binder.clearCallingIdentity();
4832 try {
4833 return getLastSleepReasonInternal();
4834 } finally {
4835 Binder.restoreCallingIdentity(ident);
4836 }
4837 }
4838
Salvador Martineza6f7b252017-04-10 10:46:15 -07004839 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004840 * Reboots the device.
4841 *
4842 * @param confirm If true, shows a reboot confirmation dialog.
4843 * @param reason The reason for the reboot, or null if none.
4844 * @param wait If true, this call waits for the reboot to complete and does not return.
4845 */
4846 @Override // Binder call
4847 public void reboot(boolean confirm, String reason, boolean wait) {
4848 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004849 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4850 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004851 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4852 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004853
4854 final long ident = Binder.clearCallingIdentity();
4855 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004856 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4857 } finally {
4858 Binder.restoreCallingIdentity(ident);
4859 }
4860 }
4861
4862 /**
4863 * Reboots the device into safe mode
4864 *
4865 * @param confirm If true, shows a reboot confirmation dialog.
4866 * @param wait If true, this call waits for the reboot to complete and does not return.
4867 */
4868 @Override // Binder call
4869 public void rebootSafeMode(boolean confirm, boolean wait) {
4870 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4871
4872 final long ident = Binder.clearCallingIdentity();
4873 try {
4874 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4875 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004876 } finally {
4877 Binder.restoreCallingIdentity(ident);
4878 }
4879 }
4880
4881 /**
4882 * Shuts down the device.
4883 *
4884 * @param confirm If true, shows a shutdown confirmation dialog.
4885 * @param wait If true, this call waits for the shutdown to complete and does not return.
4886 */
4887 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004888 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004889 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4890
4891 final long ident = Binder.clearCallingIdentity();
4892 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004893 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004894 } finally {
4895 Binder.restoreCallingIdentity(ident);
4896 }
4897 }
4898
4899 /**
4900 * Crash the runtime (causing a complete restart of the Android framework).
4901 * Requires REBOOT permission. Mostly for testing. Should not return.
4902 */
4903 @Override // Binder call
4904 public void crash(String message) {
4905 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4906
4907 final long ident = Binder.clearCallingIdentity();
4908 try {
4909 crashInternal(message);
4910 } finally {
4911 Binder.restoreCallingIdentity(ident);
4912 }
4913 }
4914
4915 /**
4916 * Set the setting that determines whether the device stays on when plugged in.
4917 * The argument is a bit string, with each bit specifying a power source that,
4918 * when the device is connected to that source, causes the device to stay on.
4919 * See {@link android.os.BatteryManager} for the list of power sources that
4920 * can be specified. Current values include
4921 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4922 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4923 *
4924 * Used by "adb shell svc power stayon ..."
4925 *
4926 * @param val an {@code int} containing the bits that specify which power sources
4927 * should cause the device to stay on.
4928 */
4929 @Override // Binder call
4930 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004931 int uid = Binder.getCallingUid();
4932 // if uid is of root's, we permit this operation straight away
4933 if (uid != Process.ROOT_UID) {
4934 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4935 Settings.getPackageNameForUid(mContext, uid), true)) {
4936 return;
4937 }
4938 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004939
4940 final long ident = Binder.clearCallingIdentity();
4941 try {
4942 setStayOnSettingInternal(val);
4943 } finally {
4944 Binder.restoreCallingIdentity(ident);
4945 }
4946 }
4947
4948 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004949 * Used by the phone application to make the attention LED flash when ringing.
4950 */
4951 @Override // Binder call
4952 public void setAttentionLight(boolean on, int color) {
4953 mContext.enforceCallingOrSelfPermission(
4954 android.Manifest.permission.DEVICE_POWER, null);
4955
4956 final long ident = Binder.clearCallingIdentity();
4957 try {
4958 setAttentionLightInternal(on, color);
4959 } finally {
4960 Binder.restoreCallingIdentity(ident);
4961 }
4962 }
4963
4964 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08004965 public void setDozeAfterScreenOff(boolean on) {
4966 mContext.enforceCallingOrSelfPermission(
4967 android.Manifest.permission.DEVICE_POWER, null);
4968
4969 final long ident = Binder.clearCallingIdentity();
4970 try {
4971 setDozeAfterScreenOffInternal(on);
4972 } finally {
4973 Binder.restoreCallingIdentity(ident);
4974 }
4975 }
4976
4977 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004978 public void boostScreenBrightness(long eventTime) {
4979 if (eventTime > SystemClock.uptimeMillis()) {
4980 throw new IllegalArgumentException("event time must not be in the future");
4981 }
4982
4983 mContext.enforceCallingOrSelfPermission(
4984 android.Manifest.permission.DEVICE_POWER, null);
4985
4986 final int uid = Binder.getCallingUid();
4987 final long ident = Binder.clearCallingIdentity();
4988 try {
4989 boostScreenBrightnessInternal(eventTime, uid);
4990 } finally {
4991 Binder.restoreCallingIdentity(ident);
4992 }
4993 }
4994
4995 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004996 public boolean isScreenBrightnessBoosted() {
4997 final long ident = Binder.clearCallingIdentity();
4998 try {
4999 return isScreenBrightnessBoostedInternal();
5000 } finally {
5001 Binder.restoreCallingIdentity(ident);
5002 }
5003 }
5004
Santos Cordon12f92eb2019-02-01 21:28:47 +00005005 @Override // binder call
5006 public boolean forceSuspend() {
5007 mContext.enforceCallingOrSelfPermission(
5008 android.Manifest.permission.DEVICE_POWER, null);
5009
5010 final int uid = Binder.getCallingUid();
5011 final long ident = Binder.clearCallingIdentity();
5012 try {
5013 return forceSuspendInternal(uid);
5014 } finally {
5015 Binder.restoreCallingIdentity(ident);
5016 }
5017 }
5018
Bryce Lee84d6c0f2015-03-17 10:43:08 -07005019 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08005020 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005021 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08005022
5023 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08005024
5025 boolean isDumpProto = false;
5026 for (String arg : args) {
5027 if (arg.equals("--proto")) {
5028 isDumpProto = true;
5029 }
5030 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005031 try {
Netta P958d0a52017-02-07 11:20:55 -08005032 if (isDumpProto) {
5033 dumpProto(fd);
5034 } else {
5035 dumpInternal(pw);
5036 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005037 } finally {
5038 Binder.restoreCallingIdentity(ident);
5039 }
5040 }
5041 }
5042
Salvador Martineza6f7b252017-04-10 10:46:15 -07005043 @VisibleForTesting
Santos Cordon64a6e612018-08-22 19:27:04 +01005044 BinderService getBinderServiceInstance() {
5045 return mBinderService;
5046 }
5047
5048 @VisibleForTesting
5049 LocalService getLocalServiceInstance() {
5050 return mLocalService;
5051 }
5052
5053 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07005054 // lastRebootReasonProperty argument to permit testing
5055 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
5056 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01005057 if (line == null) {
5058 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
5059 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07005060 switch (line) {
5061 case REASON_SHUTDOWN:
5062 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
5063 case REASON_REBOOT:
5064 return PowerManager.SHUTDOWN_REASON_REBOOT;
5065 case REASON_USERREQUESTED:
5066 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
5067 case REASON_THERMAL_SHUTDOWN:
5068 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07005069 case REASON_LOW_BATTERY:
5070 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
5071 case REASON_BATTERY_THERMAL_STATE:
5072 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07005073 default:
5074 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
5075 }
5076 }
5077
Calin Tatarua3805722018-08-09 16:41:28 +02005078 private int getLastSleepReasonInternal() {
5079 synchronized (mLock) {
5080 return mLastSleepReason;
5081 }
5082 }
5083
Santos Cordon623526b2019-04-09 17:02:38 +01005084 private PowerManager.WakeData getLastWakeupInternal() {
5085 synchronized (mLock) {
5086 return new WakeData(mLastWakeTime, mLastWakeReason);
5087 }
5088 }
5089
Santos Cordond9701ab2019-08-01 18:33:20 +01005090 @VisibleForTesting
5091 final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08005092 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07005093 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
5094 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
5095 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
5096 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08005097 }
Jeff Brown970d4132014-07-19 11:33:47 -07005098 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08005099 }
5100
Jeff Brown6f357d32014-01-15 20:40:55 -08005101 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07005102 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
5103 switch (screenState) {
5104 case Display.STATE_UNKNOWN:
5105 case Display.STATE_OFF:
5106 case Display.STATE_DOZE:
5107 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07005108 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07005109 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07005110 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07005111 break;
5112 default:
5113 screenState = Display.STATE_UNKNOWN;
5114 break;
5115 }
5116 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
5117 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
5118 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
5119 }
5120 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
5121 }
5122
Jeff Brown6f357d32014-01-15 20:40:55 -08005123 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07005124 public void setUserInactiveOverrideFromWindowManager() {
5125 setUserInactiveOverrideFromWindowManagerInternal();
5126 }
5127
5128 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08005129 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07005130 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08005131 }
5132
5133 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00005134 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
5135 setDrawWakeLockOverrideFromSidekickInternal(keepState);
5136 }
5137
5138 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01005139 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
5140 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08005141 }
5142
5143 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08005144 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Kweku Adams9f488e22019-01-14 16:25:08 -08005145 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005146 }
5147
5148 @Override
5149 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08005150 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005151 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005152
5153 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005154 public boolean setDeviceIdleMode(boolean enabled) {
5155 return setDeviceIdleModeInternal(enabled);
5156 }
5157
5158 @Override
5159 public boolean setLightDeviceIdleMode(boolean enabled) {
5160 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07005161 }
5162
5163 @Override
5164 public void setDeviceIdleWhitelist(int[] appids) {
5165 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005166 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07005167
5168 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07005169 public void setDeviceIdleTempWhitelist(int[] appids) {
5170 setDeviceIdleTempWhitelistInternal(appids);
5171 }
5172
5173 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07005174 public void startUidChanges() {
5175 startUidChangesInternal();
5176 }
5177
5178 @Override
5179 public void finishUidChanges() {
5180 finishUidChangesInternal();
5181 }
5182
5183 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07005184 public void updateUidProcState(int uid, int procState) {
5185 updateUidProcStateInternal(uid, procState);
5186 }
5187
5188 @Override
5189 public void uidGone(int uid) {
5190 uidGoneInternal(uid);
5191 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01005192
5193 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07005194 public void uidActive(int uid) {
5195 uidActiveInternal(uid);
5196 }
5197
5198 @Override
5199 public void uidIdle(int uid) {
5200 uidIdleInternal(uid);
5201 }
5202
5203 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01005204 public void powerHint(int hintId, int data) {
5205 powerHintInternal(hintId, data);
5206 }
Alex Kershaw2418ea92018-10-19 17:17:49 +01005207
5208 @Override
5209 public boolean wasDeviceIdleFor(long ms) {
5210 return wasDeviceIdleForInternal(ms);
5211 }
Santos Cordon623526b2019-04-09 17:02:38 +01005212
5213 @Override
5214 public WakeData getLastWakeup() {
5215 return getLastWakeupInternal();
5216 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005217 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005218}