blob: 9cfd09563bfa2ac7a3f121c369ad73df27056ec8 [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;
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -0800110import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000111import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Jeff Brown96307042012-07-27 15:51:34 -0700113/**
114 * The power manager service is responsible for coordinating power management
115 * functions on the device.
116 */
Jeff Brown2175e9c2014-09-12 16:11:07 -0700117public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -0700118 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800120
Santos Cordon4ddb8012017-09-20 15:25:44 -0700121 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700122 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700123
Jeff Brown96307042012-07-27 15:51:34 -0700124 // Message: Sent when a user activity timeout occurs to update the power state.
125 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800126 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700127 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700128 // Message: Sent when the screen brightness boost expires.
129 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700130 // Message: Polling to look for long held wake locks.
131 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Robert Horvath5560f382019-07-10 10:46:38 +0200132 // Message: Sent when an attentive timeout occurs to update the power state.
133 private static final int MSG_ATTENTIVE_TIMEOUT = 5;
Jeff Brown7304c342012-05-11 18:42:42 -0700134
Jeff Brown96307042012-07-27 15:51:34 -0700135 // Dirty bit: mWakeLocks changed
136 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
137 // Dirty bit: mWakefulness changed
138 private static final int DIRTY_WAKEFULNESS = 1 << 1;
139 // Dirty bit: user activity was poked or may have timed out
140 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
141 // Dirty bit: actual display power state was updated asynchronously
142 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
143 // Dirty bit: mBootCompleted changed
144 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
145 // Dirty bit: settings changed
146 private static final int DIRTY_SETTINGS = 1 << 5;
147 // Dirty bit: mIsPowered changed
148 private static final int DIRTY_IS_POWERED = 1 << 6;
149 // Dirty bit: mStayOn changed
150 private static final int DIRTY_STAY_ON = 1 << 7;
151 // Dirty bit: battery state changed
152 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700153 // Dirty bit: proximity state changed
154 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700155 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700156 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700157 // Dirty bit: brightness boost changed
158 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800159 // Dirty bit: sQuiescent changed
160 private static final int DIRTY_QUIESCENT = 1 << 12;
Santos Cordon3107d292016-09-20 15:50:35 -0700161 // Dirty bit: VR Mode enabled changed
162 private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
Robert Horvath5560f382019-07-10 10:46:38 +0200163 // Dirty bit: attentive timer may have timed out
164 private static final int DIRTY_ATTENTIVE = 1 << 14;
Jeff Brown7304c342012-05-11 18:42:42 -0700165
Jeff Brown96307042012-07-27 15:51:34 -0700166 // Summarizes the state of all active wakelocks.
167 private static final int WAKE_LOCK_CPU = 1 << 0;
168 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
169 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
170 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
171 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700172 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800173 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800174 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
Jeff Brown96307042012-07-27 15:51:34 -0700176 // Summarizes the user activity state.
177 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
178 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700179 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Jeff Brown27736f52014-05-20 17:17:10 -0700181 // Default timeout in milliseconds. This is only used until the settings
182 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700183 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700184 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700185
Jeff Browne333e672014-10-28 13:48:55 -0700186 // Screen brightness boost timeout.
187 // Hardcoded for now until we decide what the right policy should be.
188 // This should perhaps be a setting.
189 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
190
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700191 // How long a partial wake lock must be held until we consider it a long wake lock.
192 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
193
Jason Monk27bbb2d2015-03-31 16:46:39 -0400194 // Power features defined in hardware/libhardware/include/hardware/power.h.
195 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
196
197 // Default setting for double tap to wake.
198 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
199
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800200 // System property indicating that the screen should remain off until an explicit user action
201 private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
202
Christine Franks732c0432017-06-23 18:12:46 -0700203 // System Property indicating that retail demo mode is currently enabled.
204 private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
205
Wei Wang72b77cc2019-02-07 14:10:23 -0800206 // Possible reasons for shutting down or reboot for use in REBOOT_PROPERTY(sys.boot.reason)
207 // which is set by bootstat
Salvador Martineza6f7b252017-04-10 10:46:15 -0700208 private static final String REASON_SHUTDOWN = "shutdown";
209 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700210 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
211 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700212 private static final String REASON_LOW_BATTERY = "shutdown,battery";
213 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700214
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700215 private static final String TRACE_SCREEN_ON = "Screen turning on";
216
217 /** If turning screen on takes more than this long, we show a warning on logcat. */
218 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
219
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700220 /** Constants for {@link #shutdownOrRebootInternal} */
221 @Retention(RetentionPolicy.SOURCE)
222 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
223 public @interface HaltMode {}
224 private static final int HALT_MODE_SHUTDOWN = 0;
225 private static final int HALT_MODE_REBOOT = 1;
226 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
227
Mark Salyzyn74ce8b32018-06-05 09:06:54 -0700228 // property for last reboot reason
229 private static final String REBOOT_PROPERTY = "sys.boot.reason";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700230
Jeff Brownb880d882014-02-10 19:47:07 -0800231 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700232 private final ServiceThread mHandlerThread;
233 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100234 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800235 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800236 private final BatterySaverController mBatterySaverController;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700237 private final BatterySaverStateMachine mBatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700238 private final BatterySavingStats mBatterySavingStats;
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800239 private final AttentionDetector mAttentionDetector;
Santos Cordon64a6e612018-08-22 19:27:04 +0100240 private final BinderService mBinderService;
241 private final LocalService mLocalService;
242 private final NativeWrapper mNativeWrapper;
243 private final Injector mInjector;
Jeff Brown2c43c332014-06-12 22:38:59 -0700244
Adam Lesinski182f73f2013-12-05 16:48:06 -0800245 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700246 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800247 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700248 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700249 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700250 private WindowManagerPolicy mPolicy;
251 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800252 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700253 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800254 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800255 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700256
Robert Horvath5560f382019-07-10 10:46:38 +0200257 private InattentiveSleepWarningController mInattentiveSleepWarningOverlayController;
258
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600259 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700260
261 // A bitfield that indicates what parts of the power state have
262 // changed and need to be recalculated.
263 private int mDirty;
264
265 // Indicates whether the device is awake or asleep or somewhere in between.
266 // This is distinct from the screen power state, which is managed separately.
267 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800268 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700269
Jeff Brown26875502014-01-30 21:47:47 -0800270 // True if the sandman has just been summoned for the first time since entering the
271 // dreaming or dozing state. Indicates whether a new dream should begin.
272 private boolean mSandmanSummoned;
273
Jeff Brown96307042012-07-27 15:51:34 -0700274 // True if MSG_SANDMAN has been scheduled.
275 private boolean mSandmanScheduled;
276
277 // Table of all suspend blockers.
278 // There should only be a few of these.
279 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
280
281 // Table of all wake locks acquired by applications.
282 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
283
284 // A bitfield that summarizes the state of all active wakelocks.
285 private int mWakeLockSummary;
286
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700287 // Have we scheduled a message to check for long wake locks? This is when we will check.
288 private long mNotifyLongScheduled;
289
290 // Last time we checked for long wake locks.
291 private long mNotifyLongDispatched;
292
293 // The time we decided to do next long check.
294 private long mNotifyLongNextCheck;
295
Jeff Brown96307042012-07-27 15:51:34 -0700296 // If true, instructs the display controller to wait for the proximity sensor to
297 // go negative before turning the screen on.
298 private boolean mRequestWaitForNegativeProximity;
299
300 // Timestamp of the last time the device was awoken or put to sleep.
301 private long mLastWakeTime;
302 private long mLastSleepTime;
303
Calin Tatarua3805722018-08-09 16:41:28 +0200304 // Last reason the device went to sleep.
Michael Wrighte3001042019-02-05 00:13:14 +0000305 private @WakeReason int mLastWakeReason;
Calin Tatarua3805722018-08-09 16:41:28 +0200306 private int mLastSleepReason;
307
Jeff Brown96307042012-07-27 15:51:34 -0700308 // Timestamp of the last call to user activity.
309 private long mLastUserActivityTime;
310 private long mLastUserActivityTimeNoChangeLights;
311
Jeff Brown0a571122014-08-21 21:50:43 -0700312 // Timestamp of last interactive power hint.
313 private long mLastInteractivePowerHintTime;
314
Jeff Browne333e672014-10-28 13:48:55 -0700315 // Timestamp of the last screen brightness boost.
316 private long mLastScreenBrightnessBoostTime;
317 private boolean mScreenBrightnessBoostInProgress;
318
Jeff Brown96307042012-07-27 15:51:34 -0700319 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700320 private int mUserActivitySummary;
321
322 // The desired display power state. The actual state may lag behind the
323 // requested because it is updated asynchronously by the display power controller.
324 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
325
Jeff Brown96307042012-07-27 15:51:34 -0700326 // True if the display power state has been fully applied, which means the display
327 // is actually on or actually off or whatever was requested.
328 private boolean mDisplayReady;
329
Jeff Brown27f7a862012-12-12 15:43:31 -0800330 // The suspend blocker used to keep the CPU alive when an application has acquired
331 // a wake lock.
332 private final SuspendBlocker mWakeLockSuspendBlocker;
333
334 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700335 private boolean mHoldingWakeLockSuspendBlocker;
336
Jeff Brown27f7a862012-12-12 15:43:31 -0800337 // The suspend blocker used to keep the CPU alive when the display is on, the
338 // display is getting ready or there is user activity (in which case the display
339 // must be on).
340 private final SuspendBlocker mDisplaySuspendBlocker;
341
342 // True if the display suspend blocker has been acquired.
343 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700344
345 // True if systemReady() has been called.
346 private boolean mSystemReady;
347
348 // True if boot completed occurred. We keep the screen on until this happens.
349 private boolean mBootCompleted;
350
Jeff Brown26875502014-01-30 21:47:47 -0800351 // True if auto-suspend mode is enabled.
352 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700353 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800354
355 // True if interactive mode is enabled.
356 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700357 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800358
Jeff Brown96307042012-07-27 15:51:34 -0700359 // True if the device is plugged into a power source.
360 private boolean mIsPowered;
361
Jeff Brownf3fb8952012-10-02 20:57:05 -0700362 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
363 private int mPlugType;
364
Jeff Brown016ff142012-10-15 16:47:22 -0700365 // The current battery level percentage.
366 private int mBatteryLevel;
367
368 // The battery level percentage at the time the dream started.
369 // This is used to terminate a dream and go to sleep if the battery is
370 // draining faster than it is charging and the user activity timeout has expired.
371 private int mBatteryLevelWhenDreamStarted;
372
Jeff Brownec6aa592012-10-17 20:30:25 -0700373 // The current dock state.
374 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
375
Jeff Brown26875502014-01-30 21:47:47 -0800376 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700377 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800378
379 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700380 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800381
Jeff Brown96307042012-07-27 15:51:34 -0700382 // True if the device should wake up when plugged or unplugged.
383 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
384
Bryce Lee584a4452014-10-21 15:55:55 -0700385 // True if the device should wake up when plugged or unplugged in theater mode.
386 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
387
Jeff Brownec083212013-09-11 20:45:25 -0700388 // True if the device should suspend when the screen is off due to proximity.
389 private boolean mSuspendWhenScreenOffDueToProximityConfig;
390
Robert Horvath5560f382019-07-10 10:46:38 +0200391 // Default value for attentive timeout.
392 private int mAttentiveTimeoutConfig;
393
Jeff Brown96307042012-07-27 15:51:34 -0700394 // True if dreams are supported on this device.
395 private boolean mDreamsSupportedConfig;
396
John Spurlocked108f32012-10-18 16:49:24 -0400397 // Default value for dreams enabled
398 private boolean mDreamsEnabledByDefaultConfig;
399
400 // Default value for dreams activate-on-sleep
401 private boolean mDreamsActivatedOnSleepByDefaultConfig;
402
403 // Default value for dreams activate-on-dock
404 private boolean mDreamsActivatedOnDockByDefaultConfig;
405
Jeff Brown26875502014-01-30 21:47:47 -0800406 // True if dreams can run while not plugged in.
407 private boolean mDreamsEnabledOnBatteryConfig;
408
409 // Minimum battery level to allow dreaming when powered.
410 // Use -1 to disable this safety feature.
411 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
412
413 // Minimum battery level to allow dreaming when not powered.
414 // Use -1 to disable this safety feature.
415 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
416
417 // If the battery level drops by this percentage and the user activity timeout
418 // has expired, then assume the device is receiving insufficient current to charge
419 // effectively and terminate the dream. Use -1 to disable this safety feature.
420 private int mDreamsBatteryLevelDrainCutoffConfig;
421
Jeff Brown96307042012-07-27 15:51:34 -0700422 // True if dreams are enabled by the user.
423 private boolean mDreamsEnabledSetting;
424
John Spurlock1a868b72012-08-22 09:56:51 -0400425 // True if dreams should be activated on sleep.
426 private boolean mDreamsActivateOnSleepSetting;
427
Jeff Brownec6aa592012-10-17 20:30:25 -0700428 // True if dreams should be activated on dock.
429 private boolean mDreamsActivateOnDockSetting;
430
Jeff Brown2175e9c2014-09-12 16:11:07 -0700431 // True if doze should not be started until after the screen off transition.
Lucas Dupin16cfe452018-02-08 13:14:50 -0800432 private boolean mDozeAfterScreenOff;
Jeff Brown2175e9c2014-09-12 16:11:07 -0700433
Jeff Brown27736f52014-05-20 17:17:10 -0700434 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100435 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700436
437 // The screen dim duration, in milliseconds.
438 // This is subtracted from the end of the screen off timeout so the
439 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100440 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700441
442 // The maximum screen dim time expressed as a ratio relative to the screen
443 // off timeout. If the screen off timeout is very short then we want the
444 // dim timeout to also be quite short so that most of the time is spent on.
445 // Otherwise the user won't get much screen on time before dimming occurs.
446 private float mMaximumScreenDimRatioConfig;
447
Jason Monk27bbb2d2015-03-31 16:46:39 -0400448 // Whether device supports double tap to wake.
449 private boolean mSupportsDoubleTapWakeConfig;
450
Jeff Brown96307042012-07-27 15:51:34 -0700451 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100452 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700453
Robert Horvath5560f382019-07-10 10:46:38 +0200454 // Default for attentive warning duration.
455 private long mAttentiveWarningDurationConfig;
456
Jeff Brown05af6ad2014-09-30 20:54:30 -0700457 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100458 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700459
Robert Horvath5560f382019-07-10 10:46:38 +0200460 // How long to show a warning message to user before the device goes to sleep
461 // after long user inactivity, even if wakelocks are held.
462 private long mAttentiveTimeoutSetting;
463
Jeff Brown96307042012-07-27 15:51:34 -0700464 // The maximum allowable screen off timeout according to the device
465 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100466 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700467
468 // The stay on while plugged in setting.
469 // A bitfield of battery conditions under which to make the screen stay on.
470 private int mStayOnWhilePluggedInSetting;
471
472 // True if the device should stay on.
473 private boolean mStayOn;
474
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800475 // True if the lights should stay off until an explicit user action.
476 private static boolean sQuiescent;
477
Jeff Brown93cbbb22012-10-04 13:18:36 -0700478 // True if the proximity sensor reads a positive result.
479 private boolean mProximityPositive;
480
Jeff Brown96307042012-07-27 15:51:34 -0700481 // Screen brightness setting limits.
482 private int mScreenBrightnessSettingMinimum;
483 private int mScreenBrightnessSettingMaximum;
484 private int mScreenBrightnessSettingDefault;
485
486 // The screen brightness setting, from 0 to 255.
487 // Use -1 if no value has been set.
488 private int mScreenBrightnessSetting;
489
490 // The screen brightness mode.
491 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
492 private int mScreenBrightnessModeSetting;
493
494 // The screen brightness setting override from the window manager
495 // to allow the current foreground activity to override the brightness.
496 // Use -1 to disable.
497 private int mScreenBrightnessOverrideFromWindowManager = -1;
498
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700499 // The window manager has determined the user to be inactive via other means.
500 // Set this to false to disable.
501 private boolean mUserInactiveOverrideFromWindowManager;
502
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700503 // The next possible user activity timeout after being explicitly told the user is inactive.
504 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
505 private long mOverriddenTimeout = -1;
506
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700507 // The user activity timeout override from the window manager
508 // to allow the current foreground activity to override the user activity timeout.
509 // Use -1 to disable.
510 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
511
Jeff Brown970d4132014-07-19 11:33:47 -0700512 // The screen state to use while dozing.
513 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
514
515 // The screen brightness to use while dozing.
516 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
517
Ivan Podogov56bc6d02018-02-26 16:04:24 +0000518 // Keep display state when dozing.
519 private boolean mDrawWakeLockOverrideFromSidekick;
520
Jeff Brown9ba8d782012-10-01 16:38:23 -0700521 // Time when we last logged a warning about calling userActivity() without permission.
522 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
523
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700524 // True if the battery level is currently considered low.
525 private boolean mBatteryLevelLow;
526
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700527 // True if we are currently in device idle mode.
528 private boolean mDeviceIdleMode;
529
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700530 // True if we are currently in light device idle mode.
531 private boolean mLightDeviceIdleMode;
532
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700533 // Set of app ids that we will always respect the wake locks for.
534 int[] mDeviceIdleWhitelist = new int[0];
535
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700536 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
537 int[] mDeviceIdleTempWhitelist = new int[0];
538
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700539 private final SparseArray<UidState> mUidState = new SparseArray<>();
540
541 // We are currently in the middle of a batch change of uids.
542 private boolean mUidsChanging;
543
544 // Some uids have actually changed while mUidsChanging was true.
545 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700546
Bryce Lee584a4452014-10-21 15:55:55 -0700547 // True if theater mode is enabled
548 private boolean mTheaterModeEnabled;
549
Adrian Roos56021892017-02-27 20:25:09 +0100550 // True if always on display is enabled
551 private boolean mAlwaysOnEnabled;
552
Jason Monk27bbb2d2015-03-31 16:46:39 -0400553 // True if double tap to wake is enabled
554 private boolean mDoubleTapWakeEnabled;
555
Santos Cordon3107d292016-09-20 15:50:35 -0700556 // True if we are currently in VR Mode.
557 private boolean mIsVrModeEnabled;
558
Santos Cordon12f92eb2019-02-01 21:28:47 +0000559 // True if we in the process of performing a forceSuspend
560 private boolean mForceSuspendActive;
561
Santos Cordon03044382019-09-19 16:59:01 +0100562 // Transition to Doze is in progress. We have transitioned to WAKEFULNESS_DOZING,
563 // but the DreamService has not yet been told to start (it's an async process).
564 private boolean mDozeStartInProgress;
565
Pavel Grafov28939982017-10-03 15:11:52 +0100566 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
567 @Override
Beverly478722e2019-10-14 11:16:57 -0400568 public void onUserSwitching(@UserIdInt int newUserId) throws RemoteException {
569 synchronized (mLock) {
570 mUserId = newUserId;
571 }
572 }
Pavel Grafov28939982017-10-03 15:11:52 +0100573
574 @Override
575 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
576 final long now = SystemClock.uptimeMillis();
Beverly478722e2019-10-14 11:16:57 -0400577 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +0100578 mForegroundProfile = newProfileId;
579 maybeUpdateForegroundProfileLastActivityLocked(now);
580 }
581 }
582 }
583
584 // User id corresponding to activity the user is currently interacting with.
585 private @UserIdInt int mForegroundProfile;
Beverly478722e2019-10-14 11:16:57 -0400586 // User id of main profile for the current user (doesn't include managed profiles)
587 private @UserIdInt int mUserId;
Pavel Grafov28939982017-10-03 15:11:52 +0100588
589 // Per-profile state to track when a profile should be locked.
590 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
591
592 private static final class ProfilePowerState {
593 // Profile user id.
594 final @UserIdInt int mUserId;
595 // Maximum time to lock set by admin.
596 long mScreenOffTimeout;
597 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
598 int mWakeLockSummary;
599 // Last user activity that happened in an app running in the profile.
600 long mLastUserActivityTime;
601 // Whether profile has been locked last time it timed out.
602 boolean mLockingNotified;
603
604 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
605 mUserId = userId;
606 mScreenOffTimeout = screenOffTimeout;
607 // Not accurate but at least won't cause immediate locking of the profile.
608 mLastUserActivityTime = SystemClock.uptimeMillis();
609 }
610 }
611
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800612 /**
613 * All times are in milliseconds. These constants are kept synchronized with the system
614 * global Settings. Any access to this class or its fields should be done while
615 * holding the PowerManagerService.mLock lock.
616 */
617 private final class Constants extends ContentObserver {
618 // Key names stored in the settings value.
619 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
620
621 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
622
623 // Prevent processes that are cached from holding wake locks?
624 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
625
626 private ContentResolver mResolver;
627 private final KeyValueListParser mParser = new KeyValueListParser(',');
628
629 public Constants(Handler handler) {
630 super(handler);
631 }
632
633 public void start(ContentResolver resolver) {
634 mResolver = resolver;
635 mResolver.registerContentObserver(Settings.Global.getUriFor(
636 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
637 updateConstants();
638 }
639
640 @Override
641 public void onChange(boolean selfChange, Uri uri) {
642 updateConstants();
643 }
644
645 private void updateConstants() {
646 synchronized (mLock) {
647 try {
648 mParser.setString(Settings.Global.getString(mResolver,
649 Settings.Global.POWER_MANAGER_CONSTANTS));
650 } catch (IllegalArgumentException e) {
651 // Failed to parse the settings string, log this and move on
652 // with defaults.
653 Slog.e(TAG, "Bad alarm manager settings", e);
654 }
655
656 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
657 DEFAULT_NO_CACHED_WAKE_LOCKS);
658 }
659 }
660
661 void dump(PrintWriter pw) {
662 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
663
664 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
665 pw.println(NO_CACHED_WAKE_LOCKS);
666 }
Netta P958d0a52017-02-07 11:20:55 -0800667
668 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700669 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
670 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800671 NO_CACHED_WAKE_LOCKS);
672 proto.end(constantsToken);
673 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800674 }
675
Santos Cordon64a6e612018-08-22 19:27:04 +0100676 /**
677 * Wrapper around the static-native methods of PowerManagerService.
678 *
679 * This class exists to allow us to mock static native methods in our tests. If mocking static
680 * methods becomes easier than this in the future, we can delete this class.
681 */
682 @VisibleForTesting
683 public static class NativeWrapper {
684 /** Wrapper for PowerManager.nativeInit */
685 public void nativeInit(PowerManagerService service) {
686 service.nativeInit();
687 }
688
689 /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
690 public void nativeAcquireSuspendBlocker(String name) {
691 PowerManagerService.nativeAcquireSuspendBlocker(name);
692 }
693
694 /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
695 public void nativeReleaseSuspendBlocker(String name) {
696 PowerManagerService.nativeReleaseSuspendBlocker(name);
697 }
698
699 /** Wrapper for PowerManager.nativeSetInteractive */
700 public void nativeSetInteractive(boolean enable) {
701 PowerManagerService.nativeSetInteractive(enable);
702 }
703
704 /** Wrapper for PowerManager.nativeSetAutoSuspend */
705 public void nativeSetAutoSuspend(boolean enable) {
706 PowerManagerService.nativeSetAutoSuspend(enable);
707 }
708
709 /** Wrapper for PowerManager.nativeSendPowerHint */
710 public void nativeSendPowerHint(int hintId, int data) {
711 PowerManagerService.nativeSendPowerHint(hintId, data);
712 }
713
714 /** Wrapper for PowerManager.nativeSetFeature */
715 public void nativeSetFeature(int featureId, int data) {
716 PowerManagerService.nativeSetFeature(featureId, data);
717 }
Santos Cordon12f92eb2019-02-01 21:28:47 +0000718
719 /** Wrapper for PowerManager.nativeForceSuspend */
720 public boolean nativeForceSuspend() {
721 return PowerManagerService.nativeForceSuspend();
722 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100723 }
724
725 @VisibleForTesting
726 static class Injector {
727 Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
728 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
729 return new Notifier(looper, context, batteryStats, suspendBlocker, policy);
730 }
731
732 SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
733 SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
734 service.mSuspendBlockers.add(suspendBlocker);
735 return suspendBlocker;
736 }
737
738 BatterySaverPolicy createBatterySaverPolicy(
739 Object lock, Context context, BatterySavingStats batterySavingStats) {
740 return new BatterySaverPolicy(lock, context, batterySavingStats);
741 }
742
743 NativeWrapper createNativeWrapper() {
744 return new NativeWrapper();
745 }
Santos Cordon9b510a22018-08-24 16:42:54 +0100746
747 WirelessChargerDetector createWirelessChargerDetector(
748 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
749 return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
750 }
751
752 AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
753 return new AmbientDisplayConfiguration(context);
754 }
Robert Horvath5560f382019-07-10 10:46:38 +0200755
756 InattentiveSleepWarningController createInattentiveSleepWarningController() {
757 return new InattentiveSleepWarningController();
758 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100759 }
760
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800761 final Constants mConstants;
762
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700763 private native void nativeInit();
Jeff Brown96307042012-07-27 15:51:34 -0700764 private static native void nativeAcquireSuspendBlocker(String name);
765 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700766 private static native void nativeSetInteractive(boolean enable);
767 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700768 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400769 private static native void nativeSetFeature(int featureId, int data);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000770 private static native boolean nativeForceSuspend();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800771
Jeff Brownb880d882014-02-10 19:47:07 -0800772 public PowerManagerService(Context context) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100773 this(context, new Injector());
774 }
775
776 @VisibleForTesting
777 PowerManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800778 super(context);
Santos Cordon64a6e612018-08-22 19:27:04 +0100779
Jeff Brownb880d882014-02-10 19:47:07 -0800780 mContext = context;
Santos Cordon64a6e612018-08-22 19:27:04 +0100781 mBinderService = new BinderService();
782 mLocalService = new LocalService();
783 mNativeWrapper = injector.createNativeWrapper();
784 mInjector = injector;
785
Jeff Brown2c43c332014-06-12 22:38:59 -0700786 mHandlerThread = new ServiceThread(TAG,
787 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
788 mHandlerThread.start();
789 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800790 mConstants = new Constants(mHandler);
Santos Cordon9b510a22018-08-24 16:42:54 +0100791 mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800792 mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800793
Makoto Onukibd7a6252018-05-10 13:41:39 -0700794 mBatterySavingStats = new BatterySavingStats(mLock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100795 mBatterySaverPolicy =
796 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700797 mBatterySaverController = new BatterySaverController(mLock, mContext,
Santos Cordon64a6e612018-08-22 19:27:04 +0100798 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
799 mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700800 mBatterySaverStateMachine = new BatterySaverStateMachine(
801 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700802
Robert Horvath5560f382019-07-10 10:46:38 +0200803 mInattentiveSleepWarningOverlayController =
804 mInjector.createInattentiveSleepWarningController();
805
Jeff Brown96307042012-07-27 15:51:34 -0700806 synchronized (mLock) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100807 mWakeLockSuspendBlocker =
808 mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
809 mDisplaySuspendBlocker =
810 mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
811 if (mDisplaySuspendBlocker != null) {
812 mDisplaySuspendBlocker.acquire();
813 mHoldingDisplaySuspendBlocker = true;
814 }
Jeff Brown037c33e2014-04-09 00:31:55 -0700815 mHalAutoSuspendModeEnabled = false;
816 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800817
Jeff Brown96307042012-07-27 15:51:34 -0700818 mWakefulness = WAKEFULNESS_AWAKE;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800819 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
820
Santos Cordon64a6e612018-08-22 19:27:04 +0100821 mNativeWrapper.nativeInit(this);
822 mNativeWrapper.nativeSetAutoSuspend(false);
823 mNativeWrapper.nativeSetInteractive(true);
824 mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800826 }
827
Jeff Brown6f357d32014-01-15 20:40:55 -0800828 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800829 public void onStart() {
Santos Cordon64a6e612018-08-22 19:27:04 +0100830 publishBinderService(Context.POWER_SERVICE, mBinderService);
831 publishLocalService(PowerManagerInternal.class, mLocalService);
Jeff Brown9e316a12012-10-08 19:17:06 -0700832
833 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800834 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700835 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800836
Jeff Brown6d2a9492014-08-07 19:06:49 -0700837 @Override
838 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700839 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600840 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
841 incrementBootCount();
842
843 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700844 final long now = SystemClock.uptimeMillis();
845 mBootCompleted = true;
846 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700847
848 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700849 userActivityNoUpdateLocked(
850 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
851 updatePowerStateLocked();
852 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700853 }
854 }
855
Jeff Brown21392762014-06-13 19:00:36 -0700856 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700857 synchronized (mLock) {
858 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700859 mAppOps = appOps;
860 mDreamManager = getLocalService(DreamManagerInternal.class);
861 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
862 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700863 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800864 mAttentionDetector.systemReady(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800865
Adam Lesinski182f73f2013-12-05 16:48:06 -0800866 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700867 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
868 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
869 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800870
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700871 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800872
Jeff Brownc38c9be2012-10-04 13:16:19 -0700873 // The notifier runs on the system server's main looper so as not to interfere
874 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700875 mBatteryStats = BatteryStatsService.getService();
Santos Cordon64a6e612018-08-22 19:27:04 +0100876 mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
877 mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
878 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700879
Santos Cordon9b510a22018-08-24 16:42:54 +0100880 mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
Santos Cordon64a6e612018-08-22 19:27:04 +0100881 mInjector.createSuspendBlocker(
882 this, "PowerManagerService.WirelessChargerDetector"),
Jeff Browndbcc8a22013-10-01 16:16:44 -0700883 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700884 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700885
886 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800887 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400888
Jeff Brown131206b2014-04-08 17:27:14 -0700889 // Initialize display power management.
890 mDisplayManagerInternal.initPowerManagement(
891 mDisplayPowerCallbacks, mHandler, sensorManager);
892
Pavel Grafov28939982017-10-03 15:11:52 +0100893 try {
894 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
895 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
896 } catch (RemoteException e) {
897 // Shouldn't happen since in-process.
898 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800899
Jeff Brown96307042012-07-27 15:51:34 -0700900 // Go.
901 readConfigurationLocked();
902 updateSettingsLocked();
903 mDirty |= DIRTY_BATTERY_STATE;
904 updatePowerStateLocked();
905 }
Shibin George43f5de02016-07-06 02:12:10 +0530906
Jeff Sharkey6e544612017-02-20 11:02:26 -0700907 final ContentResolver resolver = mContext.getContentResolver();
908 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800909
910 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -0700911 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -0700912
913 // Register for settings changes.
914 resolver.registerContentObserver(Settings.Secure.getUriFor(
915 Settings.Secure.SCREENSAVER_ENABLED),
916 false, mSettingsObserver, UserHandle.USER_ALL);
917 resolver.registerContentObserver(Settings.Secure.getUriFor(
918 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
919 false, mSettingsObserver, UserHandle.USER_ALL);
920 resolver.registerContentObserver(Settings.Secure.getUriFor(
921 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
922 false, mSettingsObserver, UserHandle.USER_ALL);
923 resolver.registerContentObserver(Settings.System.getUriFor(
924 Settings.System.SCREEN_OFF_TIMEOUT),
925 false, mSettingsObserver, UserHandle.USER_ALL);
926 resolver.registerContentObserver(Settings.Secure.getUriFor(
927 Settings.Secure.SLEEP_TIMEOUT),
928 false, mSettingsObserver, UserHandle.USER_ALL);
Robert Horvath5560f382019-07-10 10:46:38 +0200929 resolver.registerContentObserver(Settings.Secure.getUriFor(
930 Settings.Secure.ATTENTIVE_TIMEOUT),
931 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Sharkey6e544612017-02-20 11:02:26 -0700932 resolver.registerContentObserver(Settings.Global.getUriFor(
933 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
934 false, mSettingsObserver, UserHandle.USER_ALL);
935 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700936 Settings.System.SCREEN_BRIGHTNESS_MODE),
937 false, mSettingsObserver, UserHandle.USER_ALL);
938 resolver.registerContentObserver(Settings.System.getUriFor(
939 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
940 false, mSettingsObserver, UserHandle.USER_ALL);
941 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700942 Settings.Global.THEATER_MODE_ON),
943 false, mSettingsObserver, UserHandle.USER_ALL);
944 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100945 Settings.Secure.DOZE_ALWAYS_ON),
946 false, mSettingsObserver, UserHandle.USER_ALL);
947 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700948 Settings.Secure.DOUBLE_TAP_TO_WAKE),
949 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700950 resolver.registerContentObserver(Settings.Global.getUriFor(
951 Settings.Global.DEVICE_DEMO_MODE),
952 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Santos Cordon64a6e612018-08-22 19:27:04 +0100953 IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
Jeff Sharkey6e544612017-02-20 11:02:26 -0700954 if (vrManager != null) {
955 try {
956 vrManager.registerListener(mVrStateCallbacks);
957 } catch (RemoteException e) {
958 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
959 }
960 }
961
Shibin George43f5de02016-07-06 02:12:10 +0530962 // Register for broadcasts from other components of the system.
963 IntentFilter filter = new IntentFilter();
964 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
965 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
966 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
967
968 filter = new IntentFilter();
969 filter.addAction(Intent.ACTION_DREAMING_STARTED);
970 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
971 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
972
973 filter = new IntentFilter();
974 filter.addAction(Intent.ACTION_USER_SWITCHED);
975 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
976
977 filter = new IntentFilter();
978 filter.addAction(Intent.ACTION_DOCK_EVENT);
979 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700980 }
981
Santos Cordon9b510a22018-08-24 16:42:54 +0100982 @VisibleForTesting
983 void readConfigurationLocked() {
Jeff Brown96307042012-07-27 15:51:34 -0700984 final Resources resources = mContext.getResources();
985
Jeff Brown037c33e2014-04-09 00:31:55 -0700986 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800987 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700988 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800989 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700990 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700991 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700992 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
993 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700994 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
995 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Robert Horvath5560f382019-07-10 10:46:38 +0200996 mAttentiveTimeoutConfig = resources.getInteger(
997 com.android.internal.R.integer.config_attentiveTimeout);
998 mAttentiveWarningDurationConfig = resources.getInteger(
999 com.android.internal.R.integer.config_attentiveWarningDuration);
Jeff Brown96307042012-07-27 15:51:34 -07001000 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -04001001 com.android.internal.R.bool.config_dreamsSupported);
1002 mDreamsEnabledByDefaultConfig = resources.getBoolean(
1003 com.android.internal.R.bool.config_dreamsEnabledByDefault);
1004 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
1005 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
1006 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
1007 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -08001008 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
1009 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
1010 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
1011 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
1012 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
1013 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
1014 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
1015 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -08001016 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -07001017 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -07001018 mMinimumScreenOffTimeoutConfig = resources.getInteger(
1019 com.android.internal.R.integer.config_minimumScreenOffTimeout);
1020 mMaximumScreenDimDurationConfig = resources.getInteger(
1021 com.android.internal.R.integer.config_maximumScreenDimDuration);
1022 mMaximumScreenDimRatioConfig = resources.getFraction(
1023 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001024 mSupportsDoubleTapWakeConfig = resources.getBoolean(
1025 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001026 }
1027
Jeff Brown96307042012-07-27 15:51:34 -07001028 private void updateSettingsLocked() {
1029 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -07001030
Jeff Brownd4935962012-09-25 13:27:20 -07001031 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001032 Settings.Secure.SCREENSAVER_ENABLED,
1033 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001034 UserHandle.USER_CURRENT) != 0);
1035 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001036 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
1037 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001038 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -07001039 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001040 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1041 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -07001042 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -07001043 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1044 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1045 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -07001046 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1047 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1048 UserHandle.USER_CURRENT);
Robert Horvath5560f382019-07-10 10:46:38 +02001049 mAttentiveTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1050 Settings.Secure.ATTENTIVE_TIMEOUT, mAttentiveTimeoutConfig,
1051 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -07001052 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -07001053 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -07001054 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1055 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +01001056 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -07001057
Jason Monk27bbb2d2015-03-31 16:46:39 -04001058 if (mSupportsDoubleTapWakeConfig) {
1059 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1060 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1061 UserHandle.USER_CURRENT) != 0;
1062 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1063 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
Santos Cordon64a6e612018-08-22 19:27:04 +01001064 mNativeWrapper.nativeSetFeature(
1065 POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001066 }
1067 }
1068
Christine Franks732c0432017-06-23 18:12:46 -07001069 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1070 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
1071 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1072 }
1073
Jeff Brownd4935962012-09-25 13:27:20 -07001074 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -07001075 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -07001076 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -07001077
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001078 mDirty |= DIRTY_SETTINGS;
1079 }
1080
Jeff Brown96307042012-07-27 15:51:34 -07001081 private void handleSettingsChangedLocked() {
1082 updateSettingsLocked();
1083 updatePowerStateLocked();
1084 }
1085
Dianne Hackborn713df152013-05-17 11:27:57 -07001086 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001087 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001088 synchronized (mLock) {
1089 if (DEBUG_SPEW) {
1090 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1091 + ", flags=0x" + Integer.toHexString(flags)
1092 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001093 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094
Jeff Brown96307042012-07-27 15:51:34 -07001095 WakeLock wakeLock;
1096 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001097 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001098 if (index >= 0) {
1099 wakeLock = mWakeLocks.get(index);
1100 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1101 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001102 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1103 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001104 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001105 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001106 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001107 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001108 UidState state = mUidState.get(uid);
1109 if (state == null) {
1110 state = new UidState(uid);
1111 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1112 mUidState.put(uid, state);
1113 }
1114 state.mNumWakeLocks++;
1115 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1116 state);
Jeff Brown96307042012-07-27 15:51:34 -07001117 try {
1118 lock.linkToDeath(wakeLock, 0);
1119 } catch (RemoteException ex) {
1120 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 }
Jeff Brown96307042012-07-27 15:51:34 -07001122 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001123 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001124 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126
Jeff Brownc12035c2014-08-13 18:52:25 -07001127 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001128 mDirty |= DIRTY_WAKE_LOCKS;
1129 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001130 if (notifyAcquire) {
1131 // This needs to be done last so we are sure we have acquired the
1132 // kernel wake lock. Otherwise we have a race where the system may
1133 // go to sleep between the time we start the accounting in battery
1134 // stats and when we actually get around to telling the kernel to
1135 // stay awake.
1136 notifyWakeLockAcquiredLocked(wakeLock);
1137 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001138 }
1139 }
1140
Jeff Brownec083212013-09-11 20:45:25 -07001141 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001142 private static boolean isScreenLock(final WakeLock wakeLock) {
1143 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1144 case PowerManager.FULL_WAKE_LOCK:
1145 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1146 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1147 return true;
1148 }
1149 return false;
1150 }
1151
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001152 private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1153 if (workSource.getWorkChains() == null) {
1154 return null;
1155 }
1156
1157 for (WorkChain workChain: workSource.getWorkChains()) {
1158 if (workChain.getSize() > 0) {
1159 return workChain;
1160 }
1161 }
1162
1163 return null;
1164 }
1165
Jeff Brownc12035c2014-08-13 18:52:25 -07001166 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001167 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1168 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001169 String opPackageName;
1170 int opUid;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001171 if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1172 WorkSource workSource = wakeLock.mWorkSource;
1173 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1174 if (workChain != null) {
1175 opPackageName = workChain.getAttributionTag();
1176 opUid = workChain.getAttributionUid();
1177 } else {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08001178 opPackageName = workSource.getPackageName(0) != null
1179 ? workSource.getPackageName(0) : wakeLock.mPackageName;
1180 opUid = workSource.getUid(0);
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001181 }
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001182 } else {
1183 opPackageName = wakeLock.mPackageName;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001184 opUid = wakeLock.mOwnerUid;
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001185 }
Michael Wrighte3001042019-02-05 00:13:14 +00001186 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1187 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1188 opUid, opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001189 }
1190 }
1191
Jeff Brown96307042012-07-27 15:51:34 -07001192 private void releaseWakeLockInternal(IBinder lock, int flags) {
1193 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001194 int index = findWakeLockIndexLocked(lock);
1195 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001196 if (DEBUG_SPEW) {
1197 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1198 + " [not found], flags=0x" + Integer.toHexString(flags));
1199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 return;
1201 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001202
Jeff Brown96307042012-07-27 15:51:34 -07001203 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001204 if (DEBUG_SPEW) {
1205 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1206 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1207 }
1208
Michael Wright1208e272014-09-08 19:57:50 -07001209 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001210 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001211 }
1212
Jeff Brown3edf5272014-08-14 19:25:14 -07001213 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1214 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 }
1216 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001217
Jeff Brown96307042012-07-27 15:51:34 -07001218 private void handleWakeLockDeath(WakeLock wakeLock) {
1219 synchronized (mLock) {
1220 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001221 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1222 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001223 }
1224
1225 int index = mWakeLocks.indexOf(wakeLock);
1226 if (index < 0) {
1227 return;
1228 }
1229
Jeff Brown3edf5272014-08-14 19:25:14 -07001230 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001231 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001232 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001233
Jeff Brown3edf5272014-08-14 19:25:14 -07001234 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1235 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001236 UidState state = wakeLock.mUidState;
1237 state.mNumWakeLocks--;
1238 if (state.mNumWakeLocks <= 0 &&
1239 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1240 mUidState.remove(state.mUid);
1241 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001242 notifyWakeLockReleasedLocked(wakeLock);
1243
1244 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1245 mDirty |= DIRTY_WAKE_LOCKS;
1246 updatePowerStateLocked();
1247 }
1248
Jeff Brown96307042012-07-27 15:51:34 -07001249 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001250 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1251 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001252 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1253 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1254 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1255 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001257 }
1258
Dianne Hackbornd953c532014-08-16 18:17:38 -07001259 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1260 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001261 synchronized (mLock) {
1262 int index = findWakeLockIndexLocked(lock);
1263 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001264 if (DEBUG_SPEW) {
1265 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1266 + " [not found], ws=" + ws);
1267 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001268 throw new IllegalArgumentException("Wake lock not active: " + lock
1269 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001270 }
1271
1272 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001273 if (DEBUG_SPEW) {
1274 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1275 + " [" + wakeLock.mTag + "], ws=" + ws);
1276 }
1277
Jeff Brown96307042012-07-27 15:51:34 -07001278 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001279 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1280 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001281 ws, historyTag);
1282 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001283 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001284 }
1285 }
1286 }
1287
1288 private int findWakeLockIndexLocked(IBinder lock) {
1289 final int count = mWakeLocks.size();
1290 for (int i = 0; i < count; i++) {
1291 if (mWakeLocks.get(i).mLock == lock) {
1292 return i;
1293 }
1294 }
1295 return -1;
1296 }
1297
1298 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001299 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001300 wakeLock.mNotifiedAcquired = true;
1301 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001302 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1303 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001304 restartNofifyLongTimerLocked(wakeLock);
1305 }
1306 }
1307
1308 private void enqueueNotifyLongMsgLocked(long time) {
1309 mNotifyLongScheduled = time;
1310 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1311 msg.setAsynchronous(true);
1312 mHandler.sendMessageAtTime(msg, time);
1313 }
1314
1315 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1316 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1317 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1318 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1319 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1320 }
1321 }
1322
1323 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1324 if (mSystemReady && !wakeLock.mDisabled) {
1325 wakeLock.mNotifiedLong = true;
1326 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1327 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1328 }
1329 }
1330
1331 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1332 if (wakeLock.mNotifiedLong) {
1333 wakeLock.mNotifiedLong = false;
1334 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1335 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001336 }
1337 }
1338
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001339 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1340 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1341 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1342 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1343 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1344 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001345 notifyWakeLockLongFinishedLocked(wakeLock);
1346 // Changing the wake lock will count as releasing the old wake lock(s) and
1347 // acquiring the new ones... we do this because otherwise once a wakelock
1348 // becomes long, if we just continued to treat it as long we can get in to
1349 // situations where we spam battery stats with every following change to it.
1350 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001351 }
1352 }
1353
Jeff Brown96307042012-07-27 15:51:34 -07001354 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001355 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1356 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001357 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001358 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1359 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1360 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001361 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001362 }
1363 }
1364
Jeff Brownec083212013-09-11 20:45:25 -07001365 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001366 private boolean isWakeLockLevelSupportedInternal(int level) {
1367 synchronized (mLock) {
1368 switch (level) {
1369 case PowerManager.PARTIAL_WAKE_LOCK:
1370 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1371 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1372 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001373 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001374 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001375 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001376
1377 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001378 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001379
1380 default:
1381 return false;
1382 }
1383 }
1384 }
1385
Jeff Brown96307042012-07-27 15:51:34 -07001386 // Called from native code.
1387 private void userActivityFromNative(long eventTime, int event, int flags) {
1388 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1389 }
1390
1391 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1392 synchronized (mLock) {
1393 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1394 updatePowerStateLocked();
1395 }
1396 }
1397 }
1398
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001399 private void onUserAttention() {
1400 synchronized (mLock) {
1401 if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1402 PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1403 Process.SYSTEM_UID)) {
1404 updatePowerStateLocked();
1405 }
1406 }
1407 }
1408
Jeff Brown96307042012-07-27 15:51:34 -07001409 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1410 if (DEBUG_SPEW) {
1411 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1412 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1413 + ", uid=" + uid);
1414 }
1415
1416 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001417 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001418 return false;
1419 }
1420
Jeff Brown3edf5272014-08-14 19:25:14 -07001421 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1422 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001423 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001424 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001425 mLastInteractivePowerHintTime = eventTime;
1426 }
1427
Jeff Brown3edf5272014-08-14 19:25:14 -07001428 mNotifier.onUserActivity(event, uid);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001429 mAttentionDetector.onUserActivity(eventTime, event);
Jeff Brown96307042012-07-27 15:51:34 -07001430
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001431 if (mUserInactiveOverrideFromWindowManager) {
1432 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001433 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001434 }
1435
Jeff Brown0a571122014-08-21 21:50:43 -07001436 if (mWakefulness == WAKEFULNESS_ASLEEP
1437 || mWakefulness == WAKEFULNESS_DOZING
1438 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1439 return false;
1440 }
1441
Pavel Grafov28939982017-10-03 15:11:52 +01001442 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1443
Jeff Brown3edf5272014-08-14 19:25:14 -07001444 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1445 if (eventTime > mLastUserActivityTimeNoChangeLights
1446 && eventTime > mLastUserActivityTime) {
1447 mLastUserActivityTimeNoChangeLights = eventTime;
1448 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001449 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1450 mDirty |= DIRTY_QUIESCENT;
1451 }
1452
Jeff Brown3edf5272014-08-14 19:25:14 -07001453 return true;
1454 }
1455 } else {
1456 if (eventTime > mLastUserActivityTime) {
1457 mLastUserActivityTime = eventTime;
1458 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001459 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1460 mDirty |= DIRTY_QUIESCENT;
1461 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001462 return true;
1463 }
Jeff Brown96307042012-07-27 15:51:34 -07001464 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001465 } finally {
1466 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001467 }
1468 return false;
1469 }
1470
Pavel Grafov28939982017-10-03 15:11:52 +01001471 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1472 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1473 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1474 profile.mLastUserActivityTime = eventTime;
1475 }
1476 }
1477
Michael Wrighte3001042019-02-05 00:13:14 +00001478 private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1479 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001480 synchronized (mLock) {
Michael Wrighte3001042019-02-05 00:13:14 +00001481 if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001482 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001483 }
1484 }
Jeff Brown96307042012-07-27 15:51:34 -07001485 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001486
Michael Wrighte3001042019-02-05 00:13:14 +00001487 private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1488 int reasonUid, String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001489 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001490 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001491 }
Jeff Brown96307042012-07-27 15:51:34 -07001492
1493 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
Santos Cordon12f92eb2019-02-01 21:28:47 +00001494 || !mBootCompleted || !mSystemReady || mForceSuspendActive) {
Jeff Brown96307042012-07-27 15:51:34 -07001495 return false;
1496 }
1497
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001498 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1499
Jeff Brown3edf5272014-08-14 19:25:14 -07001500 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1501 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001502 Slog.i(TAG, "Waking up from "
1503 + PowerManagerInternal.wakefulnessToString(mWakefulness)
1504 + " (uid=" + reasonUid
1505 + ", reason=" + PowerManager.wakeReasonToString(reason)
1506 + ", details=" + details
1507 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001508
1509 mLastWakeTime = eventTime;
Michael Wrighte3001042019-02-05 00:13:14 +00001510 mLastWakeReason = reason;
1511 setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001512
Michael Wrighte3001042019-02-05 00:13:14 +00001513 mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001514 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001515 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001516 } finally {
1517 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001518 }
Jeff Brown96307042012-07-27 15:51:34 -07001519 return true;
1520 }
1521
Jeff Brownc12035c2014-08-13 18:52:25 -07001522 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001523 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001524 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001525 updatePowerStateLocked();
1526 }
1527 }
1528 }
1529
Santos Cordon12f92eb2019-02-01 21:28:47 +00001530 /**
1531 * Puts the system in doze.
1532 *
1533 * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1534 * and only tucks itself in to SLEEP if requested with the flag
1535 * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1536 */
Jeff Brownec083212013-09-11 20:45:25 -07001537 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001538 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001539 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001540 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001541 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001542 }
1543
Jeff Brown26875502014-01-30 21:47:47 -08001544 if (eventTime < mLastWakeTime
1545 || mWakefulness == WAKEFULNESS_ASLEEP
1546 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001547 || !mBootCompleted || !mSystemReady) {
1548 return false;
1549 }
1550
Jeff Brown3edf5272014-08-14 19:25:14 -07001551 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1552 try {
Santos Cordon12f92eb2019-02-01 21:28:47 +00001553 reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1554 Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1555 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1556 + " (uid " + uid + ")...");
Jeff Brown6d8fd272014-05-20 21:24:38 -07001557
Jeff Brown3edf5272014-08-14 19:25:14 -07001558 mLastSleepTime = eventTime;
Calin Tatarua3805722018-08-09 16:41:28 +02001559 mLastSleepReason = reason;
Jeff Brown3edf5272014-08-14 19:25:14 -07001560 mSandmanSummoned = true;
Santos Cordon03044382019-09-19 16:59:01 +01001561 mDozeStartInProgress = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001562 setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001563
1564 // Report the number of wake locks that will be cleared by going to sleep.
1565 int numWakeLocksCleared = 0;
1566 final int numWakeLocks = mWakeLocks.size();
1567 for (int i = 0; i < numWakeLocks; i++) {
1568 final WakeLock wakeLock = mWakeLocks.get(i);
1569 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1570 case PowerManager.FULL_WAKE_LOCK:
1571 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1572 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1573 numWakeLocksCleared += 1;
1574 break;
1575 }
1576 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001577 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001578
1579 // Skip dozing if requested.
1580 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1581 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1582 }
1583 } finally {
1584 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001585 }
Jeff Brown96307042012-07-27 15:51:34 -07001586 return true;
1587 }
1588
Jeff Brownc12035c2014-08-13 18:52:25 -07001589 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001590 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001591 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001592 updatePowerStateLocked();
1593 }
1594 }
1595 }
1596
Jeff Brownc12035c2014-08-13 18:52:25 -07001597 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001598 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001599 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001600 }
1601
1602 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1603 || !mBootCompleted || !mSystemReady) {
1604 return false;
1605 }
1606
Jeff Brown3edf5272014-08-14 19:25:14 -07001607 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1608 try {
1609 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001610
Jeff Brown3edf5272014-08-14 19:25:14 -07001611 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001612 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001613 } finally {
1614 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1615 }
Jeff Brown26875502014-01-30 21:47:47 -08001616 return true;
1617 }
1618
1619 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001620 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001621 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001622 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1623 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001624 }
1625
1626 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1627 || !mBootCompleted || !mSystemReady) {
1628 return false;
1629 }
1630
Jeff Brown3edf5272014-08-14 19:25:14 -07001631 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1632 try {
1633 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001634
Michael Wrighte3001042019-02-05 00:13:14 +00001635 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1636 eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001637 } finally {
1638 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1639 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001640 return true;
1641 }
1642
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001643 @VisibleForTesting
Michael Wrighte3001042019-02-05 00:13:14 +00001644 void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001645 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001646 mWakefulness = wakefulness;
1647 mWakefulnessChanging = true;
1648 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon03044382019-09-19 16:59:01 +01001649
1650 // This is only valid while we are in wakefulness dozing. Set to false otherwise.
1651 mDozeStartInProgress &= (mWakefulness == WAKEFULNESS_DOZING);
1652
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001653 if (mNotifier != null) {
Michael Wrighte3001042019-02-05 00:13:14 +00001654 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001655 }
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001656 mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
Jeff Brown037c33e2014-04-09 00:31:55 -07001657 }
1658 }
1659
Santos Cordon64a6e612018-08-22 19:27:04 +01001660 @VisibleForTesting
1661 int getWakefulness() {
1662 return mWakefulness;
1663 }
1664
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001665 /**
1666 * Logs the time the device would have spent awake before user activity timeout,
1667 * had the system not been told the user was inactive.
1668 */
1669 private void logSleepTimeoutRecapturedLocked() {
1670 final long now = SystemClock.uptimeMillis();
1671 final long savedWakeTimeMs = mOverriddenTimeout - now;
1672 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001673 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001674 mOverriddenTimeout = -1;
1675 }
1676 }
1677
Jeff Brown416c49c2015-05-26 19:50:18 -07001678 private void finishWakefulnessChangeIfNeededLocked() {
1679 if (mWakefulnessChanging && mDisplayReady) {
1680 if (mWakefulness == WAKEFULNESS_DOZING
1681 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1682 return; // wait until dream has enabled dozing
Santos Cordon03044382019-09-19 16:59:01 +01001683 } else {
1684 // Doze wakelock acquired (doze started) or device is no longer dozing.
1685 mDozeStartInProgress = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001686 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001687 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1688 logSleepTimeoutRecapturedLocked();
1689 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001690 if (mWakefulness == WAKEFULNESS_AWAKE) {
Michael Wrighte3001042019-02-05 00:13:14 +00001691 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1692 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1693 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1694 Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1695 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001696 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001697 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001698 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001699 }
1700 }
1701
Jeff Brown96307042012-07-27 15:51:34 -07001702 /**
1703 * Updates the global power state based on dirty bits recorded in mDirty.
1704 *
1705 * This is the main function that performs power state transitions.
1706 * We centralize them here so that we can recompute the power state completely
1707 * each time something important changes, and ensure that we do it the same
1708 * way each time. The point is to gather all of the transition logic here.
1709 */
1710 private void updatePowerStateLocked() {
1711 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001712 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001713 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001714 if (!Thread.holdsLock(mLock)) {
1715 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1716 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001717
Jeff Brown3edf5272014-08-14 19:25:14 -07001718 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1719 try {
1720 // Phase 0: Basic state updates.
1721 updateIsPoweredLocked(mDirty);
1722 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001723 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001724
Jeff Brown3edf5272014-08-14 19:25:14 -07001725 // Phase 1: Update wakefulness.
1726 // Loop because the wake lock and user activity computations are influenced
1727 // by changes in wakefulness.
1728 final long now = SystemClock.uptimeMillis();
1729 int dirtyPhase2 = 0;
1730 for (;;) {
1731 int dirtyPhase1 = mDirty;
1732 dirtyPhase2 |= dirtyPhase1;
1733 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001734
Jeff Brown3edf5272014-08-14 19:25:14 -07001735 updateWakeLockSummaryLocked(dirtyPhase1);
1736 updateUserActivitySummaryLocked(now, dirtyPhase1);
Robert Horvath5560f382019-07-10 10:46:38 +02001737 updateAttentiveStateLocked(now, dirtyPhase1);
Jeff Brown3edf5272014-08-14 19:25:14 -07001738 if (!updateWakefulnessLocked(dirtyPhase1)) {
1739 break;
1740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001742
Pavel Grafov28939982017-10-03 15:11:52 +01001743 // Phase 2: Lock profiles that became inactive/not kept awake.
1744 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001745
Pavel Grafov28939982017-10-03 15:11:52 +01001746 // Phase 3: Update display power state.
1747 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1748
1749 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001750 updateDreamLocked(dirtyPhase2, displayBecameReady);
1751
Pavel Grafov28939982017-10-03 15:11:52 +01001752 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001753 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001754
Pavel Grafov28939982017-10-03 15:11:52 +01001755 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001756 // Because we might release the last suspend blocker here, we need to make sure
1757 // we finished everything else first!
1758 updateSuspendBlockerLocked();
1759 } finally {
1760 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 }
Jeff Brown96307042012-07-27 15:51:34 -07001762 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001763
Jim Miller92e66dd2012-02-21 18:57:12 -08001764 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001765 * Check profile timeouts and notify profiles that should be locked.
1766 */
1767 private void updateProfilesLocked(long now) {
1768 final int numProfiles = mProfilePowerState.size();
1769 for (int i = 0; i < numProfiles; i++) {
1770 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1771 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1772 profile.mLockingNotified = false;
1773 } else if (!profile.mLockingNotified) {
1774 profile.mLockingNotified = true;
1775 mNotifier.onProfileTimeout(profile.mUserId);
1776 }
1777 }
1778 }
1779
1780 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1781 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1782 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1783 || (mProximityPositive &&
1784 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1785 }
1786
1787 /**
Jeff Brown96307042012-07-27 15:51:34 -07001788 * Updates the value of mIsPowered.
1789 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001790 */
Jeff Brown96307042012-07-27 15:51:34 -07001791 private void updateIsPoweredLocked(int dirty) {
1792 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001793 final boolean wasPowered = mIsPowered;
1794 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001795 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001796 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1797 mPlugType = mBatteryManagerInternal.getPlugType();
1798 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1799 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001800
Jeff Brown26875502014-01-30 21:47:47 -08001801 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001802 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001803 + ", mIsPowered=" + mIsPowered
1804 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001805 + ", mPlugType=" + mPlugType
1806 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001807 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001808
Jeff Brownf3fb8952012-10-02 20:57:05 -07001809 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001810 mDirty |= DIRTY_IS_POWERED;
1811
Jeff Brown3b971592013-01-09 18:46:37 -08001812 // Update wireless dock detection state.
1813 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001814 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001815
Jeff Brown96307042012-07-27 15:51:34 -07001816 // Treat plugging and unplugging the devices as a user activity.
1817 // Users find it disconcerting when they plug or unplug the device
1818 // and it shuts off right away.
1819 // Some devices also wake the device when plugged or unplugged because
1820 // they don't have a charging LED.
1821 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001822 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1823 dockedOnWirelessCharger)) {
Michael Wrighte3001042019-02-05 00:13:14 +00001824 wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1825 "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001826 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001827 }
1828 userActivityNoUpdateLocked(
1829 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001830
Beverlyac32c9a2018-01-31 16:10:41 -05001831 // only play charging sounds if boot is completed so charging sounds don't play
1832 // with potential notification sounds
1833 if (mBootCompleted) {
1834 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1835 && BatteryManager.isPlugWired(mPlugType)) {
Beverly478722e2019-10-14 11:16:57 -04001836 mNotifier.onWiredChargingStarted(mUserId);
Beverlyac32c9a2018-01-31 16:10:41 -05001837 } else if (dockedOnWirelessCharger) {
Beverly478722e2019-10-14 11:16:57 -04001838 mNotifier.onWirelessChargingStarted(mBatteryLevel, mUserId);
Beverlyac32c9a2018-01-31 16:10:41 -05001839 }
Jeff Brown84e27562012-12-07 13:56:34 -08001840 }
Jeff Brown96307042012-07-27 15:51:34 -07001841 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001842
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001843 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001844 }
1845 }
1846
Jeff Brown3b971592013-01-09 18:46:37 -08001847 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1848 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001849 // Don't wake when powered unless configured to do so.
1850 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1851 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001852 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001853
Jeff Brown3b971592013-01-09 18:46:37 -08001854 // Don't wake when undocked from wireless charger.
1855 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001856 if (wasPowered && !mIsPowered
1857 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1858 return false;
1859 }
Jeff Brown3b971592013-01-09 18:46:37 -08001860
1861 // Don't wake when docked on wireless charger unless we are certain of it.
1862 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001863 if (!wasPowered && mIsPowered
1864 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001865 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001866 return false;
1867 }
1868
1869 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001870 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001871 return false;
1872 }
1873
Bryce Lee584a4452014-10-21 15:55:55 -07001874 // Don't wake while theater mode is enabled.
1875 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1876 return false;
1877 }
1878
Adrian Roos56021892017-02-27 20:25:09 +01001879 // On Always On Display, SystemUI shows the charging indicator
1880 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1881 return false;
1882 }
1883
Jeff Brown9fca9e92012-10-05 14:42:56 -07001884 // Otherwise wake up!
1885 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001886 }
1887
Jeff Brown96307042012-07-27 15:51:34 -07001888 /**
1889 * Updates the value of mStayOn.
1890 * Sets DIRTY_STAY_ON if a change occurred.
1891 */
1892 private void updateStayOnLocked(int dirty) {
1893 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001894 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001895 if (mStayOnWhilePluggedInSetting != 0
1896 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001897 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001898 } else {
1899 mStayOn = false;
1900 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001901
1902 if (mStayOn != wasStayOn) {
1903 mDirty |= DIRTY_STAY_ON;
1904 }
Jeff Brown96307042012-07-27 15:51:34 -07001905 }
1906 }
1907
1908 /**
1909 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1910 * Note that most wake-locks are ignored when the system is asleep.
1911 *
1912 * This function must have no other side-effects.
1913 */
Jeff Brownec083212013-09-11 20:45:25 -07001914 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001915 private void updateWakeLockSummaryLocked(int dirty) {
1916 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1917 mWakeLockSummary = 0;
1918
Pavel Grafov28939982017-10-03 15:11:52 +01001919 final int numProfiles = mProfilePowerState.size();
1920 for (int i = 0; i < numProfiles; i++) {
1921 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1922 }
1923
Jeff Brown96307042012-07-27 15:51:34 -07001924 final int numWakeLocks = mWakeLocks.size();
1925 for (int i = 0; i < numWakeLocks; i++) {
1926 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001927 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1928 mWakeLockSummary |= wakeLockFlags;
1929 for (int j = 0; j < numProfiles; j++) {
1930 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1931 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1932 profile.mWakeLockSummary |= wakeLockFlags;
1933 }
Jeff Brown96307042012-07-27 15:51:34 -07001934 }
1935 }
1936
Pavel Grafov28939982017-10-03 15:11:52 +01001937 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1938 for (int i = 0; i < numProfiles; i++) {
1939 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1940 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001941 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001942
Jeff Brown96307042012-07-27 15:51:34 -07001943 if (DEBUG_SPEW) {
1944 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001945 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001946 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1947 }
1948 }
1949 }
1950
Pavel Grafov28939982017-10-03 15:11:52 +01001951 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1952 // Cancel wake locks that make no sense based on the current state.
1953 if (mWakefulness != WAKEFULNESS_DOZING) {
1954 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1955 }
1956 if (mWakefulness == WAKEFULNESS_ASLEEP
1957 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1958 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1959 | WAKE_LOCK_BUTTON_BRIGHT);
1960 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1961 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1962 }
1963 }
1964
1965 // Infer implied wake locks where necessary based on the current state.
1966 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1967 if (mWakefulness == WAKEFULNESS_AWAKE) {
1968 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1969 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1970 wakeLockSummary |= WAKE_LOCK_CPU;
1971 }
1972 }
1973 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1974 wakeLockSummary |= WAKE_LOCK_CPU;
1975 }
1976
1977 return wakeLockSummary;
1978 }
1979
1980 /** Get wake lock summary flags that correspond to the given wake lock. */
1981 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1982 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1983 case PowerManager.PARTIAL_WAKE_LOCK:
1984 if (!wakeLock.mDisabled) {
1985 // We only respect this if the wake lock is not disabled.
1986 return WAKE_LOCK_CPU;
1987 }
1988 break;
1989 case PowerManager.FULL_WAKE_LOCK:
1990 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1991 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1992 return WAKE_LOCK_SCREEN_BRIGHT;
1993 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1994 return WAKE_LOCK_SCREEN_DIM;
1995 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1996 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1997 case PowerManager.DOZE_WAKE_LOCK:
1998 return WAKE_LOCK_DOZE;
1999 case PowerManager.DRAW_WAKE_LOCK:
2000 return WAKE_LOCK_DRAW;
2001 }
2002 return 0;
2003 }
2004
2005 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
2006 if (wakeLock.mWorkSource != null) {
2007 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08002008 final int uid = wakeLock.mWorkSource.getUid(k);
Pavel Grafov28939982017-10-03 15:11:52 +01002009 if (userId == UserHandle.getUserId(uid)) {
2010 return true;
2011 }
2012 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00002013
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08002014 final List<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
Narayan Kamath2f916ed2017-12-29 13:02:15 +00002015 if (workChains != null) {
2016 for (int k = 0; k < workChains.size(); k++) {
2017 final int uid = workChains.get(k).getAttributionUid();
2018 if (userId == UserHandle.getUserId(uid)) {
2019 return true;
2020 }
2021 }
2022 }
Pavel Grafov28939982017-10-03 15:11:52 +01002023 }
2024 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
2025 }
2026
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07002027 void checkForLongWakeLocks() {
2028 synchronized (mLock) {
2029 final long now = SystemClock.uptimeMillis();
2030 mNotifyLongDispatched = now;
2031 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
2032 long nextCheckTime = Long.MAX_VALUE;
2033 final int numWakeLocks = mWakeLocks.size();
2034 for (int i = 0; i < numWakeLocks; i++) {
2035 final WakeLock wakeLock = mWakeLocks.get(i);
2036 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2037 == PowerManager.PARTIAL_WAKE_LOCK) {
2038 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
2039 if (wakeLock.mAcquireTime < when) {
2040 // This wake lock has exceeded the long acquire time, report!
2041 notifyWakeLockLongStartedLocked(wakeLock);
2042 } else {
2043 // This wake lock could still become a long one, at this time.
2044 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
2045 if (checkTime < nextCheckTime) {
2046 nextCheckTime = checkTime;
2047 }
2048 }
2049 }
2050 }
2051 }
2052 mNotifyLongScheduled = 0;
2053 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2054 if (nextCheckTime != Long.MAX_VALUE) {
2055 mNotifyLongNextCheck = nextCheckTime;
2056 enqueueNotifyLongMsgLocked(nextCheckTime);
2057 } else {
2058 mNotifyLongNextCheck = 0;
2059 }
2060 }
2061 }
2062
Jeff Brown96307042012-07-27 15:51:34 -07002063 /**
2064 * Updates the value of mUserActivitySummary to summarize the user requested
2065 * state of the system such as whether the screen should be bright or dim.
2066 * Note that user activity is ignored when the system is asleep.
2067 *
2068 * This function must have no other side-effects.
2069 */
2070 private void updateUserActivitySummaryLocked(long now, int dirty) {
2071 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07002072 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08002073 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002074 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2075
2076 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08002077 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002078 || mWakefulness == WAKEFULNESS_DREAMING
2079 || mWakefulness == WAKEFULNESS_DOZING) {
Robert Horvath5560f382019-07-10 10:46:38 +02002080 final long attentiveTimeout = getAttentiveTimeoutLocked();
2081 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
2082 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout,
2083 attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01002084 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002085 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002086 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002087
2088 mUserActivitySummary = 0;
2089 if (mLastUserActivityTime >= mLastWakeTime) {
2090 nextTimeout = mLastUserActivityTime
2091 + screenOffTimeout - screenDimDuration;
2092 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002093 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002094 } else {
2095 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2096 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002097 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002098 }
2099 }
2100 }
2101 if (mUserActivitySummary == 0
2102 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2103 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002104 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002105 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2106 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002107 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2108 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2109 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2110 }
Jeff Brown96307042012-07-27 15:51:34 -07002111 }
2112 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002113
Jeff Brown05af6ad2014-09-30 20:54:30 -07002114 if (mUserActivitySummary == 0) {
2115 if (sleepTimeout >= 0) {
2116 final long anyUserActivity = Math.max(mLastUserActivityTime,
2117 mLastUserActivityTimeNoChangeLights);
2118 if (anyUserActivity >= mLastWakeTime) {
2119 nextTimeout = anyUserActivity + sleepTimeout;
2120 if (now < nextTimeout) {
2121 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2122 }
2123 }
2124 } else {
2125 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2126 nextTimeout = -1;
2127 }
2128 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002129
2130 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002131 if ((mUserActivitySummary &
2132 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002133 // Device is being kept awake by recent user activity
2134 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2135 // Save when the next timeout would have occurred
2136 mOverriddenTimeout = nextTimeout;
2137 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002138 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002139 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2140 nextTimeout = -1;
2141 }
2142
Alex Salo9e242232019-05-14 19:27:17 -07002143 if ((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
2144 && (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) == 0) {
Lucas Dupin0a5d7972019-01-16 18:52:30 -08002145 nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout);
2146 }
2147
Pavel Grafov28939982017-10-03 15:11:52 +01002148 if (nextProfileTimeout > 0) {
2149 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2150 }
2151
Jeff Brown05af6ad2014-09-30 20:54:30 -07002152 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002153 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002154 }
2155 } else {
2156 mUserActivitySummary = 0;
2157 }
2158
2159 if (DEBUG_SPEW) {
2160 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002161 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002162 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2163 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2164 }
2165 }
2166 }
2167
Pavel Grafov28939982017-10-03 15:11:52 +01002168 private void scheduleUserInactivityTimeout(long timeMs) {
2169 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2170 msg.setAsynchronous(true);
2171 mHandler.sendMessageAtTime(msg, timeMs);
2172 }
2173
Robert Horvath5560f382019-07-10 10:46:38 +02002174 private void scheduleAttentiveTimeout(long timeMs) {
2175 final Message msg = mHandler.obtainMessage(MSG_ATTENTIVE_TIMEOUT);
2176 msg.setAsynchronous(true);
2177 mHandler.sendMessageAtTime(msg, timeMs);
2178 }
2179
Pavel Grafov28939982017-10-03 15:11:52 +01002180 /**
2181 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2182 */
2183 private long getNextProfileTimeoutLocked(long now) {
2184 long nextTimeout = -1;
2185 final int numProfiles = mProfilePowerState.size();
2186 for (int i = 0; i < numProfiles; i++) {
2187 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2188 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2189 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2190 nextTimeout = timeout;
2191 }
2192 }
2193 return nextTimeout;
2194 }
2195
Robert Horvath5560f382019-07-10 10:46:38 +02002196 private void updateAttentiveStateLocked(long now, int dirty) {
2197 long attentiveTimeout = getAttentiveTimeoutLocked();
2198 long goToSleepTime = mLastUserActivityTime + attentiveTimeout;
2199 long showWarningTime = goToSleepTime - mAttentiveWarningDurationConfig;
2200
2201 boolean warningDismissed = maybeHideInattentiveSleepWarningLocked(now, showWarningTime);
2202
2203 if (attentiveTimeout >= 0 && (warningDismissed
2204 || (dirty & (DIRTY_ATTENTIVE | DIRTY_STAY_ON | DIRTY_SCREEN_BRIGHTNESS_BOOST
2205 | DIRTY_PROXIMITY_POSITIVE | DIRTY_WAKEFULNESS | DIRTY_BOOT_COMPLETED
2206 | DIRTY_SETTINGS)) != 0)) {
2207 if (DEBUG_SPEW) {
2208 Slog.d(TAG, "Updating attentive state");
2209 }
2210
2211 mHandler.removeMessages(MSG_ATTENTIVE_TIMEOUT);
2212
2213 if (isBeingKeptFromShowingInattentiveSleepWarningLocked()) {
2214 return;
2215 }
2216
2217 long nextTimeout = -1;
2218
2219 if (now < showWarningTime) {
2220 nextTimeout = showWarningTime;
2221 } else if (now < goToSleepTime) {
2222 if (DEBUG) {
2223 long timeToSleep = goToSleepTime - now;
2224 Slog.d(TAG, "Going to sleep in " + timeToSleep
2225 + "ms if there is no user activity");
2226 }
2227 mInattentiveSleepWarningOverlayController.show();
2228 nextTimeout = goToSleepTime;
2229 } else {
2230 if (DEBUG && mWakefulness != WAKEFULNESS_ASLEEP) {
2231 Slog.i(TAG, "Going to sleep now due to long user inactivity");
2232 }
2233 }
2234
2235 if (nextTimeout >= 0) {
2236 scheduleAttentiveTimeout(nextTimeout);
2237 }
2238 }
2239 }
2240
2241 private boolean maybeHideInattentiveSleepWarningLocked(long now, long showWarningTime) {
2242 long attentiveTimeout = getAttentiveTimeoutLocked();
2243
Robert Horvath60e51fe2019-08-20 13:10:34 +02002244 if (!mInattentiveSleepWarningOverlayController.isShown()) {
2245 return false;
2246 }
2247
2248 if (mWakefulness != WAKEFULNESS_AWAKE) {
2249 mInattentiveSleepWarningOverlayController.dismiss(false);
2250 return true;
2251 } else if (attentiveTimeout < 0 || isBeingKeptFromShowingInattentiveSleepWarningLocked()
2252 || now < showWarningTime) {
2253 mInattentiveSleepWarningOverlayController.dismiss(true);
Robert Horvath5560f382019-07-10 10:46:38 +02002254 return true;
2255 }
2256
2257 return false;
2258 }
2259
2260 private boolean isAttentiveTimeoutExpired(long now) {
2261 long attentiveTimeout = getAttentiveTimeoutLocked();
2262 return attentiveTimeout >= 0 && now > mLastUserActivityTime + attentiveTimeout;
2263 }
2264
Jeff Brown96307042012-07-27 15:51:34 -07002265 /**
2266 * Called when a user activity timeout has occurred.
2267 * Simply indicates that something about user activity has changed so that the new
2268 * state can be recomputed when the power state is updated.
2269 *
2270 * This function must have no other side-effects besides setting the dirty
2271 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2272 */
2273 private void handleUserActivityTimeout() { // runs on handler thread
2274 synchronized (mLock) {
2275 if (DEBUG_SPEW) {
2276 Slog.d(TAG, "handleUserActivityTimeout");
2277 }
2278
2279 mDirty |= DIRTY_USER_ACTIVITY;
2280 updatePowerStateLocked();
2281 }
2282 }
2283
Robert Horvath5560f382019-07-10 10:46:38 +02002284 private void handleAttentiveTimeout() { // runs on handler thread
2285 synchronized (mLock) {
2286 if (DEBUG_SPEW) {
2287 Slog.d(TAG, "handleAttentiveTimeout");
2288 }
2289
2290 mDirty |= DIRTY_ATTENTIVE;
2291 updatePowerStateLocked();
2292 }
2293 }
2294
2295 private long getAttentiveTimeoutLocked() {
2296 long timeout = mAttentiveTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002297 if (timeout <= 0) {
2298 return -1;
2299 }
Robert Horvath5560f382019-07-10 10:46:38 +02002300
2301 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2302 }
2303
2304 private long getSleepTimeoutLocked(long attentiveTimeout) {
2305 long timeout = mSleepTimeoutSetting;
2306 if (timeout <= 0) {
2307 return -1;
2308 }
2309 if (attentiveTimeout >= 0) {
2310 timeout = Math.min(timeout, attentiveTimeout);
2311 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002312 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2313 }
2314
Robert Horvath5560f382019-07-10 10:46:38 +02002315 private long getScreenOffTimeoutLocked(long sleepTimeout, long attentiveTimeout) {
Pavel Grafov28939982017-10-03 15:11:52 +01002316 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002317 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2318 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2319 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002320 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002321 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002322 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002323 if (sleepTimeout >= 0) {
2324 timeout = Math.min(timeout, sleepTimeout);
2325 }
Robert Horvath5560f382019-07-10 10:46:38 +02002326 if (attentiveTimeout >= 0) {
2327 timeout = Math.min(timeout, attentiveTimeout);
2328 }
Jeff Brown27736f52014-05-20 17:17:10 -07002329 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002330 }
2331
Pavel Grafov28939982017-10-03 15:11:52 +01002332 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002333 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002334 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002335 }
2336
2337 /**
2338 * Updates the wakefulness of the device.
2339 *
Jeff Brown26875502014-01-30 21:47:47 -08002340 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002341 * based on the current wake locks and user activity state. It may modify mDirty
2342 * if the wakefulness changes.
2343 *
2344 * Returns true if the wakefulness changed and we need to restart power state calculation.
2345 */
2346 private boolean updateWakefulnessLocked(int dirty) {
2347 boolean changed = false;
2348 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002349 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
Robert Horvath5560f382019-07-10 10:46:38 +02002350 | DIRTY_DOCK_STATE | DIRTY_ATTENTIVE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002351 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2352 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002353 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002354 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002355 final long time = SystemClock.uptimeMillis();
Robert Horvath5560f382019-07-10 10:46:38 +02002356 if (isAttentiveTimeoutExpired(time)) {
2357 changed = goToSleepNoUpdateLocked(time, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
2358 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, Process.SYSTEM_UID);
2359 } else if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002360 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002361 } else {
2362 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002363 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002364 }
Jeff Brown96307042012-07-27 15:51:34 -07002365 }
2366 }
2367 return changed;
2368 }
2369
Jeff Brown645832d2012-10-03 14:57:03 -07002370 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002371 * Returns true if the device should automatically nap and start dreaming when the user
2372 * activity timeout has expired and it's bedtime.
2373 */
2374 private boolean shouldNapAtBedTimeLocked() {
2375 return mDreamsActivateOnSleepSetting
2376 || (mDreamsActivateOnDockSetting
2377 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2378 }
2379
2380 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002381 * Returns true if the device should go to sleep now.
2382 * Also used when exiting a dream to determine whether we should go back
2383 * to being fully awake or else go to sleep for good.
2384 */
Jeff Brown96307042012-07-27 15:51:34 -07002385 private boolean isItBedTimeYetLocked() {
Robert Horvath5560f382019-07-10 10:46:38 +02002386 if (!mBootCompleted) {
2387 return false;
2388 }
2389
2390 long now = SystemClock.uptimeMillis();
2391 if (isAttentiveTimeoutExpired(now)) {
2392 return !isBeingKeptFromInattentiveSleepLocked();
2393 } else {
2394 return !isBeingKeptAwakeLocked();
2395 }
Jeff Brown645832d2012-10-03 14:57:03 -07002396 }
2397
2398 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002399 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002400 * or the stay on while powered setting. We also keep the phone awake when
2401 * the proximity sensor returns a positive result so that the device does not
2402 * lock while in a phone call. This function only controls whether the device
2403 * will go to sleep or dream which is independent of whether it will be allowed
2404 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002405 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002406 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002407 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002408 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002409 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002410 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002411 | USER_ACTIVITY_SCREEN_DIM)) != 0
2412 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002413 }
2414
2415 /**
Robert Horvath5560f382019-07-10 10:46:38 +02002416 * Returns true if the device is prevented from going into inattentive sleep by the stay on
2417 * while powered setting. We also keep the device awake when the proximity sensor returns a
2418 * positive result so that the device does not lock while in a phone call. This function only
2419 * controls whether the device will go to sleep which is independent of whether it will be
2420 * allowed to suspend.
2421 */
2422 private boolean isBeingKeptFromInattentiveSleepLocked() {
2423 return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive
2424 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2425 | USER_ACTIVITY_SCREEN_DIM)) != 0;
2426 }
2427
2428 private boolean isBeingKeptFromShowingInattentiveSleepWarningLocked() {
2429 return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive || !mBootCompleted;
2430 }
2431
2432 /**
Jeff Brown96307042012-07-27 15:51:34 -07002433 * Determines whether to post a message to the sandman to update the dream state.
2434 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002435 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002436 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002437 | DIRTY_USER_ACTIVITY
Robert Horvath5560f382019-07-10 10:46:38 +02002438 | DIRTY_ATTENTIVE
Jeff Brown645832d2012-10-03 14:57:03 -07002439 | DIRTY_WAKE_LOCKS
2440 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002441 | DIRTY_SETTINGS
2442 | DIRTY_IS_POWERED
2443 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002444 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002445 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2446 if (mDisplayReady) {
2447 scheduleSandmanLocked();
2448 }
Jeff Brown96307042012-07-27 15:51:34 -07002449 }
2450 }
2451
2452 private void scheduleSandmanLocked() {
2453 if (!mSandmanScheduled) {
2454 mSandmanScheduled = true;
2455 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2456 msg.setAsynchronous(true);
2457 mHandler.sendMessage(msg);
2458 }
2459 }
2460
2461 /**
Jeff Brown26875502014-01-30 21:47:47 -08002462 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002463 *
2464 * We do this asynchronously because we must call out of the power manager to start
2465 * the dream and we don't want to hold our lock while doing so. There is a risk that
2466 * the device will wake or go to sleep in the meantime so we have to handle that case.
2467 */
2468 private void handleSandman() { // runs on handler thread
2469 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002470 final boolean startDreaming;
2471 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002472 synchronized (mLock) {
2473 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002474 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002475 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002476 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002477 mSandmanSummoned = false;
2478 } else {
2479 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002480 }
2481 }
2482
Jeff Brown96307042012-07-27 15:51:34 -07002483 // Start dreaming if needed.
2484 // We only control the dream on the handler thread, so we don't need to worry about
2485 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002486 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002487 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002488 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002489 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002490 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002491 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002492 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002493 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002494 } else {
2495 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002496 }
2497
Santos Cordon03044382019-09-19 16:59:01 +01002498 // At this point, we either attempted to start the dream or no attempt will be made,
2499 // so stop holding the display suspend blocker for Doze.
2500 mDozeStartInProgress = false;
2501
Jeff Brown96307042012-07-27 15:51:34 -07002502 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002503 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002504 // Remember the initial battery level when the dream started.
2505 if (startDreaming && isDreaming) {
2506 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2507 if (wakefulness == WAKEFULNESS_DOZING) {
2508 Slog.i(TAG, "Dozing...");
2509 } else {
2510 Slog.i(TAG, "Dreaming...");
2511 }
2512 }
2513
2514 // If preconditions changed, wait for the next iteration to determine
2515 // whether the dream should continue (or be restarted).
2516 if (mSandmanSummoned || mWakefulness != wakefulness) {
2517 return; // wait for next cycle
2518 }
2519
2520 // Determine whether the dream should continue.
Robert Horvath5560f382019-07-10 10:46:38 +02002521 long now = SystemClock.uptimeMillis();
Jeff Brown26875502014-01-30 21:47:47 -08002522 if (wakefulness == WAKEFULNESS_DREAMING) {
2523 if (isDreaming && canDreamLocked()) {
2524 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002525 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002526 - mDreamsBatteryLevelDrainCutoffConfig
2527 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002528 // If the user activity timeout expired and the battery appears
2529 // to be draining faster than it is charging then stop dreaming
2530 // and go to sleep.
2531 Slog.i(TAG, "Stopping dream because the battery appears to "
2532 + "be draining faster than it is charging. "
2533 + "Battery level when dream started: "
2534 + mBatteryLevelWhenDreamStarted + "%. "
2535 + "Battery level now: " + mBatteryLevel + "%.");
2536 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002537 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002538 }
Jeff Brown96307042012-07-27 15:51:34 -07002539 }
Jeff Brown26875502014-01-30 21:47:47 -08002540
2541 // Dream has ended or will be stopped. Update the power state.
2542 if (isItBedTimeYetLocked()) {
Robert Horvath5560f382019-07-10 10:46:38 +02002543 int flags = 0;
2544 if (isAttentiveTimeoutExpired(now)) {
2545 flags |= PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE;
2546 }
2547 goToSleepNoUpdateLocked(now, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, flags,
2548 Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002549 updatePowerStateLocked();
2550 } else {
Robert Horvath5560f382019-07-10 10:46:38 +02002551 wakeUpNoUpdateLocked(now,
Michael Wrighte3001042019-02-05 00:13:14 +00002552 PowerManager.WAKE_REASON_UNKNOWN,
2553 "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2554 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002555 updatePowerStateLocked();
2556 }
2557 } else if (wakefulness == WAKEFULNESS_DOZING) {
2558 if (isDreaming) {
2559 return; // continue dozing
2560 }
2561
2562 // Doze has ended or will be stopped. Update the power state.
Robert Horvath5560f382019-07-10 10:46:38 +02002563 reallyGoToSleepNoUpdateLocked(now, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002564 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002565 }
Jeff Brown96307042012-07-27 15:51:34 -07002566 }
2567
Jeff Brown26875502014-01-30 21:47:47 -08002568 // Stop dream.
2569 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002570 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002571 }
2572 }
2573
2574 /**
Jeff Brown26875502014-01-30 21:47:47 -08002575 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002576 */
2577 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002578 if (mWakefulness != WAKEFULNESS_DREAMING
2579 || !mDreamsSupportedConfig
2580 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002581 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002582 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002583 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2584 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002585 || !mBootCompleted) {
2586 return false;
2587 }
2588 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002589 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002590 return false;
2591 }
2592 if (!mIsPowered
2593 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2594 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2595 return false;
2596 }
2597 if (mIsPowered
2598 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2599 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2600 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002601 }
2602 }
Jeff Brown26875502014-01-30 21:47:47 -08002603 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002604 }
2605
Jeff Brown96307042012-07-27 15:51:34 -07002606 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002607 * Returns true if the device is allowed to doze in its current state.
2608 */
2609 private boolean canDozeLocked() {
2610 return mWakefulness == WAKEFULNESS_DOZING;
2611 }
2612
2613 /**
Jeff Brown96307042012-07-27 15:51:34 -07002614 * Updates the display power state asynchronously.
2615 * When the update is finished, mDisplayReady will be set to true. The display
2616 * controller posts a message to tell us when the actual display power state
2617 * has been updated so we come back here to double-check and finish up.
2618 *
2619 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002620 *
2621 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002622 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002623 private boolean updateDisplayPowerStateLocked(int dirty) {
2624 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002625 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2626 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002627 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2628 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002629 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002630
Jeff Browne333e672014-10-28 13:48:55 -07002631 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002632 final boolean autoBrightness;
2633 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002634 if (!mBootCompleted) {
2635 // Keep the brightness steady during boot. This requires the
2636 // bootloader brightness and the default brightness to be identical.
2637 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002638 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002639 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002640 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002641 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2642 } else {
2643 autoBrightness = (mScreenBrightnessModeSetting ==
2644 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2645 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002646 }
Jeff Browne333e672014-10-28 13:48:55 -07002647
2648 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002649 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002650 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002651 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002652 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002653
jackqdyulei92681e82017-02-28 11:26:28 -08002654 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2655
Jeff Brown970d4132014-07-19 11:33:47 -07002656 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2657 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002658 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2659 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002660 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2661 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2662 }
2663 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2664 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2665 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002666 }
Jeff Brown970d4132014-07-19 11:33:47 -07002667 mDisplayPowerRequest.dozeScreenBrightness =
2668 mDozeScreenBrightnessOverrideFromDreamManager;
2669 } else {
2670 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2671 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2672 }
2673
Jeff Brown131206b2014-04-08 17:27:14 -07002674 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002675 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002676 mRequestWaitForNegativeProximity = false;
2677
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002678 if ((dirty & DIRTY_QUIESCENT) != 0) {
2679 sQuiescent = false;
2680 }
Jeff Brown96307042012-07-27 15:51:34 -07002681 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002682 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002683 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002684 + ", mWakefulness=" + mWakefulness
2685 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2686 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002687 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002688 + ", screenBrightnessOverride=" + screenBrightnessOverride
2689 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002690 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002691 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002692 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002693 }
2694 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002695 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002696 }
2697
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002698 private void updateScreenBrightnessBoostLocked(int dirty) {
2699 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2700 if (mScreenBrightnessBoostInProgress) {
2701 final long now = SystemClock.uptimeMillis();
2702 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2703 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2704 final long boostTimeout = mLastScreenBrightnessBoostTime +
2705 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2706 if (boostTimeout > now) {
2707 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2708 msg.setAsynchronous(true);
2709 mHandler.sendMessageAtTime(msg, boostTimeout);
2710 return;
2711 }
Jeff Browne333e672014-10-28 13:48:55 -07002712 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002713 mScreenBrightnessBoostInProgress = false;
2714 userActivityNoUpdateLocked(now,
2715 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002716 }
Jeff Browne333e672014-10-28 13:48:55 -07002717 }
2718 }
2719
Santos Cordon3107d292016-09-20 15:50:35 -07002720 private boolean shouldBoostScreenBrightness() {
2721 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2722 }
2723
Jeff Brown96307042012-07-27 15:51:34 -07002724 private static boolean isValidBrightness(int value) {
2725 return value >= 0 && value <= 255;
2726 }
2727
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002728 @VisibleForTesting
2729 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002730 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002731 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002732 }
2733
Jeff Brown2175e9c2014-09-12 16:11:07 -07002734 if (mWakefulness == WAKEFULNESS_DOZING) {
2735 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2736 return DisplayPowerRequest.POLICY_DOZE;
2737 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002738 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002739 return DisplayPowerRequest.POLICY_OFF;
2740 }
2741 // Fall through and preserve the current screen policy if not configured to
2742 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002743 }
2744
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002745 // It is important that POLICY_VR check happens after the wakefulness checks above so
2746 // that VR-mode does not prevent displays from transitioning to the correct state when
2747 // dozing or sleeping.
2748 if (mIsVrModeEnabled) {
2749 return DisplayPowerRequest.POLICY_VR;
2750 }
2751
Jeff Brown96307042012-07-27 15:51:34 -07002752 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2753 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002754 || !mBootCompleted
2755 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002756 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002757 }
2758
Jeff Brown970d4132014-07-19 11:33:47 -07002759 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002760 }
2761
Jeff Brown131206b2014-04-08 17:27:14 -07002762 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2763 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002764 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002765
Jeff Brown96307042012-07-27 15:51:34 -07002766 @Override
2767 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002768 synchronized (mLock) {
2769 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2770 updatePowerStateLocked();
2771 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002772 }
2773
2774 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002775 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002776 synchronized (mLock) {
2777 mProximityPositive = true;
2778 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2779 updatePowerStateLocked();
2780 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002781 }
2782
2783 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002784 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002785 synchronized (mLock) {
2786 mProximityPositive = false;
2787 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2788 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2789 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2790 updatePowerStateLocked();
2791 }
Jeff Brown96307042012-07-27 15:51:34 -07002792 }
Jeff Brown131206b2014-04-08 17:27:14 -07002793
2794 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002795 public void onDisplayStateChange(int state) {
2796 // This method is only needed to support legacy display blanking behavior
2797 // where the display's power state is coupled to suspend or to the power HAL.
2798 // The order of operations matters here.
2799 synchronized (mLock) {
2800 if (mDisplayState != state) {
2801 mDisplayState = state;
2802 if (state == Display.STATE_OFF) {
2803 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2804 setHalInteractiveModeLocked(false);
2805 }
2806 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2807 setHalAutoSuspendModeLocked(true);
2808 }
2809 } else {
2810 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2811 setHalAutoSuspendModeLocked(false);
2812 }
2813 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2814 setHalInteractiveModeLocked(true);
2815 }
2816 }
2817 }
2818 }
2819 }
2820
2821 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002822 public void acquireSuspendBlocker() {
2823 mDisplaySuspendBlocker.acquire();
2824 }
2825
2826 @Override
2827 public void releaseSuspendBlocker() {
2828 mDisplaySuspendBlocker.release();
2829 }
2830
2831 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002832 public String toString() {
2833 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002834 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002835 }
2836 }
Jeff Brown96307042012-07-27 15:51:34 -07002837 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002838
Jeff Brown96307042012-07-27 15:51:34 -07002839 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002840 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002841 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002842
Jeff Brown96307042012-07-27 15:51:34 -07002843 /**
2844 * Updates the suspend blocker that keeps the CPU alive.
2845 *
2846 * This function must have no other side-effects.
2847 */
2848 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002849 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002850 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2851 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002852 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002853
2854 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002855 // FIXME We should consider just leaving auto-suspend enabled forever since
2856 // we already hold the necessary wakelocks.
2857 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2858 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002859 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002860
2861 // First acquire suspend blockers if needed.
2862 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2863 mWakeLockSuspendBlocker.acquire();
2864 mHoldingWakeLockSuspendBlocker = true;
2865 }
2866 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2867 mDisplaySuspendBlocker.acquire();
2868 mHoldingDisplaySuspendBlocker = true;
2869 }
2870
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002871 // Inform the power HAL about interactive mode.
2872 // Although we could set interactive strictly based on the wakefulness
2873 // as reported by isInteractive(), it is actually more desirable to track
2874 // the display policy state instead so that the interactive state observed
2875 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2876 // Refer to getDesiredScreenPolicyLocked() for details.
2877 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2878 // When becoming non-interactive, we want to defer sending this signal
2879 // until the display is actually ready so that all transitions have
2880 // completed. This is probably a good sign that things have gotten
2881 // too tangled over here...
2882 if (interactive || mDisplayReady) {
2883 setHalInteractiveModeLocked(interactive);
2884 }
2885 }
2886
Jeff Brown27f7a862012-12-12 15:43:31 -08002887 // Then release suspend blockers if needed.
2888 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2889 mWakeLockSuspendBlocker.release();
2890 mHoldingWakeLockSuspendBlocker = false;
2891 }
2892 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2893 mDisplaySuspendBlocker.release();
2894 mHoldingDisplaySuspendBlocker = false;
2895 }
Jeff Brown26875502014-01-30 21:47:47 -08002896
2897 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002898 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2899 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002900 }
Jeff Brown96307042012-07-27 15:51:34 -07002901 }
2902
Jeff Brownec083212013-09-11 20:45:25 -07002903 /**
2904 * Return true if we must keep a suspend blocker active on behalf of the display.
2905 * We do so if the screen is on or is in transition between states.
2906 */
Jeff Brown26875502014-01-30 21:47:47 -08002907 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002908 if (!mDisplayReady) {
2909 return true;
2910 }
Jeff Brown970d4132014-07-19 11:33:47 -07002911 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002912 // If we asked for the screen to be on but it is off due to the proximity
2913 // sensor then we may suspend but only if the configuration allows it.
2914 // On some hardware it may not be safe to suspend because the proximity
2915 // sensor may not be correctly configured as a wake-up source.
2916 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2917 || !mSuspendWhenScreenOffDueToProximityConfig) {
2918 return true;
2919 }
2920 }
Santos Cordond9701ab2019-08-01 18:33:20 +01002921
2922 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE
2923 && mDisplayPowerRequest.dozeScreenState == Display.STATE_ON) {
2924 // Although we are in DOZE and would normally allow the device to suspend,
2925 // the doze service has explicitly requested the display to remain in the ON
2926 // state which means we should hold the display suspend blocker.
2927 return true;
2928 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002929 if (mScreenBrightnessBoostInProgress) {
2930 return true;
2931 }
Santos Cordon03044382019-09-19 16:59:01 +01002932
2933 // When we transition to DOZING, we have to keep the display suspend blocker
2934 // up until the Doze service has a change to acquire the DOZE wakelock.
2935 // Here we wait for mWakefulnessChanging to become false since the wakefulness
2936 // transition to DOZING isn't considered "changed" until the doze wake lock is
2937 // acquired.
2938 if (mWakefulness == WAKEFULNESS_DOZING && mDozeStartInProgress) {
2939 return true;
2940 }
2941
Jeff Brown26875502014-01-30 21:47:47 -08002942 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002943 return false;
2944 }
2945
Jeff Brown037c33e2014-04-09 00:31:55 -07002946 private void setHalAutoSuspendModeLocked(boolean enable) {
2947 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002948 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002949 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002950 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002951 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002952 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2953 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002954 mNativeWrapper.nativeSetAutoSuspend(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002955 } finally {
2956 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2957 }
Jeff Brown26875502014-01-30 21:47:47 -08002958 }
2959 }
2960
Jeff Brown037c33e2014-04-09 00:31:55 -07002961 private void setHalInteractiveModeLocked(boolean enable) {
2962 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002963 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002964 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002965 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002966 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002967 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2968 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002969 mNativeWrapper.nativeSetInteractive(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002970 } finally {
2971 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2972 }
Jeff Brown26875502014-01-30 21:47:47 -08002973 }
2974 }
2975
Jeff Brown037c33e2014-04-09 00:31:55 -07002976 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002977 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002978 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002979 }
2980 }
2981
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002982 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002983 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002984 if (DEBUG) {
2985 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2986 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002987 if (mIsPowered) {
2988 return false;
2989 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002990
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002991 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002992
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002993 return true;
2994 }
2995 }
2996
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002997 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002998 synchronized (mLock) {
2999 return mDeviceIdleMode;
3000 }
3001 }
3002
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003003 boolean isLightDeviceIdleModeInternal() {
3004 synchronized (mLock) {
3005 return mLightDeviceIdleMode;
3006 }
3007 }
3008
Jeff Brown96307042012-07-27 15:51:34 -07003009 private void handleBatteryStateChangedLocked() {
3010 mDirty |= DIRTY_BATTERY_STATE;
3011 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003012 }
3013
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003014 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003015 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07003016 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07003017 if (RescueParty.isAttemptingFactoryReset()) {
3018 // If we're stuck in a really low-level reboot loop, and a
3019 // rescue party is trying to prompt the user for a factory data
3020 // reset, we must GET TO DA CHOPPA!
3021 PowerManagerService.lowLevelReboot(reason);
3022 } else {
3023 throw new IllegalStateException("Too early to call shutdown() or reboot()");
3024 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003025 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003026
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003027 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07003028 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003029 public void run() {
3030 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003031 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003032 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003033 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003034 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003035 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003036 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003037 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003038 }
San Mehat1e512792010-01-07 10:40:29 -08003039 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003040 };
Jeff Brown96307042012-07-27 15:51:34 -07003041
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003042 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00003043 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07003044 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00003045 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003046
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003047 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003048 if (wait) {
3049 synchronized (runnable) {
3050 while (true) {
3051 try {
3052 runnable.wait();
3053 } catch (InterruptedException e) {
3054 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003055 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003056 }
Doug Zongker50a21f42009-11-19 12:49:53 -08003057 }
3058 }
3059
Jeff Brown96307042012-07-27 15:51:34 -07003060 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08003061 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07003062 @Override
Jeff Brown96307042012-07-27 15:51:34 -07003063 public void run() {
3064 throw new RuntimeException(message);
3065 }
Dan Egnor60d87622009-12-16 16:32:58 -08003066 };
3067 try {
3068 t.start();
3069 t.join();
3070 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07003071 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08003072 }
3073 }
3074
jackqdyulei92681e82017-02-28 11:26:28 -08003075 @VisibleForTesting
3076 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
3077 PowerSaveState state = mBatterySaverPolicy.
Kweku Adams9f488e22019-01-14 16:25:08 -08003078 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
jackqdyulei92681e82017-02-28 11:26:28 -08003079 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
3080 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
3081 }
3082
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003083 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07003084 Settings.Global.putInt(mContext.getContentResolver(),
3085 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003086 }
3087
Pavel Grafov28939982017-10-03 15:11:52 +01003088 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
3089 if (userId < 0) {
3090 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
3091 return;
3092 }
Jeff Brown96307042012-07-27 15:51:34 -07003093 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01003094 // System-wide timeout
3095 if (userId == UserHandle.USER_SYSTEM) {
3096 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
3097 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
3098 mProfilePowerState.delete(userId);
3099 } else {
3100 final ProfilePowerState profile = mProfilePowerState.get(userId);
3101 if (profile != null) {
3102 profile.mScreenOffTimeout = timeMs;
3103 } else {
3104 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
3105 // We need to recalculate wake locks for the new profile state.
3106 mDirty |= DIRTY_WAKE_LOCKS;
3107 }
3108 }
Jeff Brown96307042012-07-27 15:51:34 -07003109 mDirty |= DIRTY_SETTINGS;
3110 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003111 }
3112 }
3113
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003114 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003115 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07003116 if (mDeviceIdleMode == enabled) {
3117 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003118 }
Felipe Lemeea014392016-09-06 13:59:54 -07003119 mDeviceIdleMode = enabled;
3120 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003121 }
Felipe Lemeea014392016-09-06 13:59:54 -07003122 if (enabled) {
3123 EventLogTags.writeDeviceIdleOnPhase("power");
3124 } else {
3125 EventLogTags.writeDeviceIdleOffPhase("power");
3126 }
3127 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003128 }
3129
3130 boolean setLightDeviceIdleModeInternal(boolean enabled) {
3131 synchronized (mLock) {
3132 if (mLightDeviceIdleMode != enabled) {
3133 mLightDeviceIdleMode = enabled;
3134 return true;
3135 }
3136 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003137 }
3138 }
3139
3140 void setDeviceIdleWhitelistInternal(int[] appids) {
3141 synchronized (mLock) {
3142 mDeviceIdleWhitelist = appids;
3143 if (mDeviceIdleMode) {
3144 updateWakeLockDisabledStatesLocked();
3145 }
3146 }
3147 }
3148
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003149 void setDeviceIdleTempWhitelistInternal(int[] appids) {
3150 synchronized (mLock) {
3151 mDeviceIdleTempWhitelist = appids;
3152 if (mDeviceIdleMode) {
3153 updateWakeLockDisabledStatesLocked();
3154 }
3155 }
3156 }
3157
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003158 void startUidChangesInternal() {
3159 synchronized (mLock) {
3160 mUidsChanging = true;
3161 }
3162 }
3163
3164 void finishUidChangesInternal() {
3165 synchronized (mLock) {
3166 mUidsChanging = false;
3167 if (mUidsChanged) {
3168 updateWakeLockDisabledStatesLocked();
3169 mUidsChanged = false;
3170 }
3171 }
3172 }
3173
3174 private void handleUidStateChangeLocked() {
3175 if (mUidsChanging) {
3176 mUidsChanged = true;
3177 } else {
3178 updateWakeLockDisabledStatesLocked();
3179 }
3180 }
3181
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003182 void updateUidProcStateInternal(int uid, int procState) {
3183 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003184 UidState state = mUidState.get(uid);
3185 if (state == null) {
3186 state = new UidState(uid);
3187 mUidState.put(uid, state);
3188 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07003189 final boolean oldShouldAllow = state.mProcState
3190 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003191 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07003192 if (state.mNumWakeLocks > 0) {
3193 if (mDeviceIdleMode) {
3194 handleUidStateChangeLocked();
3195 } else if (!state.mActive && oldShouldAllow !=
3196 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
3197 // If this uid is not active, but the process state has changed such
3198 // that we may still want to allow it to hold a wake lock, then take care of it.
3199 handleUidStateChangeLocked();
3200 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003201 }
3202 }
3203 }
3204
3205 void uidGoneInternal(int uid) {
3206 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003207 final int index = mUidState.indexOfKey(uid);
3208 if (index >= 0) {
3209 UidState state = mUidState.valueAt(index);
3210 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
3211 state.mActive = false;
3212 mUidState.removeAt(index);
3213 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
3214 handleUidStateChangeLocked();
3215 }
3216 }
3217 }
3218 }
3219
3220 void uidActiveInternal(int uid) {
3221 synchronized (mLock) {
3222 UidState state = mUidState.get(uid);
3223 if (state == null) {
3224 state = new UidState(uid);
3225 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3226 mUidState.put(uid, state);
3227 }
3228 state.mActive = true;
3229 if (state.mNumWakeLocks > 0) {
3230 handleUidStateChangeLocked();
3231 }
3232 }
3233 }
3234
3235 void uidIdleInternal(int uid) {
3236 synchronized (mLock) {
3237 UidState state = mUidState.get(uid);
3238 if (state != null) {
3239 state.mActive = false;
3240 if (state.mNumWakeLocks > 0) {
3241 handleUidStateChangeLocked();
3242 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003243 }
3244 }
3245 }
3246
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003247 private void updateWakeLockDisabledStatesLocked() {
3248 boolean changed = false;
3249 final int numWakeLocks = mWakeLocks.size();
3250 for (int i = 0; i < numWakeLocks; i++) {
3251 final WakeLock wakeLock = mWakeLocks.get(i);
3252 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003253 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003254 if (setWakeLockDisabledStateLocked(wakeLock)) {
3255 changed = true;
3256 if (wakeLock.mDisabled) {
3257 // This wake lock is no longer being respected.
3258 notifyWakeLockReleasedLocked(wakeLock);
3259 } else {
3260 notifyWakeLockAcquiredLocked(wakeLock);
3261 }
3262 }
3263 }
3264 }
3265 if (changed) {
3266 mDirty |= DIRTY_WAKE_LOCKS;
3267 updatePowerStateLocked();
3268 }
3269 }
3270
3271 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3272 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3273 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003274 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003275 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3276 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003277 // Cached inactive processes are never allowed to hold wake locks.
3278 if (mConstants.NO_CACHED_WAKE_LOCKS) {
Santos Cordon12f92eb2019-02-01 21:28:47 +00003279 disabled = mForceSuspendActive
3280 || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003281 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Santos Cordon12f92eb2019-02-01 21:28:47 +00003282 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003283 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003284 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003285 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003286 // for application uids that are not whitelisted.
3287 final UidState state = wakeLock.mUidState;
3288 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3289 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3290 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003291 state.mProcState >
3292 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003293 disabled = true;
3294 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003295 }
3296 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003297 if (wakeLock.mDisabled != disabled) {
3298 wakeLock.mDisabled = disabled;
3299 return true;
3300 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003301 }
3302 return false;
3303 }
3304
Jeff Brown96307042012-07-27 15:51:34 -07003305 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3306 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003307 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003309
Jeff Brown96307042012-07-27 15:51:34 -07003310 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003311 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003312 synchronized (mLock) {
3313 if (!mSystemReady) {
3314 return;
3315 }
3316 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003317 }
Jeff Brown96307042012-07-27 15:51:34 -07003318
3319 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003320 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003321 }
3322
Lucas Dupin16cfe452018-02-08 13:14:50 -08003323 private void setDozeAfterScreenOffInternal(boolean on) {
3324 synchronized (mLock) {
3325 mDozeAfterScreenOff = on;
3326 }
3327 }
3328
Jeff Browne333e672014-10-28 13:48:55 -07003329 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3330 synchronized (mLock) {
3331 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3332 || eventTime < mLastScreenBrightnessBoostTime) {
3333 return;
3334 }
3335
3336 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3337 mLastScreenBrightnessBoostTime = eventTime;
Kweku Adamsf94be8a2019-06-14 13:39:14 -07003338 mScreenBrightnessBoostInProgress = true;
Jeff Browne333e672014-10-28 13:48:55 -07003339 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3340
3341 userActivityNoUpdateLocked(eventTime,
3342 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3343 updatePowerStateLocked();
3344 }
3345 }
3346
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003347 private boolean isScreenBrightnessBoostedInternal() {
3348 synchronized (mLock) {
3349 return mScreenBrightnessBoostInProgress;
3350 }
3351 }
3352
Jeff Browne333e672014-10-28 13:48:55 -07003353 /**
3354 * Called when a screen brightness boost timeout has occurred.
3355 *
3356 * This function must have no other side-effects besides setting the dirty
3357 * bit and calling update power state.
3358 */
3359 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3360 synchronized (mLock) {
3361 if (DEBUG_SPEW) {
3362 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3363 }
3364
3365 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3366 updatePowerStateLocked();
3367 }
3368 }
3369
Jeff Brown96307042012-07-27 15:51:34 -07003370 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3371 synchronized (mLock) {
3372 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3373 mScreenBrightnessOverrideFromWindowManager = brightness;
3374 mDirty |= DIRTY_SETTINGS;
3375 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003376 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003377 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003378 }
3379
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003380 private void setUserInactiveOverrideFromWindowManagerInternal() {
3381 synchronized (mLock) {
3382 mUserInactiveOverrideFromWindowManager = true;
3383 mDirty |= DIRTY_USER_ACTIVITY;
3384 updatePowerStateLocked();
3385 }
3386 }
3387
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003388 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3389 synchronized (mLock) {
3390 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3391 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003392 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003393 mDirty |= DIRTY_SETTINGS;
3394 updatePowerStateLocked();
3395 }
3396 }
3397 }
3398
Jeff Brown970d4132014-07-19 11:33:47 -07003399 private void setDozeOverrideFromDreamManagerInternal(
3400 int screenState, int screenBrightness) {
3401 synchronized (mLock) {
3402 if (mDozeScreenStateOverrideFromDreamManager != screenState
3403 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3404 mDozeScreenStateOverrideFromDreamManager = screenState;
3405 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3406 mDirty |= DIRTY_SETTINGS;
3407 updatePowerStateLocked();
3408 }
3409 }
3410 }
3411
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003412 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3413 synchronized (mLock) {
3414 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3415 mDrawWakeLockOverrideFromSidekick = keepState;
3416 mDirty |= DIRTY_SETTINGS;
3417 updatePowerStateLocked();
3418 }
3419 }
3420 }
3421
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003422 @VisibleForTesting
3423 void setVrModeEnabled(boolean enabled) {
3424 mIsVrModeEnabled = enabled;
3425 }
3426
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003427 private void powerHintInternal(int hintId, int data) {
3428 // Maybe filter the event.
3429 switch (hintId) {
3430 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3431 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3432 return;
3433 }
3434 break;
3435 }
3436
Santos Cordon64a6e612018-08-22 19:27:04 +01003437 mNativeWrapper.nativeSendPowerHint(hintId, data);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003438 }
3439
Alex Kershaw2418ea92018-10-19 17:17:49 +01003440 @VisibleForTesting
3441 boolean wasDeviceIdleForInternal(long ms) {
3442 synchronized (mLock) {
3443 return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3444 }
3445 }
3446
3447 @VisibleForTesting
3448 void onUserActivity() {
3449 synchronized (mLock) {
3450 mLastUserActivityTime = SystemClock.uptimeMillis();
3451 }
3452 }
3453
Santos Cordon12f92eb2019-02-01 21:28:47 +00003454 private boolean forceSuspendInternal(int uid) {
3455 try {
3456 synchronized (mLock) {
3457 mForceSuspendActive = true;
3458 // Place the system in an non-interactive state
3459 goToSleepInternal(SystemClock.uptimeMillis(),
3460 PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3461 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3462
3463 // Disable all the partial wake locks as well
3464 updateWakeLockDisabledStatesLocked();
3465 }
3466
3467 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3468 boolean success = mNativeWrapper.nativeForceSuspend();
3469 if (!success) {
3470 Slog.i(TAG, "Force-Suspending failed in native.");
3471 }
3472 return success;
3473 } finally {
3474 synchronized (mLock) {
3475 mForceSuspendActive = false;
3476 // Re-enable wake locks once again.
3477 updateWakeLockDisabledStatesLocked();
3478 }
3479 }
3480 }
3481
Jeff Brown96307042012-07-27 15:51:34 -07003482 /**
3483 * Low-level function turn the device off immediately, without trying
3484 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003485 *
3486 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003487 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003488 public static void lowLevelShutdown(String reason) {
3489 if (reason == null) {
3490 reason = "";
3491 }
3492 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003493 }
3494
3495 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003496 * Low-level function to reboot the device. On success, this
3497 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003498 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003499 *
3500 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003501 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003502 public static void lowLevelReboot(String reason) {
3503 if (reason == null) {
3504 reason = "";
3505 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003506
3507 // If the reason is "quiescent", it means that the boot process should proceed
3508 // without turning on the screen/lights.
3509 // The "quiescent" property is sticky, meaning that any number
3510 // of subsequent reboots should honor the property until it is reset.
3511 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3512 sQuiescent = true;
3513 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003514 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3515 sQuiescent = true;
3516 reason = reason.substring(0,
3517 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3518 }
3519
3520 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3521 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3522 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003523 }
3524
3525 if (sQuiescent) {
3526 // Pass the optional "quiescent" argument to the bootloader to let it know
3527 // that it should not turn the screen/lights on.
3528 reason = reason + ",quiescent";
3529 }
3530
3531 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003532 try {
Tao Bao90237f72015-05-21 16:25:19 -07003533 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003534 } catch (InterruptedException e) {
3535 Thread.currentThread().interrupt();
3536 }
Tao Bao90237f72015-05-21 16:25:19 -07003537 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003538 }
3539
3540 @Override // Watchdog.Monitor implementation
3541 public void monitor() {
3542 // Grab and release lock for watchdog monitor to detect deadlocks.
3543 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003544 }
Jeff Brown96307042012-07-27 15:51:34 -07003545 }
3546
Jeff Brown6f357d32014-01-15 20:40:55 -08003547 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003548 pw.println("POWER MANAGER (dumpsys power)\n");
3549
Jeff Brown3b971592013-01-09 18:46:37 -08003550 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003551 synchronized (mLock) {
3552 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003553 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003554 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003555 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3556 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003557 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003558 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003559 pw.println(" mBatteryLevel=" + mBatteryLevel);
3560 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003561 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003562 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003563 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003564 pw.println(" mBootCompleted=" + mBootCompleted);
3565 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003566 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3567 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003568 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003569 pw.print(" mNotifyLongScheduled=");
3570 if (mNotifyLongScheduled == 0) {
3571 pw.print("(none)");
3572 } else {
3573 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3574 }
3575 pw.println();
3576 pw.print(" mNotifyLongDispatched=");
3577 if (mNotifyLongDispatched == 0) {
3578 pw.print("(none)");
3579 } else {
3580 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3581 }
3582 pw.println();
3583 pw.print(" mNotifyLongNextCheck=");
3584 if (mNotifyLongNextCheck == 0) {
3585 pw.print("(none)");
3586 } else {
3587 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3588 }
3589 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003590 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3591 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3592 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003593 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003594 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003595 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003596 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3597 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003598 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003599 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3600 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Calin Tatarua3805722018-08-09 16:41:28 +02003601 pw.println(" mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
Jeff Brown96307042012-07-27 15:51:34 -07003602 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3603 pw.println(" mLastUserActivityTimeNoChangeLights="
3604 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003605 pw.println(" mLastInteractivePowerHintTime="
3606 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003607 pw.println(" mLastScreenBrightnessBoostTime="
3608 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3609 pw.println(" mScreenBrightnessBoostInProgress="
3610 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003611 pw.println(" mDisplayReady=" + mDisplayReady);
3612 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003613 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003614
3615 pw.println();
3616 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003617 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3618 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3619 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3620 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003621 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3622 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003623 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3624 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3625 pw.println(" mTheaterModeEnabled="
3626 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003627 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3628 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003629 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003630 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3631 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3632 + mDreamsActivatedOnSleepByDefaultConfig);
3633 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3634 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003635 pw.println(" mDreamsEnabledOnBatteryConfig="
3636 + mDreamsEnabledOnBatteryConfig);
3637 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3638 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3639 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3640 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3641 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3642 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003643 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003644 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003645 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003646 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003647 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3648 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3649 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Robert Horvath5560f382019-07-10 10:46:38 +02003650 pw.println(" mAttentiveTimeoutConfig=" + mAttentiveTimeoutConfig);
3651 pw.println(" mAttentiveTimeoutSetting=" + mAttentiveTimeoutSetting);
3652 pw.println(" mAttentiveWarningDurationConfig=" + mAttentiveWarningDurationConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003653 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003654 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003655 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3656 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3657 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3658 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3659 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3660 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3661 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3662 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003663 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3664 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003665 pw.println(" mUserInactiveOverrideFromWindowManager="
3666 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003667 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3668 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003669 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003670 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3671 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003672 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3673 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3674 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003675 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003676 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003677 pw.println(" mForegroundProfile=" + mForegroundProfile);
Beverly478722e2019-10-14 11:16:57 -04003678 pw.println(" mUserId=" + mUserId);
Jeff Brown96307042012-07-27 15:51:34 -07003679
Robert Horvath5560f382019-07-10 10:46:38 +02003680 final long attentiveTimeout = getAttentiveTimeoutLocked();
3681 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
3682 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01003683 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003684 pw.println();
Robert Horvath5560f382019-07-10 10:46:38 +02003685 pw.println("Attentive timeout: " + attentiveTimeout + " ms");
Jeff Brown05af6ad2014-09-30 20:54:30 -07003686 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003687 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3688 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3689
Jeff Brown96307042012-07-27 15:51:34 -07003690 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003691 pw.print("UID states (changing=");
3692 pw.print(mUidsChanging);
3693 pw.print(" changed=");
3694 pw.print(mUidsChanged);
3695 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003696 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003697 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003698 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003699 pw.print(": ");
3700 if (state.mActive) pw.print(" ACTIVE ");
3701 else pw.print("INACTIVE ");
3702 pw.print(" count=");
3703 pw.print(state.mNumWakeLocks);
3704 pw.print(" state=");
3705 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003706 }
3707
3708 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003709 pw.println("Looper state:");
3710 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3711
3712 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003713 pw.println("Wake Locks: size=" + mWakeLocks.size());
3714 for (WakeLock wl : mWakeLocks) {
3715 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003716 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003717
Jeff Brown96307042012-07-27 15:51:34 -07003718 pw.println();
3719 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3720 for (SuspendBlocker sb : mSuspendBlockers) {
3721 pw.println(" " + sb);
3722 }
3723
Jeff Brownc38c9be2012-10-04 13:16:19 -07003724 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003725 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003726
jackqdyulei455e90a2017-02-09 15:29:16 -08003727 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003728 mBatterySaverStateMachine.dump(pw);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08003729 mAttentionDetector.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003730
Pavel Grafov28939982017-10-03 15:11:52 +01003731 pw.println();
3732 final int numProfiles = mProfilePowerState.size();
3733 pw.println("Profile power states: size=" + numProfiles);
3734 for (int i = 0; i < numProfiles; i++) {
3735 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3736 pw.print(" mUserId=");
3737 pw.print(profile.mUserId);
3738 pw.print(" mScreenOffTimeout=");
3739 pw.print(profile.mScreenOffTimeout);
3740 pw.print(" mWakeLockSummary=");
3741 pw.print(profile.mWakeLockSummary);
3742 pw.print(" mLastUserActivityTime=");
3743 pw.print(profile.mLastUserActivityTime);
3744 pw.print(" mLockingNotified=");
3745 pw.println(profile.mLockingNotified);
3746 }
3747
Jeff Brown3b971592013-01-09 18:46:37 -08003748 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003749 }
3750
Jeff Brown3b971592013-01-09 18:46:37 -08003751 if (wcd != null) {
3752 wcd.dump(pw);
3753 }
Jeff Brown96307042012-07-27 15:51:34 -07003754 }
3755
Netta P958d0a52017-02-07 11:20:55 -08003756 private void dumpProto(FileDescriptor fd) {
3757 final WirelessChargerDetector wcd;
3758 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3759
3760 synchronized (mLock) {
3761 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003762 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3763 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3764 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3765 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3766 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3767 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003768 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003769 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003770 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003771 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3772 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3773 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3774 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3775 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003776 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003777 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003778 mHalAutoSuspendModeEnabled);
3779 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003780 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003781 mHalInteractiveModeEnabled);
3782
Kweku Adamse6b00c22017-10-23 16:46:45 -07003783 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003784 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003785 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003786 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3787 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003788 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003789 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3790 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003791 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003792 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3793 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003794 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003795 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3796 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003797 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003798 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3799 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003800 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003801 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3802 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003803 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003804 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3805 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003806 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003807 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3808 proto.end(activeWakeLocksToken);
3809
Kweku Adamse6b00c22017-10-23 16:46:45 -07003810 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3811 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3812 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003813
Kweku Adamse6b00c22017-10-23 16:46:45 -07003814 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003815 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003816 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003817 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3818 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003819 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003820 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3821 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003822 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003823 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3824 proto.end(userActivityToken);
3825
3826 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003827 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003828 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003829 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3830 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003831 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3832 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3833 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003834
3835 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003836 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003837 }
3838 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003839 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003840 }
3841
Kweku Adamse6b00c22017-10-23 16:46:45 -07003842 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3843 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3844 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003845 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003846 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003847 mLastUserActivityTimeNoChangeLights);
3848 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003849 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003850 mLastInteractivePowerHintTime);
3851 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003852 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003853 mLastScreenBrightnessBoostTime);
3854 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003855 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003856 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003857 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003858 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003859 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003860 mHoldingWakeLockSuspendBlocker);
3861 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003862 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003863 mHoldingDisplaySuspendBlocker);
3864
3865 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003866 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003867 proto.write(
3868 PowerServiceSettingsAndConfigurationDumpProto
3869 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3870 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3871 proto.write(
3872 PowerServiceSettingsAndConfigurationDumpProto
3873 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3874 mDecoupleHalInteractiveModeFromDisplayConfig);
3875 proto.write(
3876 PowerServiceSettingsAndConfigurationDumpProto
3877 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3878 mWakeUpWhenPluggedOrUnpluggedConfig);
3879 proto.write(
3880 PowerServiceSettingsAndConfigurationDumpProto
3881 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3882 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3883 proto.write(
3884 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3885 mTheaterModeEnabled);
3886 proto.write(
3887 PowerServiceSettingsAndConfigurationDumpProto
3888 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3889 mSuspendWhenScreenOffDueToProximityConfig);
3890 proto.write(
3891 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3892 mDreamsSupportedConfig);
3893 proto.write(
3894 PowerServiceSettingsAndConfigurationDumpProto
3895 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3896 mDreamsEnabledByDefaultConfig);
3897 proto.write(
3898 PowerServiceSettingsAndConfigurationDumpProto
3899 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3900 mDreamsActivatedOnSleepByDefaultConfig);
3901 proto.write(
3902 PowerServiceSettingsAndConfigurationDumpProto
3903 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3904 mDreamsActivatedOnDockByDefaultConfig);
3905 proto.write(
3906 PowerServiceSettingsAndConfigurationDumpProto
3907 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3908 mDreamsEnabledOnBatteryConfig);
3909 proto.write(
3910 PowerServiceSettingsAndConfigurationDumpProto
3911 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3912 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3913 proto.write(
3914 PowerServiceSettingsAndConfigurationDumpProto
3915 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3916 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3917 proto.write(
3918 PowerServiceSettingsAndConfigurationDumpProto
3919 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3920 mDreamsBatteryLevelDrainCutoffConfig);
3921 proto.write(
3922 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3923 mDreamsEnabledSetting);
3924 proto.write(
3925 PowerServiceSettingsAndConfigurationDumpProto
3926 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3927 mDreamsActivateOnSleepSetting);
3928 proto.write(
3929 PowerServiceSettingsAndConfigurationDumpProto
3930 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3931 mDreamsActivateOnDockSetting);
3932 proto.write(
3933 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08003934 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08003935 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003936 PowerServiceSettingsAndConfigurationDumpProto
3937 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3938 mMinimumScreenOffTimeoutConfig);
3939 proto.write(
3940 PowerServiceSettingsAndConfigurationDumpProto
3941 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3942 mMaximumScreenDimDurationConfig);
3943 proto.write(
3944 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3945 mMaximumScreenDimRatioConfig);
3946 proto.write(
3947 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3948 mScreenOffTimeoutSetting);
3949 proto.write(
3950 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3951 mSleepTimeoutSetting);
3952 proto.write(
Robert Horvath5560f382019-07-10 10:46:38 +02003953 PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_SETTING_MS,
3954 mAttentiveTimeoutSetting);
3955 proto.write(
3956 PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_CONFIG_MS,
3957 mAttentiveTimeoutConfig);
3958 proto.write(
3959 PowerServiceSettingsAndConfigurationDumpProto
3960 .ATTENTIVE_WARNING_DURATION_CONFIG_MS,
3961 mAttentiveWarningDurationConfig);
3962 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003963 PowerServiceSettingsAndConfigurationDumpProto
3964 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003965 // Clamp to int32
3966 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003967 proto.write(
3968 PowerServiceSettingsAndConfigurationDumpProto
3969 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3970 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3971
3972 final long stayOnWhilePluggedInToken =
3973 proto.start(
3974 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3975 proto.write(
3976 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3977 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3978 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3979 proto.write(
3980 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3981 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3982 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3983 proto.write(
3984 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3985 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3986 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3987 != 0));
3988 proto.end(stayOnWhilePluggedInToken);
3989
3990 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003991 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3992 mScreenBrightnessModeSetting);
3993 proto.write(
3994 PowerServiceSettingsAndConfigurationDumpProto
3995 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3996 mScreenBrightnessOverrideFromWindowManager);
3997 proto.write(
3998 PowerServiceSettingsAndConfigurationDumpProto
3999 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
4000 mUserActivityTimeoutOverrideFromWindowManager);
4001 proto.write(
4002 PowerServiceSettingsAndConfigurationDumpProto
4003 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
4004 mUserInactiveOverrideFromWindowManager);
4005 proto.write(
4006 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08004007 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
4008 mDozeScreenStateOverrideFromDreamManager);
4009 proto.write(
4010 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004011 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
4012 mDrawWakeLockOverrideFromSidekick);
4013 proto.write(
4014 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08004015 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
4016 mDozeScreenBrightnessOverrideFromDreamManager);
4017
4018 final long screenBrightnessSettingLimitsToken =
4019 proto.start(
4020 PowerServiceSettingsAndConfigurationDumpProto
4021 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
4022 proto.write(
4023 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4024 .SETTING_MINIMUM,
4025 mScreenBrightnessSettingMinimum);
4026 proto.write(
4027 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4028 .SETTING_MAXIMUM,
4029 mScreenBrightnessSettingMaximum);
4030 proto.write(
4031 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4032 .SETTING_DEFAULT,
4033 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08004034 proto.end(screenBrightnessSettingLimitsToken);
4035
4036 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08004037 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
4038 mDoubleTapWakeEnabled);
4039 proto.write(
4040 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
4041 mIsVrModeEnabled);
4042 proto.end(settingsAndConfigurationToken);
4043
Robert Horvath5560f382019-07-10 10:46:38 +02004044 final long attentiveTimeout = getAttentiveTimeoutLocked();
4045 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
4046 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01004047 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Robert Horvath5560f382019-07-10 10:46:38 +02004048 proto.write(PowerManagerServiceDumpProto.ATTENTIVE_TIMEOUT_MS, attentiveTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07004049 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
4050 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
4051 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
4052 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
4053 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08004054
4055 for (int i = 0; i < mUidState.size(); i++) {
4056 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07004057 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08004058 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07004059 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
4060 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
4061 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
4062 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08004063 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
4064 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08004065 proto.end(uIDToken);
4066 }
4067
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004068 mBatterySaverStateMachine.dumpProto(proto,
4069 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
4070
Kweku Adamse6b00c22017-10-23 16:46:45 -07004071 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08004072
4073 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004074 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08004075 }
4076
4077 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004078 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08004079 }
4080 wcd = mWirelessChargerDetector;
4081 }
4082
4083 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004084 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08004085 }
4086 proto.flush();
4087 }
4088
Daichi Hirono82ab9802016-03-02 13:23:29 +09004089 private void incrementBootCount() {
4090 synchronized (mLock) {
4091 int count;
4092 try {
4093 count = Settings.Global.getInt(
4094 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
4095 } catch (SettingNotFoundException e) {
4096 count = 0;
4097 }
4098 Settings.Global.putInt(
4099 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
4100 }
4101 }
4102
Jeff Brown96307042012-07-27 15:51:34 -07004103 private static WorkSource copyWorkSource(WorkSource workSource) {
4104 return workSource != null ? new WorkSource(workSource) : null;
4105 }
4106
Santos Cordon9b510a22018-08-24 16:42:54 +01004107 @VisibleForTesting
4108 final class BatteryReceiver extends BroadcastReceiver {
Jeff Brown96307042012-07-27 15:51:34 -07004109 @Override
4110 public void onReceive(Context context, Intent intent) {
4111 synchronized (mLock) {
4112 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05004113 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05004114 }
4115 }
4116
John Spurlockf4f6b4c2012-08-25 12:08:03 -04004117 private final class DreamReceiver extends BroadcastReceiver {
4118 @Override
4119 public void onReceive(Context context, Intent intent) {
4120 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07004121 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04004122 }
4123 }
4124 }
4125
Santos Cordon9b510a22018-08-24 16:42:54 +01004126 @VisibleForTesting
4127 final class UserSwitchedReceiver extends BroadcastReceiver {
Jeff Brownd4935962012-09-25 13:27:20 -07004128 @Override
4129 public void onReceive(Context context, Intent intent) {
4130 synchronized (mLock) {
4131 handleSettingsChangedLocked();
4132 }
4133 }
4134 }
4135
Jeff Brownec6aa592012-10-17 20:30:25 -07004136 private final class DockReceiver extends BroadcastReceiver {
4137 @Override
4138 public void onReceive(Context context, Intent intent) {
4139 synchronized (mLock) {
4140 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4141 Intent.EXTRA_DOCK_STATE_UNDOCKED);
4142 if (mDockState != dockState) {
4143 mDockState = dockState;
4144 mDirty |= DIRTY_DOCK_STATE;
4145 updatePowerStateLocked();
4146 }
4147 }
4148 }
4149 }
4150
Jeff Brown96307042012-07-27 15:51:34 -07004151 private final class SettingsObserver extends ContentObserver {
4152 public SettingsObserver(Handler handler) {
4153 super(handler);
4154 }
4155
4156 @Override
4157 public void onChange(boolean selfChange, Uri uri) {
4158 synchronized (mLock) {
4159 handleSettingsChangedLocked();
4160 }
4161 }
4162 }
4163
Ruben Brunkc7be3be2016-04-01 17:07:51 -07004164 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07004165 @Override
4166 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07004167 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07004168
4169 synchronized (mLock) {
4170 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07004171 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07004172 mDirty |= DIRTY_VR_MODE_CHANGED;
4173 updatePowerStateLocked();
4174 }
4175 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07004176 }
4177 };
4178
Jeff Brown96307042012-07-27 15:51:34 -07004179 /**
4180 * Handler for asynchronous operations performed by the power manager.
4181 */
4182 private final class PowerManagerHandler extends Handler {
4183 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07004184 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07004185 }
4186
4187 @Override
4188 public void handleMessage(Message msg) {
4189 switch (msg.what) {
4190 case MSG_USER_ACTIVITY_TIMEOUT:
4191 handleUserActivityTimeout();
4192 break;
4193 case MSG_SANDMAN:
4194 handleSandman();
4195 break;
Jeff Browne333e672014-10-28 13:48:55 -07004196 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
4197 handleScreenBrightnessBoostTimeout();
4198 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004199 case MSG_CHECK_FOR_LONG_WAKELOCKS:
4200 checkForLongWakeLocks();
4201 break;
Robert Horvath5560f382019-07-10 10:46:38 +02004202 case MSG_ATTENTIVE_TIMEOUT:
4203 handleAttentiveTimeout();
4204 break;
Jeff Brown96307042012-07-27 15:51:34 -07004205 }
4206 }
4207 }
4208
4209 /**
4210 * Represents a wake lock that has been acquired by an application.
4211 */
4212 private final class WakeLock implements IBinder.DeathRecipient {
4213 public final IBinder mLock;
4214 public int mFlags;
4215 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004216 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07004217 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004218 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004219 public final int mOwnerUid;
4220 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004221 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004222 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07004223 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004224 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004225 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07004226
Dianne Hackborn713df152013-05-17 11:27:57 -07004227 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004228 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
4229 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07004230 mLock = lock;
4231 mFlags = flags;
4232 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004233 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07004234 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004235 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004236 mOwnerUid = ownerUid;
4237 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004238 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07004239 }
4240
4241 @Override
4242 public void binderDied() {
4243 PowerManagerService.this.handleWakeLockDeath(this);
4244 }
4245
4246 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4247 int ownerUid, int ownerPid) {
4248 return mFlags == flags
4249 && mTag.equals(tag)
4250 && hasSameWorkSource(workSource)
4251 && mOwnerUid == ownerUid
4252 && mOwnerPid == ownerPid;
4253 }
4254
Dianne Hackborn713df152013-05-17 11:27:57 -07004255 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004256 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07004257 if (!mPackageName.equals(packageName)) {
4258 throw new IllegalStateException("Existing wake lock package name changed: "
4259 + mPackageName + " to " + packageName);
4260 }
4261 if (mOwnerUid != ownerUid) {
4262 throw new IllegalStateException("Existing wake lock uid changed: "
4263 + mOwnerUid + " to " + ownerUid);
4264 }
4265 if (mOwnerPid != ownerPid) {
4266 throw new IllegalStateException("Existing wake lock pid changed: "
4267 + mOwnerPid + " to " + ownerPid);
4268 }
Jeff Brown96307042012-07-27 15:51:34 -07004269 mFlags = flags;
4270 mTag = tag;
4271 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004272 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004273 }
4274
4275 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00004276 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07004277 }
4278
4279 public void updateWorkSource(WorkSource workSource) {
4280 mWorkSource = copyWorkSource(workSource);
4281 }
4282
4283 @Override
4284 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004285 StringBuilder sb = new StringBuilder();
4286 sb.append(getLockLevelString());
4287 sb.append(" '");
4288 sb.append(mTag);
4289 sb.append("'");
4290 sb.append(getLockFlagsString());
4291 if (mDisabled) {
4292 sb.append(" DISABLED");
4293 }
4294 if (mNotifiedAcquired) {
4295 sb.append(" ACQ=");
4296 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4297 }
4298 if (mNotifiedLong) {
4299 sb.append(" LONG");
4300 }
4301 sb.append(" (uid=");
4302 sb.append(mOwnerUid);
4303 if (mOwnerPid != 0) {
4304 sb.append(" pid=");
4305 sb.append(mOwnerPid);
4306 }
4307 if (mWorkSource != null) {
4308 sb.append(" ws=");
4309 sb.append(mWorkSource);
4310 }
4311 sb.append(")");
4312 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004313 }
4314
Netta P958d0a52017-02-07 11:20:55 -08004315 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4316 final long wakeLockToken = proto.start(fieldId);
4317 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4318 proto.write(WakeLockProto.TAG, mTag);
4319
4320 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4321 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4322 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4323 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4324 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4325 proto.end(wakeLockFlagsToken);
4326
4327 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4328 if (mNotifiedAcquired) {
4329 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4330 }
4331 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4332 proto.write(WakeLockProto.UID, mOwnerUid);
4333 proto.write(WakeLockProto.PID, mOwnerPid);
4334
4335 if (mWorkSource != null) {
4336 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4337 }
4338 proto.end(wakeLockToken);
4339 }
4340
Jeff Brown26875502014-01-30 21:47:47 -08004341 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004342 private String getLockLevelString() {
4343 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4344 case PowerManager.FULL_WAKE_LOCK:
4345 return "FULL_WAKE_LOCK ";
4346 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4347 return "SCREEN_BRIGHT_WAKE_LOCK ";
4348 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4349 return "SCREEN_DIM_WAKE_LOCK ";
4350 case PowerManager.PARTIAL_WAKE_LOCK:
4351 return "PARTIAL_WAKE_LOCK ";
4352 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4353 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004354 case PowerManager.DOZE_WAKE_LOCK:
4355 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004356 case PowerManager.DRAW_WAKE_LOCK:
4357 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004358 default:
4359 return "??? ";
4360 }
4361 }
4362
4363 private String getLockFlagsString() {
4364 String result = "";
4365 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4366 result += " ACQUIRE_CAUSES_WAKEUP";
4367 }
4368 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4369 result += " ON_AFTER_RELEASE";
4370 }
4371 return result;
4372 }
4373 }
4374
4375 private final class SuspendBlockerImpl implements SuspendBlocker {
4376 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004377 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004378 private int mReferenceCount;
4379
4380 public SuspendBlockerImpl(String name) {
4381 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004382 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004383 }
4384
4385 @Override
4386 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004387 try {
Jeff Brown96307042012-07-27 15:51:34 -07004388 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004389 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004390 + "\" was finalized without being released!");
4391 mReferenceCount = 0;
Santos Cordon64a6e612018-08-22 19:27:04 +01004392 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004393 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004394 }
4395 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004396 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004397 }
4398 }
4399
Craig Mautner75fc9de2012-06-18 16:53:27 -07004400 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004401 public void acquire() {
4402 synchronized (this) {
4403 mReferenceCount += 1;
4404 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004405 if (DEBUG_SPEW) {
4406 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4407 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004408 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +01004409 mNativeWrapper.nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004410 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004411 }
4412 }
4413
Craig Mautner75fc9de2012-06-18 16:53:27 -07004414 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004415 public void release() {
4416 synchronized (this) {
4417 mReferenceCount -= 1;
4418 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004419 if (DEBUG_SPEW) {
4420 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4421 }
Santos Cordon64a6e612018-08-22 19:27:04 +01004422 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004423 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004424 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004425 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004426 + "\" was released without being acquired!", new Throwable());
4427 mReferenceCount = 0;
4428 }
4429 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004430 }
Jeff Brown96307042012-07-27 15:51:34 -07004431
4432 @Override
4433 public String toString() {
4434 synchronized (this) {
4435 return mName + ": ref count=" + mReferenceCount;
4436 }
4437 }
Netta P958d0a52017-02-07 11:20:55 -08004438
4439 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4440 final long sbToken = proto.start(fieldId);
4441 synchronized (this) {
4442 proto.write(SuspendBlockerProto.NAME, mName);
4443 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4444 }
4445 proto.end(sbToken);
4446 }
Jeff Brown96307042012-07-27 15:51:34 -07004447 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004448
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004449 static final class UidState {
4450 final int mUid;
4451 int mNumWakeLocks;
4452 int mProcState;
4453 boolean mActive;
4454
4455 UidState(int uid) {
4456 mUid = uid;
4457 }
4458 }
4459
Santos Cordon64a6e612018-08-22 19:27:04 +01004460 @VisibleForTesting
4461 final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004462 @Override
4463 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4464 FileDescriptor err, String[] args, ShellCallback callback,
4465 ResultReceiver resultReceiver) {
4466 (new PowerManagerShellCommand(this)).exec(
4467 this, in, out, err, args, callback, resultReceiver);
4468 }
4469
Jeff Brown6f357d32014-01-15 20:40:55 -08004470 @Override // Binder call
4471 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4472 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004473 if (uid < 0) {
4474 uid = Binder.getCallingUid();
4475 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004476 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004477 }
4478
4479 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004480 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004481 if (!mSystemReady) {
4482 // Service not ready yet, so who the heck cares about power hints, bah.
4483 return;
4484 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004485 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004486 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004487 }
4488
4489 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004490 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004491 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004492 if (lock == null) {
4493 throw new IllegalArgumentException("lock must not be null");
4494 }
4495 if (packageName == null) {
4496 throw new IllegalArgumentException("packageName must not be null");
4497 }
4498 PowerManager.validateWakeLockParameters(flags, tag);
4499
4500 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004501 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4502 mContext.enforceCallingOrSelfPermission(
4503 android.Manifest.permission.DEVICE_POWER, null);
4504 }
Narayan Kamath81822022017-12-08 11:56:01 +00004505 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004506 mContext.enforceCallingOrSelfPermission(
4507 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4508 } else {
4509 ws = null;
4510 }
4511
4512 final int uid = Binder.getCallingUid();
4513 final int pid = Binder.getCallingPid();
4514 final long ident = Binder.clearCallingIdentity();
4515 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004516 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004517 } finally {
4518 Binder.restoreCallingIdentity(ident);
4519 }
4520 }
4521
4522 @Override // Binder call
4523 public void releaseWakeLock(IBinder lock, int flags) {
4524 if (lock == null) {
4525 throw new IllegalArgumentException("lock must not be null");
4526 }
4527
4528 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4529
4530 final long ident = Binder.clearCallingIdentity();
4531 try {
4532 releaseWakeLockInternal(lock, flags);
4533 } finally {
4534 Binder.restoreCallingIdentity(ident);
4535 }
4536 }
4537
4538 @Override // Binder call
4539 public void updateWakeLockUids(IBinder lock, int[] uids) {
4540 WorkSource ws = null;
4541
4542 if (uids != null) {
4543 ws = new WorkSource();
4544 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4545 // one at a time?
4546 for (int i = 0; i < uids.length; i++) {
4547 ws.add(uids[i]);
4548 }
4549 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004550 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004551 }
4552
4553 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004554 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004555 if (lock == null) {
4556 throw new IllegalArgumentException("lock must not be null");
4557 }
4558
4559 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004560 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004561 mContext.enforceCallingOrSelfPermission(
4562 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4563 } else {
4564 ws = null;
4565 }
4566
Dianne Hackbornd953c532014-08-16 18:17:38 -07004567 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004568 final long ident = Binder.clearCallingIdentity();
4569 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004570 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004571 } finally {
4572 Binder.restoreCallingIdentity(ident);
4573 }
4574 }
4575
4576 @Override // Binder call
4577 public boolean isWakeLockLevelSupported(int level) {
4578 final long ident = Binder.clearCallingIdentity();
4579 try {
4580 return isWakeLockLevelSupportedInternal(level);
4581 } finally {
4582 Binder.restoreCallingIdentity(ident);
4583 }
4584 }
4585
4586 @Override // Binder call
4587 public void userActivity(long eventTime, int event, int flags) {
4588 final long now = SystemClock.uptimeMillis();
4589 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004590 != PackageManager.PERMISSION_GRANTED
4591 && mContext.checkCallingOrSelfPermission(
4592 android.Manifest.permission.USER_ACTIVITY)
4593 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004594 // Once upon a time applications could call userActivity().
4595 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4596 // request instead of throwing a SecurityException so we don't break old apps.
4597 synchronized (mLock) {
4598 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4599 mLastWarningAboutUserActivityPermission = now;
4600 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004601 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4602 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004603 + " pid=" + Binder.getCallingPid()
4604 + " uid=" + Binder.getCallingUid());
4605 }
4606 }
4607 return;
4608 }
4609
Jim Millerdca15d22015-06-16 20:55:13 -07004610 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004611 throw new IllegalArgumentException("event time must not be in the future");
4612 }
4613
4614 final int uid = Binder.getCallingUid();
4615 final long ident = Binder.clearCallingIdentity();
4616 try {
4617 userActivityInternal(eventTime, event, flags, uid);
4618 } finally {
4619 Binder.restoreCallingIdentity(ident);
4620 }
4621 }
4622
4623 @Override // Binder call
Michael Wrighte3001042019-02-05 00:13:14 +00004624 public void wakeUp(long eventTime, @WakeReason int reason, String details,
4625 String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004626 if (eventTime > SystemClock.uptimeMillis()) {
4627 throw new IllegalArgumentException("event time must not be in the future");
4628 }
4629
4630 mContext.enforceCallingOrSelfPermission(
4631 android.Manifest.permission.DEVICE_POWER, null);
4632
Jeff Brownc12035c2014-08-13 18:52:25 -07004633 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004634 final long ident = Binder.clearCallingIdentity();
4635 try {
Michael Wrighte3001042019-02-05 00:13:14 +00004636 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004637 } finally {
4638 Binder.restoreCallingIdentity(ident);
4639 }
4640 }
4641
4642 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004643 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004644 if (eventTime > SystemClock.uptimeMillis()) {
4645 throw new IllegalArgumentException("event time must not be in the future");
4646 }
4647
4648 mContext.enforceCallingOrSelfPermission(
4649 android.Manifest.permission.DEVICE_POWER, null);
4650
Jeff Brownc12035c2014-08-13 18:52:25 -07004651 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004652 final long ident = Binder.clearCallingIdentity();
4653 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004654 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004655 } finally {
4656 Binder.restoreCallingIdentity(ident);
4657 }
4658 }
4659
4660 @Override // Binder call
4661 public void nap(long eventTime) {
4662 if (eventTime > SystemClock.uptimeMillis()) {
4663 throw new IllegalArgumentException("event time must not be in the future");
4664 }
4665
4666 mContext.enforceCallingOrSelfPermission(
4667 android.Manifest.permission.DEVICE_POWER, null);
4668
Jeff Brownc12035c2014-08-13 18:52:25 -07004669 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004670 final long ident = Binder.clearCallingIdentity();
4671 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004672 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004673 } finally {
4674 Binder.restoreCallingIdentity(ident);
4675 }
4676 }
4677
4678 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004679 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004680 final long ident = Binder.clearCallingIdentity();
4681 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004682 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004683 } finally {
4684 Binder.restoreCallingIdentity(ident);
4685 }
4686 }
4687
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004688 @Override // Binder call
4689 public boolean isPowerSaveMode() {
4690 final long ident = Binder.clearCallingIdentity();
4691 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004692 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004693 } finally {
4694 Binder.restoreCallingIdentity(ident);
4695 }
4696 }
4697
jackqdyulei455e90a2017-02-09 15:29:16 -08004698 // Binder call
4699 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4700 final long ident = Binder.clearCallingIdentity();
4701 try {
Kweku Adams9f488e22019-01-14 16:25:08 -08004702 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
jackqdyulei455e90a2017-02-09 15:29:16 -08004703 } finally {
4704 Binder.restoreCallingIdentity(ident);
4705 }
4706 }
4707
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004708 @Override // Binder call
Salvador Martinezc8c4c5d2019-03-11 11:11:37 -07004709 public boolean setPowerSaveModeEnabled(boolean enabled) {
Salvador Martineza80bbab2018-09-24 10:36:11 -07004710 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4711 != PackageManager.PERMISSION_GRANTED) {
4712 mContext.enforceCallingOrSelfPermission(
4713 android.Manifest.permission.DEVICE_POWER, null);
4714 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004715 final long ident = Binder.clearCallingIdentity();
4716 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004717 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004718 } finally {
4719 Binder.restoreCallingIdentity(ident);
4720 }
4721 }
4722
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004723 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004724 public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
Salvador Martinez812ea752018-10-19 13:03:20 -07004725 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4726 "updateDynamicPowerSavings");
4727 final long ident = Binder.clearCallingIdentity();
4728 try {
4729 final ContentResolver resolver = mContext.getContentResolver();
4730 boolean success = Settings.Global.putInt(resolver,
4731 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4732 disableThreshold);
4733 if (success) {
4734 // abort updating if we weren't able to succeed on the threshold
4735 success &= Settings.Global.putInt(resolver,
4736 Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004737 powerSaveHint ? 1 : 0);
Salvador Martinez812ea752018-10-19 13:03:20 -07004738 }
4739 return success;
4740 } finally {
4741 Binder.restoreCallingIdentity(ident);
4742 }
4743 }
4744
4745 @Override // Binder call
Kweku Adams9f488e22019-01-14 16:25:08 -08004746 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4747 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4748 != PackageManager.PERMISSION_GRANTED) {
4749 mContext.enforceCallingOrSelfPermission(
4750 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4751 }
4752 final long ident = Binder.clearCallingIdentity();
4753 try {
4754 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4755 } finally {
4756 Binder.restoreCallingIdentity(ident);
4757 }
4758 }
4759
4760 @Override // Binder call
4761 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4762 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4763 != PackageManager.PERMISSION_GRANTED) {
4764 mContext.enforceCallingOrSelfPermission(
4765 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4766 }
4767 final long ident = Binder.clearCallingIdentity();
4768 try {
4769 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4770 } finally {
4771 Binder.restoreCallingIdentity(ident);
4772 }
4773 }
4774
4775 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004776 public int getPowerSaveModeTrigger() {
Salvador Martinez812ea752018-10-19 13:03:20 -07004777 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4778 final long ident = Binder.clearCallingIdentity();
4779 try {
4780 return Settings.Global.getInt(mContext.getContentResolver(),
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004781 Settings.Global.AUTOMATIC_POWER_SAVE_MODE,
4782 PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE);
Salvador Martinez812ea752018-10-19 13:03:20 -07004783 } finally {
4784 Binder.restoreCallingIdentity(ident);
4785 }
4786 }
4787
4788 @Override // Binder call
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004789 public boolean isDeviceIdleMode() {
4790 final long ident = Binder.clearCallingIdentity();
4791 try {
4792 return isDeviceIdleModeInternal();
4793 } finally {
4794 Binder.restoreCallingIdentity(ident);
4795 }
4796 }
4797
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004798 @Override // Binder call
4799 public boolean isLightDeviceIdleMode() {
4800 final long ident = Binder.clearCallingIdentity();
4801 try {
4802 return isLightDeviceIdleModeInternal();
4803 } finally {
4804 Binder.restoreCallingIdentity(ident);
4805 }
4806 }
4807
Jeff Brown6f357d32014-01-15 20:40:55 -08004808 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004809 * Gets the reason for the last time the phone had to reboot.
4810 *
4811 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004812 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004813 */
4814 @Override // Binder call
4815 public int getLastShutdownReason() {
4816 mContext.enforceCallingOrSelfPermission(
4817 android.Manifest.permission.DEVICE_POWER, null);
4818
4819 final long ident = Binder.clearCallingIdentity();
4820 try {
Mark Salyzyn74ce8b32018-06-05 09:06:54 -07004821 return getLastShutdownReasonInternal(REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004822 } finally {
4823 Binder.restoreCallingIdentity(ident);
4824 }
4825 }
4826
Calin Tatarua3805722018-08-09 16:41:28 +02004827 @Override // Binder call
4828 public int getLastSleepReason() {
4829 mContext.enforceCallingOrSelfPermission(
4830 android.Manifest.permission.DEVICE_POWER, null);
4831
4832 final long ident = Binder.clearCallingIdentity();
4833 try {
4834 return getLastSleepReasonInternal();
4835 } finally {
4836 Binder.restoreCallingIdentity(ident);
4837 }
4838 }
4839
Salvador Martineza6f7b252017-04-10 10:46:15 -07004840 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004841 * Reboots the device.
4842 *
4843 * @param confirm If true, shows a reboot confirmation dialog.
4844 * @param reason The reason for the reboot, or null if none.
4845 * @param wait If true, this call waits for the reboot to complete and does not return.
4846 */
4847 @Override // Binder call
4848 public void reboot(boolean confirm, String reason, boolean wait) {
4849 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004850 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4851 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004852 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4853 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004854
4855 final long ident = Binder.clearCallingIdentity();
4856 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004857 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4858 } finally {
4859 Binder.restoreCallingIdentity(ident);
4860 }
4861 }
4862
4863 /**
4864 * Reboots the device into safe mode
4865 *
4866 * @param confirm If true, shows a reboot confirmation dialog.
4867 * @param wait If true, this call waits for the reboot to complete and does not return.
4868 */
4869 @Override // Binder call
4870 public void rebootSafeMode(boolean confirm, boolean wait) {
4871 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4872
4873 final long ident = Binder.clearCallingIdentity();
4874 try {
4875 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4876 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004877 } finally {
4878 Binder.restoreCallingIdentity(ident);
4879 }
4880 }
4881
4882 /**
4883 * Shuts down the device.
4884 *
4885 * @param confirm If true, shows a shutdown confirmation dialog.
4886 * @param wait If true, this call waits for the shutdown to complete and does not return.
4887 */
4888 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004889 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004890 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4891
4892 final long ident = Binder.clearCallingIdentity();
4893 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004894 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004895 } finally {
4896 Binder.restoreCallingIdentity(ident);
4897 }
4898 }
4899
4900 /**
4901 * Crash the runtime (causing a complete restart of the Android framework).
4902 * Requires REBOOT permission. Mostly for testing. Should not return.
4903 */
4904 @Override // Binder call
4905 public void crash(String message) {
4906 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4907
4908 final long ident = Binder.clearCallingIdentity();
4909 try {
4910 crashInternal(message);
4911 } finally {
4912 Binder.restoreCallingIdentity(ident);
4913 }
4914 }
4915
4916 /**
4917 * Set the setting that determines whether the device stays on when plugged in.
4918 * The argument is a bit string, with each bit specifying a power source that,
4919 * when the device is connected to that source, causes the device to stay on.
4920 * See {@link android.os.BatteryManager} for the list of power sources that
4921 * can be specified. Current values include
4922 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4923 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4924 *
4925 * Used by "adb shell svc power stayon ..."
4926 *
4927 * @param val an {@code int} containing the bits that specify which power sources
4928 * should cause the device to stay on.
4929 */
4930 @Override // Binder call
4931 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004932 int uid = Binder.getCallingUid();
4933 // if uid is of root's, we permit this operation straight away
4934 if (uid != Process.ROOT_UID) {
4935 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4936 Settings.getPackageNameForUid(mContext, uid), true)) {
4937 return;
4938 }
4939 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004940
4941 final long ident = Binder.clearCallingIdentity();
4942 try {
4943 setStayOnSettingInternal(val);
4944 } finally {
4945 Binder.restoreCallingIdentity(ident);
4946 }
4947 }
4948
4949 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004950 * Used by the phone application to make the attention LED flash when ringing.
4951 */
4952 @Override // Binder call
4953 public void setAttentionLight(boolean on, int color) {
4954 mContext.enforceCallingOrSelfPermission(
4955 android.Manifest.permission.DEVICE_POWER, null);
4956
4957 final long ident = Binder.clearCallingIdentity();
4958 try {
4959 setAttentionLightInternal(on, color);
4960 } finally {
4961 Binder.restoreCallingIdentity(ident);
4962 }
4963 }
4964
4965 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08004966 public void setDozeAfterScreenOff(boolean on) {
4967 mContext.enforceCallingOrSelfPermission(
4968 android.Manifest.permission.DEVICE_POWER, null);
4969
4970 final long ident = Binder.clearCallingIdentity();
4971 try {
4972 setDozeAfterScreenOffInternal(on);
4973 } finally {
4974 Binder.restoreCallingIdentity(ident);
4975 }
4976 }
4977
4978 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004979 public void boostScreenBrightness(long eventTime) {
4980 if (eventTime > SystemClock.uptimeMillis()) {
4981 throw new IllegalArgumentException("event time must not be in the future");
4982 }
4983
4984 mContext.enforceCallingOrSelfPermission(
4985 android.Manifest.permission.DEVICE_POWER, null);
4986
4987 final int uid = Binder.getCallingUid();
4988 final long ident = Binder.clearCallingIdentity();
4989 try {
4990 boostScreenBrightnessInternal(eventTime, uid);
4991 } finally {
4992 Binder.restoreCallingIdentity(ident);
4993 }
4994 }
4995
4996 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004997 public boolean isScreenBrightnessBoosted() {
4998 final long ident = Binder.clearCallingIdentity();
4999 try {
5000 return isScreenBrightnessBoostedInternal();
5001 } finally {
5002 Binder.restoreCallingIdentity(ident);
5003 }
5004 }
5005
Santos Cordon12f92eb2019-02-01 21:28:47 +00005006 @Override // binder call
5007 public boolean forceSuspend() {
5008 mContext.enforceCallingOrSelfPermission(
5009 android.Manifest.permission.DEVICE_POWER, null);
5010
5011 final int uid = Binder.getCallingUid();
5012 final long ident = Binder.clearCallingIdentity();
5013 try {
5014 return forceSuspendInternal(uid);
5015 } finally {
5016 Binder.restoreCallingIdentity(ident);
5017 }
5018 }
5019
Bryce Lee84d6c0f2015-03-17 10:43:08 -07005020 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08005021 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005022 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08005023
5024 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08005025
5026 boolean isDumpProto = false;
5027 for (String arg : args) {
5028 if (arg.equals("--proto")) {
5029 isDumpProto = true;
5030 }
5031 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005032 try {
Netta P958d0a52017-02-07 11:20:55 -08005033 if (isDumpProto) {
5034 dumpProto(fd);
5035 } else {
5036 dumpInternal(pw);
5037 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005038 } finally {
5039 Binder.restoreCallingIdentity(ident);
5040 }
5041 }
5042 }
5043
Salvador Martineza6f7b252017-04-10 10:46:15 -07005044 @VisibleForTesting
Santos Cordon64a6e612018-08-22 19:27:04 +01005045 BinderService getBinderServiceInstance() {
5046 return mBinderService;
5047 }
5048
5049 @VisibleForTesting
5050 LocalService getLocalServiceInstance() {
5051 return mLocalService;
5052 }
5053
5054 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07005055 // lastRebootReasonProperty argument to permit testing
5056 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
5057 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01005058 if (line == null) {
5059 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
5060 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07005061 switch (line) {
5062 case REASON_SHUTDOWN:
5063 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
5064 case REASON_REBOOT:
5065 return PowerManager.SHUTDOWN_REASON_REBOOT;
5066 case REASON_USERREQUESTED:
5067 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
5068 case REASON_THERMAL_SHUTDOWN:
5069 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07005070 case REASON_LOW_BATTERY:
5071 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
5072 case REASON_BATTERY_THERMAL_STATE:
5073 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07005074 default:
5075 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
5076 }
5077 }
5078
Calin Tatarua3805722018-08-09 16:41:28 +02005079 private int getLastSleepReasonInternal() {
5080 synchronized (mLock) {
5081 return mLastSleepReason;
5082 }
5083 }
5084
Santos Cordon623526b2019-04-09 17:02:38 +01005085 private PowerManager.WakeData getLastWakeupInternal() {
5086 synchronized (mLock) {
5087 return new WakeData(mLastWakeTime, mLastWakeReason);
5088 }
5089 }
5090
Santos Cordond9701ab2019-08-01 18:33:20 +01005091 @VisibleForTesting
5092 final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08005093 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07005094 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
5095 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
5096 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
5097 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08005098 }
Jeff Brown970d4132014-07-19 11:33:47 -07005099 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08005100 }
5101
Jeff Brown6f357d32014-01-15 20:40:55 -08005102 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07005103 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
5104 switch (screenState) {
5105 case Display.STATE_UNKNOWN:
5106 case Display.STATE_OFF:
5107 case Display.STATE_DOZE:
5108 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07005109 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07005110 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07005111 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07005112 break;
5113 default:
5114 screenState = Display.STATE_UNKNOWN;
5115 break;
5116 }
5117 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
5118 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
5119 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
5120 }
5121 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
5122 }
5123
Jeff Brown6f357d32014-01-15 20:40:55 -08005124 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07005125 public void setUserInactiveOverrideFromWindowManager() {
5126 setUserInactiveOverrideFromWindowManagerInternal();
5127 }
5128
5129 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08005130 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07005131 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08005132 }
5133
5134 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00005135 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
5136 setDrawWakeLockOverrideFromSidekickInternal(keepState);
5137 }
5138
5139 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01005140 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
5141 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08005142 }
5143
5144 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08005145 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Kweku Adams9f488e22019-01-14 16:25:08 -08005146 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005147 }
5148
5149 @Override
5150 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08005151 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005152 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005153
5154 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005155 public boolean setDeviceIdleMode(boolean enabled) {
5156 return setDeviceIdleModeInternal(enabled);
5157 }
5158
5159 @Override
5160 public boolean setLightDeviceIdleMode(boolean enabled) {
5161 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07005162 }
5163
5164 @Override
5165 public void setDeviceIdleWhitelist(int[] appids) {
5166 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005167 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07005168
5169 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07005170 public void setDeviceIdleTempWhitelist(int[] appids) {
5171 setDeviceIdleTempWhitelistInternal(appids);
5172 }
5173
5174 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07005175 public void startUidChanges() {
5176 startUidChangesInternal();
5177 }
5178
5179 @Override
5180 public void finishUidChanges() {
5181 finishUidChangesInternal();
5182 }
5183
5184 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07005185 public void updateUidProcState(int uid, int procState) {
5186 updateUidProcStateInternal(uid, procState);
5187 }
5188
5189 @Override
5190 public void uidGone(int uid) {
5191 uidGoneInternal(uid);
5192 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01005193
5194 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07005195 public void uidActive(int uid) {
5196 uidActiveInternal(uid);
5197 }
5198
5199 @Override
5200 public void uidIdle(int uid) {
5201 uidIdleInternal(uid);
5202 }
5203
5204 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01005205 public void powerHint(int hintId, int data) {
5206 powerHintInternal(hintId, data);
5207 }
Alex Kershaw2418ea92018-10-19 17:17:49 +01005208
5209 @Override
5210 public boolean wasDeviceIdleFor(long ms) {
5211 return wasDeviceIdleForInternal(ms);
5212 }
Santos Cordon623526b2019-04-09 17:02:38 +01005213
5214 @Override
5215 public WakeData getLastWakeup() {
5216 return getLastWakeupInternal();
5217 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005219}