blob: a7b0d84ef040945eeba70c4144080ff0349e42f1 [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
Chris Ye73b85a62020-01-18 10:11:26 -080019import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_CRITICAL;
Ivailo Karamanolevf773e102020-01-16 16:10:42 +010020import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT;
Beverlyae79ab92017-12-11 09:20:02 -050021import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
22import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
23import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
24import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
25
Tony Mantlerb8009fd2016-03-14 15:55:35 -070026import android.annotation.IntDef;
Kweku Adams9f488e22019-01-14 16:25:08 -080027import android.annotation.NonNull;
Nikita Ioffe779d6be2020-02-06 23:17:17 +000028import android.annotation.Nullable;
Pavel Grafov28939982017-10-03 15:11:52 +010029import android.annotation.UserIdInt;
Jason Monkafae4bd2015-12-15 14:20:06 -050030import android.app.ActivityManager;
Pavel Grafov28939982017-10-03 15:11:52 +010031import android.app.SynchronousUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080033import android.content.ContentResolver;
34import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
37import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070038import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080039import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080040import android.hardware.SensorManager;
41import android.hardware.SystemSensorManager;
Issei Suzukica19e6e2019-02-26 12:39:11 +010042import android.hardware.display.AmbientDisplayConfiguration;
Jeff Brown4ccb8232014-01-16 22:16:42 -080043import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070044import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Ruchi Kandoi0d434042016-10-03 09:12:02 -070045import android.hardware.power.V1_0.PowerHint;
Jeff Brown96307042012-07-27 15:51:34 -070046import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070047import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070048import android.os.BatteryManagerInternal;
Kweku Adams9f488e22019-01-14 16:25:08 -080049import android.os.BatterySaverPolicyConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.Binder;
51import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.IBinder;
53import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070054import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080055import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -070057import android.os.PowerManager.ServiceType;
Santos Cordon623526b2019-04-09 17:02:38 +010058import android.os.PowerManager.WakeData;
Michael Wrighte3001042019-02-05 00:13:14 +000059import android.os.PowerManager.WakeReason;
Jeff Brown6f357d32014-01-15 20:40:55 -080060import android.os.PowerManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080061import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.os.Process;
63import android.os.RemoteException;
Jocelyn Dangf2c38c12017-03-31 14:03:37 -070064import android.os.ResultReceiver;
65import android.os.ShellCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070067import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070068import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070069import android.os.UserHandle;
Christine Franks732c0432017-06-23 18:12:46 -070070import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070071import android.os.WorkSource;
Narayan Kamath2f916ed2017-12-29 13:02:15 +000072import android.os.WorkSource.WorkChain;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.provider.Settings;
Daichi Hirono82ab9802016-03-02 13:23:29 +090074import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080075import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070076import android.service.vr.IVrManager;
77import android.service.vr.IVrStateCallbacks;
Yogisha Dixit9c20afa2020-01-15 15:55:51 +000078import android.util.ArraySet;
Dianne Hackborn0ef403e2017-01-24 18:22:15 -080079import android.util.KeyValueListParser;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070080import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080081import android.util.Slog;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -070082import android.util.SparseArray;
Jeff Brown96307042012-07-27 15:51:34 -070083import android.util.TimeUtils;
Netta P958d0a52017-02-07 11:20:55 -080084import android.util.proto.ProtoOutputStream;
Jeff Brown037c33e2014-04-09 00:31:55 -070085import android.view.Display;
Makoto Onukiaae89532017-11-08 14:32:03 -080086
Fiona Campbelld4eb2952019-11-04 17:19:56 +000087import com.android.internal.BrightnessSynchronizer;
jackqdyulei92681e82017-02-28 11:26:28 -080088import com.android.internal.annotations.VisibleForTesting;
Jason Monkafae4bd2015-12-15 14:20:06 -050089import com.android.internal.app.IAppOpsService;
90import com.android.internal.app.IBatteryStats;
91import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050093import com.android.server.EventLogTags;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060094import com.android.server.LockGuard;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070095import com.android.server.RescueParty;
Jason Monkafae4bd2015-12-15 14:20:06 -050096import com.android.server.ServiceThread;
97import com.android.server.SystemService;
Michael Wright64c820d2017-03-21 12:36:55 +000098import com.android.server.UiThread;
Nikita Ioffe779d6be2020-02-06 23:17:17 +000099import com.android.server.UserspaceRebootLogger;
Jason Monkafae4bd2015-12-15 14:20:06 -0500100import com.android.server.Watchdog;
101import com.android.server.am.BatteryStatsService;
Jason Monkafae4bd2015-12-15 14:20:06 -0500102import com.android.server.lights.LightsManager;
Ivailo Karamanolevf773e102020-01-16 16:10:42 +0100103import com.android.server.lights.LogicalLight;
Adrian Roose99bc052017-11-20 17:55:31 +0100104import com.android.server.policy.WindowManagerPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800105import com.android.server.power.batterysaver.BatterySaverController;
Kweku Adams7fb72a42019-01-08 16:08:49 -0800106import com.android.server.power.batterysaver.BatterySaverPolicy;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700107import com.android.server.power.batterysaver.BatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700108import com.android.server.power.batterysaver.BatterySavingStats;
Makoto Onuki66a78122017-11-14 15:03:21 -0800109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.io.FileDescriptor;
111import java.io.PrintWriter;
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700112import java.lang.annotation.Retention;
113import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import java.util.ArrayList;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700115import java.util.Arrays;
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -0800116import java.util.List;
Narayan Kamath607223f2018-02-19 14:09:02 +0000117import java.util.Objects;
Yogisha Dixit9c20afa2020-01-15 15:55:51 +0000118import java.util.Set;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Jeff Brown96307042012-07-27 15:51:34 -0700120/**
121 * The power manager service is responsible for coordinating power management
122 * functions on the device.
123 */
Jeff Brown2175e9c2014-09-12 16:11:07 -0700124public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -0700125 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127
Santos Cordon4ddb8012017-09-20 15:25:44 -0700128 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700129 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700130
Jeff Brown96307042012-07-27 15:51:34 -0700131 // Message: Sent when a user activity timeout occurs to update the power state.
132 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800133 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700134 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700135 // Message: Sent when the screen brightness boost expires.
136 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700137 // Message: Polling to look for long held wake locks.
138 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Robert Horvath5560f382019-07-10 10:46:38 +0200139 // Message: Sent when an attentive timeout occurs to update the power state.
140 private static final int MSG_ATTENTIVE_TIMEOUT = 5;
Jeff Brown7304c342012-05-11 18:42:42 -0700141
Jeff Brown96307042012-07-27 15:51:34 -0700142 // Dirty bit: mWakeLocks changed
143 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
144 // Dirty bit: mWakefulness changed
145 private static final int DIRTY_WAKEFULNESS = 1 << 1;
146 // Dirty bit: user activity was poked or may have timed out
147 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
148 // Dirty bit: actual display power state was updated asynchronously
149 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
150 // Dirty bit: mBootCompleted changed
151 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
152 // Dirty bit: settings changed
153 private static final int DIRTY_SETTINGS = 1 << 5;
154 // Dirty bit: mIsPowered changed
155 private static final int DIRTY_IS_POWERED = 1 << 6;
156 // Dirty bit: mStayOn changed
157 private static final int DIRTY_STAY_ON = 1 << 7;
158 // Dirty bit: battery state changed
159 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700160 // Dirty bit: proximity state changed
161 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700162 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700163 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700164 // Dirty bit: brightness boost changed
165 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800166 // Dirty bit: sQuiescent changed
167 private static final int DIRTY_QUIESCENT = 1 << 12;
Santos Cordon3107d292016-09-20 15:50:35 -0700168 // Dirty bit: VR Mode enabled changed
169 private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
Robert Horvath5560f382019-07-10 10:46:38 +0200170 // Dirty bit: attentive timer may have timed out
171 private static final int DIRTY_ATTENTIVE = 1 << 14;
Jeff Brown7304c342012-05-11 18:42:42 -0700172
Jeff Brown96307042012-07-27 15:51:34 -0700173 // Summarizes the state of all active wakelocks.
174 private static final int WAKE_LOCK_CPU = 1 << 0;
175 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
176 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
177 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
178 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700179 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800180 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800181 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Jeff Brown96307042012-07-27 15:51:34 -0700183 // Summarizes the user activity state.
184 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
185 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700186 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Jeff Brown27736f52014-05-20 17:17:10 -0700188 // Default timeout in milliseconds. This is only used until the settings
189 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700190 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700191 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700192
Jeff Browne333e672014-10-28 13:48:55 -0700193 // Screen brightness boost timeout.
194 // Hardcoded for now until we decide what the right policy should be.
195 // This should perhaps be a setting.
196 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
197
Fiona Campbelld4eb2952019-11-04 17:19:56 +0000198 // Float.NaN cannot be stored in config.xml so -2 is used instead
199 private static final float INVALID_BRIGHTNESS_IN_CONFIG = -2f;
200
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700201 // How long a partial wake lock must be held until we consider it a long wake lock.
202 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
203
Jason Monk27bbb2d2015-03-31 16:46:39 -0400204 // Power features defined in hardware/libhardware/include/hardware/power.h.
205 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
206
207 // Default setting for double tap to wake.
208 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
209
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800210 // System property indicating that the screen should remain off until an explicit user action
211 private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
212
Christine Franks732c0432017-06-23 18:12:46 -0700213 // System Property indicating that retail demo mode is currently enabled.
214 private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
215
Robert Horvath84a67c62019-11-29 15:31:30 +0100216 // System property for last reboot reason
217 private static final String SYSTEM_PROPERTY_REBOOT_REASON = "sys.boot.reason";
218
219 // Possible reasons for shutting down or reboot for use in
220 // SYSTEM_PROPERTY_REBOOT_REASON(sys.boot.reason) which is set by bootstat
Salvador Martineza6f7b252017-04-10 10:46:15 -0700221 private static final String REASON_SHUTDOWN = "shutdown";
222 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700223 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
224 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700225 private static final String REASON_LOW_BATTERY = "shutdown,battery";
226 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700227
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700228 private static final String TRACE_SCREEN_ON = "Screen turning on";
229
230 /** If turning screen on takes more than this long, we show a warning on logcat. */
231 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
232
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700233 /** Constants for {@link #shutdownOrRebootInternal} */
234 @Retention(RetentionPolicy.SOURCE)
235 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
236 public @interface HaltMode {}
237 private static final int HALT_MODE_SHUTDOWN = 0;
238 private static final int HALT_MODE_REBOOT = 1;
239 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
240
Jeff Brownb880d882014-02-10 19:47:07 -0800241 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700242 private final ServiceThread mHandlerThread;
243 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100244 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800245 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800246 private final BatterySaverController mBatterySaverController;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700247 private final BatterySaverStateMachine mBatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700248 private final BatterySavingStats mBatterySavingStats;
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800249 private final AttentionDetector mAttentionDetector;
Santos Cordon64a6e612018-08-22 19:27:04 +0100250 private final BinderService mBinderService;
251 private final LocalService mLocalService;
252 private final NativeWrapper mNativeWrapper;
Robert Horvath84a67c62019-11-29 15:31:30 +0100253 private final SystemPropertiesWrapper mSystemProperties;
Santos Cordon64a6e612018-08-22 19:27:04 +0100254 private final Injector mInjector;
Jeff Brown2c43c332014-06-12 22:38:59 -0700255
Adam Lesinski182f73f2013-12-05 16:48:06 -0800256 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700257 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800258 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700259 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700260 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700261 private WindowManagerPolicy mPolicy;
262 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800263 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700264 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800265 private DreamManagerInternal mDreamManager;
Ivailo Karamanolevf773e102020-01-16 16:10:42 +0100266 private LogicalLight mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700267
Robert Horvath5560f382019-07-10 10:46:38 +0200268 private InattentiveSleepWarningController mInattentiveSleepWarningOverlayController;
269
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600270 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700271
272 // A bitfield that indicates what parts of the power state have
273 // changed and need to be recalculated.
274 private int mDirty;
275
276 // Indicates whether the device is awake or asleep or somewhere in between.
277 // This is distinct from the screen power state, which is managed separately.
278 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800279 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700280
Jeff Brown26875502014-01-30 21:47:47 -0800281 // True if the sandman has just been summoned for the first time since entering the
282 // dreaming or dozing state. Indicates whether a new dream should begin.
283 private boolean mSandmanSummoned;
284
Jeff Brown96307042012-07-27 15:51:34 -0700285 // True if MSG_SANDMAN has been scheduled.
286 private boolean mSandmanScheduled;
287
288 // Table of all suspend blockers.
289 // There should only be a few of these.
290 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
291
292 // Table of all wake locks acquired by applications.
293 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
294
295 // A bitfield that summarizes the state of all active wakelocks.
296 private int mWakeLockSummary;
297
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700298 // Have we scheduled a message to check for long wake locks? This is when we will check.
299 private long mNotifyLongScheduled;
300
301 // Last time we checked for long wake locks.
302 private long mNotifyLongDispatched;
303
304 // The time we decided to do next long check.
305 private long mNotifyLongNextCheck;
306
Jeff Brown96307042012-07-27 15:51:34 -0700307 // If true, instructs the display controller to wait for the proximity sensor to
308 // go negative before turning the screen on.
309 private boolean mRequestWaitForNegativeProximity;
310
311 // Timestamp of the last time the device was awoken or put to sleep.
312 private long mLastWakeTime;
313 private long mLastSleepTime;
314
Calin Tatarua3805722018-08-09 16:41:28 +0200315 // Last reason the device went to sleep.
Michael Wrighte3001042019-02-05 00:13:14 +0000316 private @WakeReason int mLastWakeReason;
Calin Tatarua3805722018-08-09 16:41:28 +0200317 private int mLastSleepReason;
318
Jeff Brown96307042012-07-27 15:51:34 -0700319 // Timestamp of the last call to user activity.
320 private long mLastUserActivityTime;
321 private long mLastUserActivityTimeNoChangeLights;
322
Jeff Brown0a571122014-08-21 21:50:43 -0700323 // Timestamp of last interactive power hint.
324 private long mLastInteractivePowerHintTime;
325
Jeff Browne333e672014-10-28 13:48:55 -0700326 // Timestamp of the last screen brightness boost.
327 private long mLastScreenBrightnessBoostTime;
328 private boolean mScreenBrightnessBoostInProgress;
329
Jeff Brown96307042012-07-27 15:51:34 -0700330 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700331 private int mUserActivitySummary;
332
333 // The desired display power state. The actual state may lag behind the
334 // requested because it is updated asynchronously by the display power controller.
335 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
336
Jeff Brown96307042012-07-27 15:51:34 -0700337 // True if the display power state has been fully applied, which means the display
338 // is actually on or actually off or whatever was requested.
339 private boolean mDisplayReady;
340
Jeff Brown27f7a862012-12-12 15:43:31 -0800341 // The suspend blocker used to keep the CPU alive when an application has acquired
342 // a wake lock.
343 private final SuspendBlocker mWakeLockSuspendBlocker;
344
345 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700346 private boolean mHoldingWakeLockSuspendBlocker;
347
Jeff Brown27f7a862012-12-12 15:43:31 -0800348 // The suspend blocker used to keep the CPU alive when the display is on, the
349 // display is getting ready or there is user activity (in which case the display
350 // must be on).
351 private final SuspendBlocker mDisplaySuspendBlocker;
352
353 // True if the display suspend blocker has been acquired.
354 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700355
356 // True if systemReady() has been called.
357 private boolean mSystemReady;
358
Robert Horvath4fbab202019-11-29 15:36:39 +0100359 // True if boot completed occurred. We keep the screen on until this happens.
360 // The screen will be off if we are in quiescent mode.
Jeff Brown96307042012-07-27 15:51:34 -0700361 private boolean mBootCompleted;
362
Jeff Brown26875502014-01-30 21:47:47 -0800363 // True if auto-suspend mode is enabled.
364 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700365 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800366
367 // True if interactive mode is enabled.
368 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700369 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800370
Jeff Brown96307042012-07-27 15:51:34 -0700371 // True if the device is plugged into a power source.
372 private boolean mIsPowered;
373
Jeff Brownf3fb8952012-10-02 20:57:05 -0700374 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
375 private int mPlugType;
376
Jeff Brown016ff142012-10-15 16:47:22 -0700377 // The current battery level percentage.
378 private int mBatteryLevel;
379
380 // The battery level percentage at the time the dream started.
381 // This is used to terminate a dream and go to sleep if the battery is
382 // draining faster than it is charging and the user activity timeout has expired.
383 private int mBatteryLevelWhenDreamStarted;
384
Jeff Brownec6aa592012-10-17 20:30:25 -0700385 // The current dock state.
386 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
387
Jeff Brown26875502014-01-30 21:47:47 -0800388 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700389 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800390
391 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700392 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800393
Jeff Brown96307042012-07-27 15:51:34 -0700394 // True if the device should wake up when plugged or unplugged.
395 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
396
Bryce Lee584a4452014-10-21 15:55:55 -0700397 // True if the device should wake up when plugged or unplugged in theater mode.
398 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
399
Jeff Brownec083212013-09-11 20:45:25 -0700400 // True if the device should suspend when the screen is off due to proximity.
401 private boolean mSuspendWhenScreenOffDueToProximityConfig;
402
Robert Horvath5560f382019-07-10 10:46:38 +0200403 // Default value for attentive timeout.
404 private int mAttentiveTimeoutConfig;
405
Jeff Brown96307042012-07-27 15:51:34 -0700406 // True if dreams are supported on this device.
407 private boolean mDreamsSupportedConfig;
408
John Spurlocked108f32012-10-18 16:49:24 -0400409 // Default value for dreams enabled
410 private boolean mDreamsEnabledByDefaultConfig;
411
412 // Default value for dreams activate-on-sleep
413 private boolean mDreamsActivatedOnSleepByDefaultConfig;
414
415 // Default value for dreams activate-on-dock
416 private boolean mDreamsActivatedOnDockByDefaultConfig;
417
Jeff Brown26875502014-01-30 21:47:47 -0800418 // True if dreams can run while not plugged in.
419 private boolean mDreamsEnabledOnBatteryConfig;
420
421 // Minimum battery level to allow dreaming when powered.
422 // Use -1 to disable this safety feature.
423 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
424
425 // Minimum battery level to allow dreaming when not powered.
426 // Use -1 to disable this safety feature.
427 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
428
429 // If the battery level drops by this percentage and the user activity timeout
430 // has expired, then assume the device is receiving insufficient current to charge
431 // effectively and terminate the dream. Use -1 to disable this safety feature.
432 private int mDreamsBatteryLevelDrainCutoffConfig;
433
Jeff Brown96307042012-07-27 15:51:34 -0700434 // True if dreams are enabled by the user.
435 private boolean mDreamsEnabledSetting;
436
John Spurlock1a868b72012-08-22 09:56:51 -0400437 // True if dreams should be activated on sleep.
438 private boolean mDreamsActivateOnSleepSetting;
439
Jeff Brownec6aa592012-10-17 20:30:25 -0700440 // True if dreams should be activated on dock.
441 private boolean mDreamsActivateOnDockSetting;
442
Jeff Brown2175e9c2014-09-12 16:11:07 -0700443 // True if doze should not be started until after the screen off transition.
Lucas Dupin16cfe452018-02-08 13:14:50 -0800444 private boolean mDozeAfterScreenOff;
Jeff Brown2175e9c2014-09-12 16:11:07 -0700445
Jeff Brown27736f52014-05-20 17:17:10 -0700446 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100447 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700448
449 // The screen dim duration, in milliseconds.
450 // This is subtracted from the end of the screen off timeout so the
451 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100452 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700453
454 // The maximum screen dim time expressed as a ratio relative to the screen
455 // off timeout. If the screen off timeout is very short then we want the
456 // dim timeout to also be quite short so that most of the time is spent on.
457 // Otherwise the user won't get much screen on time before dimming occurs.
458 private float mMaximumScreenDimRatioConfig;
459
Jason Monk27bbb2d2015-03-31 16:46:39 -0400460 // Whether device supports double tap to wake.
461 private boolean mSupportsDoubleTapWakeConfig;
462
Jeff Brown96307042012-07-27 15:51:34 -0700463 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100464 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700465
Robert Horvath5560f382019-07-10 10:46:38 +0200466 // Default for attentive warning duration.
467 private long mAttentiveWarningDurationConfig;
468
Jeff Brown05af6ad2014-09-30 20:54:30 -0700469 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100470 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700471
Robert Horvath5560f382019-07-10 10:46:38 +0200472 // How long to show a warning message to user before the device goes to sleep
473 // after long user inactivity, even if wakelocks are held.
474 private long mAttentiveTimeoutSetting;
475
Jeff Brown96307042012-07-27 15:51:34 -0700476 // The maximum allowable screen off timeout according to the device
477 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100478 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700479
480 // The stay on while plugged in setting.
481 // A bitfield of battery conditions under which to make the screen stay on.
482 private int mStayOnWhilePluggedInSetting;
483
484 // True if the device should stay on.
485 private boolean mStayOn;
486
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800487 // True if the lights should stay off until an explicit user action.
488 private static boolean sQuiescent;
489
Jeff Brown93cbbb22012-10-04 13:18:36 -0700490 // True if the proximity sensor reads a positive result.
491 private boolean mProximityPositive;
492
Jeff Brown96307042012-07-27 15:51:34 -0700493 // Screen brightness setting limits.
Fiona Campbelld4eb2952019-11-04 17:19:56 +0000494 private float mScreenBrightnessSettingMinimum;
495 private float mScreenBrightnessSettingMaximum;
496 private float mScreenBrightnessSettingDefault;
497 public final float mScreenBrightnessMinimum;
498 public final float mScreenBrightnessMaximum;
499 public final float mScreenBrightnessDefault;
500 public final float mScreenBrightnessDoze;
501 public final float mScreenBrightnessDim;
502 public final float mScreenBrightnessMinimumVr;
503 public final float mScreenBrightnessMaximumVr;
504 public final float mScreenBrightnessDefaultVr;
Jeff Brown96307042012-07-27 15:51:34 -0700505
506 // The screen brightness mode.
507 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
508 private int mScreenBrightnessModeSetting;
509
510 // The screen brightness setting override from the window manager
511 // to allow the current foreground activity to override the brightness.
512 // Use -1 to disable.
513 private int mScreenBrightnessOverrideFromWindowManager = -1;
514
Fiona Campbelld4eb2952019-11-04 17:19:56 +0000515 private float mScreenBrightnessOverrideFromWindowManagerFloat =
516 PowerManager.BRIGHTNESS_INVALID_FLOAT;
517
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700518 // The window manager has determined the user to be inactive via other means.
519 // Set this to false to disable.
520 private boolean mUserInactiveOverrideFromWindowManager;
521
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700522 // The next possible user activity timeout after being explicitly told the user is inactive.
523 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
524 private long mOverriddenTimeout = -1;
525
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700526 // The user activity timeout override from the window manager
527 // to allow the current foreground activity to override the user activity timeout.
528 // Use -1 to disable.
529 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
530
Jeff Brown970d4132014-07-19 11:33:47 -0700531 // The screen state to use while dozing.
532 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
533
534 // The screen brightness to use while dozing.
535 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
536
Fiona Campbelld4eb2952019-11-04 17:19:56 +0000537 private float mDozeScreenBrightnessOverrideFromDreamManagerFloat =
538 PowerManager.BRIGHTNESS_INVALID_FLOAT;
Ivan Podogov56bc6d02018-02-26 16:04:24 +0000539 // Keep display state when dozing.
540 private boolean mDrawWakeLockOverrideFromSidekick;
541
Jeff Brown9ba8d782012-10-01 16:38:23 -0700542 // Time when we last logged a warning about calling userActivity() without permission.
543 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
544
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700545 // True if the battery level is currently considered low.
546 private boolean mBatteryLevelLow;
547
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700548 // True if we are currently in device idle mode.
549 private boolean mDeviceIdleMode;
550
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700551 // True if we are currently in light device idle mode.
552 private boolean mLightDeviceIdleMode;
553
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700554 // Set of app ids that we will always respect the wake locks for.
555 int[] mDeviceIdleWhitelist = new int[0];
556
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700557 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
558 int[] mDeviceIdleTempWhitelist = new int[0];
559
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700560 private final SparseArray<UidState> mUidState = new SparseArray<>();
561
562 // We are currently in the middle of a batch change of uids.
563 private boolean mUidsChanging;
564
565 // Some uids have actually changed while mUidsChanging was true.
566 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700567
Bryce Lee584a4452014-10-21 15:55:55 -0700568 // True if theater mode is enabled
569 private boolean mTheaterModeEnabled;
570
Adrian Roos56021892017-02-27 20:25:09 +0100571 // True if always on display is enabled
572 private boolean mAlwaysOnEnabled;
573
Jason Monk27bbb2d2015-03-31 16:46:39 -0400574 // True if double tap to wake is enabled
575 private boolean mDoubleTapWakeEnabled;
576
Santos Cordon3107d292016-09-20 15:50:35 -0700577 // True if we are currently in VR Mode.
578 private boolean mIsVrModeEnabled;
579
Santos Cordon12f92eb2019-02-01 21:28:47 +0000580 // True if we in the process of performing a forceSuspend
581 private boolean mForceSuspendActive;
582
Santos Cordon03044382019-09-19 16:59:01 +0100583 // Transition to Doze is in progress. We have transitioned to WAKEFULNESS_DOZING,
584 // but the DreamService has not yet been told to start (it's an async process).
585 private boolean mDozeStartInProgress;
586
Yogisha Dixit9c20afa2020-01-15 15:55:51 +0000587 // Set of all tokens suppressing ambient display.
588 private final Set<String> mAmbientDisplaySuppressionTokens = new ArraySet<>();
589
Pavel Grafov28939982017-10-03 15:11:52 +0100590 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
591 @Override
Beverly478722e2019-10-14 11:16:57 -0400592 public void onUserSwitching(@UserIdInt int newUserId) throws RemoteException {
593 synchronized (mLock) {
594 mUserId = newUserId;
595 }
596 }
Pavel Grafov28939982017-10-03 15:11:52 +0100597
598 @Override
599 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
600 final long now = SystemClock.uptimeMillis();
Beverly478722e2019-10-14 11:16:57 -0400601 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +0100602 mForegroundProfile = newProfileId;
603 maybeUpdateForegroundProfileLastActivityLocked(now);
604 }
605 }
606 }
607
608 // User id corresponding to activity the user is currently interacting with.
609 private @UserIdInt int mForegroundProfile;
Beverly478722e2019-10-14 11:16:57 -0400610 // User id of main profile for the current user (doesn't include managed profiles)
611 private @UserIdInt int mUserId;
Pavel Grafov28939982017-10-03 15:11:52 +0100612
613 // Per-profile state to track when a profile should be locked.
614 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
615
616 private static final class ProfilePowerState {
617 // Profile user id.
618 final @UserIdInt int mUserId;
619 // Maximum time to lock set by admin.
620 long mScreenOffTimeout;
621 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
622 int mWakeLockSummary;
623 // Last user activity that happened in an app running in the profile.
624 long mLastUserActivityTime;
625 // Whether profile has been locked last time it timed out.
626 boolean mLockingNotified;
627
628 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
629 mUserId = userId;
630 mScreenOffTimeout = screenOffTimeout;
631 // Not accurate but at least won't cause immediate locking of the profile.
632 mLastUserActivityTime = SystemClock.uptimeMillis();
633 }
634 }
635
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800636 /**
637 * All times are in milliseconds. These constants are kept synchronized with the system
638 * global Settings. Any access to this class or its fields should be done while
639 * holding the PowerManagerService.mLock lock.
640 */
641 private final class Constants extends ContentObserver {
642 // Key names stored in the settings value.
643 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
644
645 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
646
647 // Prevent processes that are cached from holding wake locks?
648 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
649
650 private ContentResolver mResolver;
651 private final KeyValueListParser mParser = new KeyValueListParser(',');
652
653 public Constants(Handler handler) {
654 super(handler);
655 }
656
657 public void start(ContentResolver resolver) {
658 mResolver = resolver;
659 mResolver.registerContentObserver(Settings.Global.getUriFor(
660 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
661 updateConstants();
662 }
663
664 @Override
665 public void onChange(boolean selfChange, Uri uri) {
666 updateConstants();
667 }
668
669 private void updateConstants() {
670 synchronized (mLock) {
671 try {
672 mParser.setString(Settings.Global.getString(mResolver,
673 Settings.Global.POWER_MANAGER_CONSTANTS));
674 } catch (IllegalArgumentException e) {
675 // Failed to parse the settings string, log this and move on
676 // with defaults.
677 Slog.e(TAG, "Bad alarm manager settings", e);
678 }
679
680 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
681 DEFAULT_NO_CACHED_WAKE_LOCKS);
682 }
683 }
684
685 void dump(PrintWriter pw) {
686 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
687
688 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
689 pw.println(NO_CACHED_WAKE_LOCKS);
690 }
Netta P958d0a52017-02-07 11:20:55 -0800691
692 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700693 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
694 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800695 NO_CACHED_WAKE_LOCKS);
696 proto.end(constantsToken);
697 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800698 }
699
Santos Cordon64a6e612018-08-22 19:27:04 +0100700 /**
701 * Wrapper around the static-native methods of PowerManagerService.
702 *
703 * This class exists to allow us to mock static native methods in our tests. If mocking static
704 * methods becomes easier than this in the future, we can delete this class.
705 */
706 @VisibleForTesting
707 public static class NativeWrapper {
708 /** Wrapper for PowerManager.nativeInit */
709 public void nativeInit(PowerManagerService service) {
710 service.nativeInit();
711 }
712
713 /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
714 public void nativeAcquireSuspendBlocker(String name) {
715 PowerManagerService.nativeAcquireSuspendBlocker(name);
716 }
717
718 /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
719 public void nativeReleaseSuspendBlocker(String name) {
720 PowerManagerService.nativeReleaseSuspendBlocker(name);
721 }
722
723 /** Wrapper for PowerManager.nativeSetInteractive */
724 public void nativeSetInteractive(boolean enable) {
725 PowerManagerService.nativeSetInteractive(enable);
726 }
727
728 /** Wrapper for PowerManager.nativeSetAutoSuspend */
729 public void nativeSetAutoSuspend(boolean enable) {
730 PowerManagerService.nativeSetAutoSuspend(enable);
731 }
732
733 /** Wrapper for PowerManager.nativeSendPowerHint */
734 public void nativeSendPowerHint(int hintId, int data) {
735 PowerManagerService.nativeSendPowerHint(hintId, data);
736 }
737
738 /** Wrapper for PowerManager.nativeSetFeature */
739 public void nativeSetFeature(int featureId, int data) {
740 PowerManagerService.nativeSetFeature(featureId, data);
741 }
Santos Cordon12f92eb2019-02-01 21:28:47 +0000742
743 /** Wrapper for PowerManager.nativeForceSuspend */
744 public boolean nativeForceSuspend() {
745 return PowerManagerService.nativeForceSuspend();
746 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100747 }
748
749 @VisibleForTesting
750 static class Injector {
751 Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
752 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
753 return new Notifier(looper, context, batteryStats, suspendBlocker, policy);
754 }
755
756 SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
757 SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
758 service.mSuspendBlockers.add(suspendBlocker);
759 return suspendBlocker;
760 }
761
762 BatterySaverPolicy createBatterySaverPolicy(
763 Object lock, Context context, BatterySavingStats batterySavingStats) {
764 return new BatterySaverPolicy(lock, context, batterySavingStats);
765 }
766
767 NativeWrapper createNativeWrapper() {
768 return new NativeWrapper();
769 }
Santos Cordon9b510a22018-08-24 16:42:54 +0100770
771 WirelessChargerDetector createWirelessChargerDetector(
772 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
773 return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
774 }
775
776 AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
777 return new AmbientDisplayConfiguration(context);
778 }
Robert Horvath5560f382019-07-10 10:46:38 +0200779
780 InattentiveSleepWarningController createInattentiveSleepWarningController() {
781 return new InattentiveSleepWarningController();
782 }
Robert Horvath84a67c62019-11-29 15:31:30 +0100783
784 public SystemPropertiesWrapper createSystemPropertiesWrapper() {
785 return new SystemPropertiesWrapper() {
786 @Override
787 public String get(String key, String def) {
788 return SystemProperties.get(key, def);
789 }
790
791 @Override
792 public void set(String key, String val) {
793 SystemProperties.set(key, val);
794 }
795 };
796 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100797 }
798
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800799 final Constants mConstants;
800
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700801 private native void nativeInit();
Jeff Brown96307042012-07-27 15:51:34 -0700802 private static native void nativeAcquireSuspendBlocker(String name);
803 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700804 private static native void nativeSetInteractive(boolean enable);
805 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700806 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400807 private static native void nativeSetFeature(int featureId, int data);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000808 private static native boolean nativeForceSuspend();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800809
Jeff Brownb880d882014-02-10 19:47:07 -0800810 public PowerManagerService(Context context) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100811 this(context, new Injector());
812 }
813
814 @VisibleForTesting
815 PowerManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800816 super(context);
Santos Cordon64a6e612018-08-22 19:27:04 +0100817
Jeff Brownb880d882014-02-10 19:47:07 -0800818 mContext = context;
Santos Cordon64a6e612018-08-22 19:27:04 +0100819 mBinderService = new BinderService();
820 mLocalService = new LocalService();
821 mNativeWrapper = injector.createNativeWrapper();
Robert Horvath84a67c62019-11-29 15:31:30 +0100822 mSystemProperties = injector.createSystemPropertiesWrapper();
Santos Cordon64a6e612018-08-22 19:27:04 +0100823 mInjector = injector;
824
Jeff Brown2c43c332014-06-12 22:38:59 -0700825 mHandlerThread = new ServiceThread(TAG,
826 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
827 mHandlerThread.start();
828 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800829 mConstants = new Constants(mHandler);
Santos Cordon9b510a22018-08-24 16:42:54 +0100830 mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800831 mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800832
Makoto Onukibd7a6252018-05-10 13:41:39 -0700833 mBatterySavingStats = new BatterySavingStats(mLock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100834 mBatterySaverPolicy =
835 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700836 mBatterySaverController = new BatterySaverController(mLock, mContext,
Santos Cordon64a6e612018-08-22 19:27:04 +0100837 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
838 mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700839 mBatterySaverStateMachine = new BatterySaverStateMachine(
840 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700841
Robert Horvath5560f382019-07-10 10:46:38 +0200842 mInattentiveSleepWarningOverlayController =
843 mInjector.createInattentiveSleepWarningController();
844
Fiona Campbelld4eb2952019-11-04 17:19:56 +0000845 // Save brightness values:
846 // Get float values from config.
847 // Store float if valid
848 // Otherwise, get int values and convert to float and then store.
849 final float min = mContext.getResources().getFloat(com.android.internal.R.dimen
850 .config_screenBrightnessSettingMinimumFloat);
851 final float max = mContext.getResources().getFloat(com.android.internal.R.dimen
852 .config_screenBrightnessSettingMaximumFloat);
853 final float def = mContext.getResources().getFloat(com.android.internal.R.dimen
854 .config_screenBrightnessSettingDefaultFloat);
855 final float doze = mContext.getResources().getFloat(com.android.internal.R.dimen
856 .config_screenBrightnessDozeFloat);
857 final float dim = mContext.getResources().getFloat(com.android.internal.R.dimen
858 .config_screenBrightnessDimFloat);
859
860 if (min == INVALID_BRIGHTNESS_IN_CONFIG || max == INVALID_BRIGHTNESS_IN_CONFIG
861 || def == INVALID_BRIGHTNESS_IN_CONFIG) {
862 mScreenBrightnessMinimum = BrightnessSynchronizer.brightnessIntToFloat(
863 mContext.getResources().getInteger(com.android.internal.R.integer
864 .config_screenBrightnessSettingMinimum),
865 PowerManager.BRIGHTNESS_OFF + 1, PowerManager.BRIGHTNESS_ON,
866 PowerManager.BRIGHTNESS_MIN, PowerManager.BRIGHTNESS_MAX);
867 mScreenBrightnessMaximum = BrightnessSynchronizer.brightnessIntToFloat(
868 mContext.getResources().getInteger(com.android.internal.R.integer
869 .config_screenBrightnessSettingMaximum),
870 PowerManager.BRIGHTNESS_OFF + 1, PowerManager.BRIGHTNESS_ON,
871 PowerManager.BRIGHTNESS_MIN, PowerManager.BRIGHTNESS_MAX);
872 mScreenBrightnessDefault = BrightnessSynchronizer.brightnessIntToFloat(
873 mContext.getResources().getInteger(com.android.internal.R.integer
874 .config_screenBrightnessSettingDefault),
875 PowerManager.BRIGHTNESS_OFF + 1, PowerManager.BRIGHTNESS_ON,
876 PowerManager.BRIGHTNESS_MIN, PowerManager.BRIGHTNESS_MAX);
877 } else {
878 mScreenBrightnessMinimum = min;
879 mScreenBrightnessMaximum = max;
880 mScreenBrightnessDefault = def;
881 }
882 if (doze == INVALID_BRIGHTNESS_IN_CONFIG) {
883 mScreenBrightnessDoze = BrightnessSynchronizer.brightnessIntToFloat(
884 mContext.getResources().getInteger(com.android.internal.R.integer
885 .config_screenBrightnessDoze), PowerManager.BRIGHTNESS_OFF + 1,
886 PowerManager.BRIGHTNESS_ON, PowerManager.BRIGHTNESS_MIN,
887 PowerManager.BRIGHTNESS_MAX);
888 } else {
889 mScreenBrightnessDoze = doze;
890 }
891 if (dim == INVALID_BRIGHTNESS_IN_CONFIG) {
892 mScreenBrightnessDim = BrightnessSynchronizer.brightnessIntToFloat(
893 mContext.getResources().getInteger(com.android.internal.R.integer
894 .config_screenBrightnessDim), PowerManager.BRIGHTNESS_OFF + 1,
895 PowerManager.BRIGHTNESS_ON, PowerManager.BRIGHTNESS_MIN,
896 PowerManager.BRIGHTNESS_MAX);
897 } else {
898 mScreenBrightnessDim = dim;
899 }
900
901 final float vrMin = mContext.getResources().getFloat(com.android.internal.R.dimen
902 .config_screenBrightnessSettingForVrMinimumFloat);
903 final float vrMax = mContext.getResources().getFloat(com.android.internal.R.dimen
904 .config_screenBrightnessSettingForVrMaximumFloat);
905 final float vrDef = mContext.getResources().getFloat(com.android.internal.R.dimen
906 .config_screenBrightnessSettingForVrDefaultFloat);
907 if (vrMin == INVALID_BRIGHTNESS_IN_CONFIG || vrMax == INVALID_BRIGHTNESS_IN_CONFIG
908 || vrDef == INVALID_BRIGHTNESS_IN_CONFIG) {
909 mScreenBrightnessMinimumVr = BrightnessSynchronizer.brightnessIntToFloat(
910 mContext.getResources().getInteger(com.android.internal.R.integer
911 .config_screenBrightnessForVrSettingMinimum),
912 PowerManager.BRIGHTNESS_OFF + 1, PowerManager.BRIGHTNESS_ON,
913 PowerManager.BRIGHTNESS_MIN, PowerManager.BRIGHTNESS_MAX);
914 mScreenBrightnessMaximumVr = BrightnessSynchronizer.brightnessIntToFloat(
915 mContext.getResources().getInteger(com.android.internal.R.integer
916 .config_screenBrightnessForVrSettingMaximum),
917 PowerManager.BRIGHTNESS_OFF + 1, PowerManager.BRIGHTNESS_ON,
918 PowerManager.BRIGHTNESS_MIN, PowerManager.BRIGHTNESS_MAX);
919 mScreenBrightnessDefaultVr = BrightnessSynchronizer.brightnessIntToFloat(
920 mContext.getResources().getInteger(com.android.internal.R.integer
921 .config_screenBrightnessForVrSettingDefault),
922 PowerManager.BRIGHTNESS_OFF + 1, PowerManager.BRIGHTNESS_ON,
923 PowerManager.BRIGHTNESS_MIN, PowerManager.BRIGHTNESS_MAX);
924 } else {
925 mScreenBrightnessMinimumVr = vrMin;
926 mScreenBrightnessMaximumVr = vrMax;
927 mScreenBrightnessDefaultVr = vrDef;
928 }
929
Jeff Brown96307042012-07-27 15:51:34 -0700930 synchronized (mLock) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100931 mWakeLockSuspendBlocker =
932 mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
933 mDisplaySuspendBlocker =
934 mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
935 if (mDisplaySuspendBlocker != null) {
936 mDisplaySuspendBlocker.acquire();
937 mHoldingDisplaySuspendBlocker = true;
938 }
Jeff Brown037c33e2014-04-09 00:31:55 -0700939 mHalAutoSuspendModeEnabled = false;
940 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800941
Jeff Brown96307042012-07-27 15:51:34 -0700942 mWakefulness = WAKEFULNESS_AWAKE;
Robert Horvath84a67c62019-11-29 15:31:30 +0100943 sQuiescent = mSystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800944
Santos Cordon64a6e612018-08-22 19:27:04 +0100945 mNativeWrapper.nativeInit(this);
946 mNativeWrapper.nativeSetAutoSuspend(false);
947 mNativeWrapper.nativeSetInteractive(true);
948 mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800950 }
951
Jeff Brown6f357d32014-01-15 20:40:55 -0800952 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800953 public void onStart() {
Chris Ye73b85a62020-01-18 10:11:26 -0800954 publishBinderService(Context.POWER_SERVICE, mBinderService, /* allowIsolated= */ false,
955 DUMP_FLAG_PRIORITY_DEFAULT | DUMP_FLAG_PRIORITY_CRITICAL);
Santos Cordon64a6e612018-08-22 19:27:04 +0100956 publishLocalService(PowerManagerInternal.class, mLocalService);
Jeff Brown9e316a12012-10-08 19:17:06 -0700957
958 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800959 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700960 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800961
Jeff Brown6d2a9492014-08-07 19:06:49 -0700962 @Override
963 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700964 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600965 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
966 incrementBootCount();
967
968 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700969 final long now = SystemClock.uptimeMillis();
970 mBootCompleted = true;
971 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700972
973 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700974 userActivityNoUpdateLocked(
975 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Robert Horvath4fbab202019-11-29 15:36:39 +0100976
977 if (sQuiescent) {
978 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
979 PowerManager.GO_TO_SLEEP_REASON_QUIESCENT,
980 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, Process.SYSTEM_UID);
981 }
Craig Mautner6e2f3952014-09-09 14:26:41 -0700982 updatePowerStateLocked();
983 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700984 }
985 }
986
Jeff Brown21392762014-06-13 19:00:36 -0700987 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700988 synchronized (mLock) {
989 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700990 mAppOps = appOps;
991 mDreamManager = getLocalService(DreamManagerInternal.class);
992 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
993 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700994 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800995 mAttentionDetector.systemReady(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996
Adam Lesinski182f73f2013-12-05 16:48:06 -0800997 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Fiona Campbelld4eb2952019-11-04 17:19:56 +0000998 mScreenBrightnessSettingMinimum = pm.getBrightnessConstraint(
999 PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM);
1000 mScreenBrightnessSettingMaximum = pm.getBrightnessConstraint(
1001 PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM);
1002 mScreenBrightnessSettingDefault = pm.getBrightnessConstraint(
1003 PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -07001005 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -08001006
Jeff Brownc38c9be2012-10-04 13:16:19 -07001007 // The notifier runs on the system server's main looper so as not to interfere
1008 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -07001009 mBatteryStats = BatteryStatsService.getService();
Santos Cordon64a6e612018-08-22 19:27:04 +01001010 mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
1011 mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
1012 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -07001013
Santos Cordon9b510a22018-08-24 16:42:54 +01001014 mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
Santos Cordon64a6e612018-08-22 19:27:04 +01001015 mInjector.createSuspendBlocker(
1016 this, "PowerManagerService.WirelessChargerDetector"),
Jeff Browndbcc8a22013-10-01 16:16:44 -07001017 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -07001018 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -07001019
1020 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001021 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -04001022
Jeff Brown131206b2014-04-08 17:27:14 -07001023 // Initialize display power management.
1024 mDisplayManagerInternal.initPowerManagement(
1025 mDisplayPowerCallbacks, mHandler, sensorManager);
1026
Pavel Grafov28939982017-10-03 15:11:52 +01001027 try {
1028 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
1029 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
1030 } catch (RemoteException e) {
1031 // Shouldn't happen since in-process.
1032 }
Makoto Onuki66a78122017-11-14 15:03:21 -08001033
Jeff Brown96307042012-07-27 15:51:34 -07001034 // Go.
1035 readConfigurationLocked();
1036 updateSettingsLocked();
1037 mDirty |= DIRTY_BATTERY_STATE;
1038 updatePowerStateLocked();
1039 }
Shibin George43f5de02016-07-06 02:12:10 +05301040
Jeff Sharkey6e544612017-02-20 11:02:26 -07001041 final ContentResolver resolver = mContext.getContentResolver();
1042 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -08001043
1044 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -07001045 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -07001046
1047 // Register for settings changes.
1048 resolver.registerContentObserver(Settings.Secure.getUriFor(
1049 Settings.Secure.SCREENSAVER_ENABLED),
1050 false, mSettingsObserver, UserHandle.USER_ALL);
1051 resolver.registerContentObserver(Settings.Secure.getUriFor(
1052 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
1053 false, mSettingsObserver, UserHandle.USER_ALL);
1054 resolver.registerContentObserver(Settings.Secure.getUriFor(
1055 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
1056 false, mSettingsObserver, UserHandle.USER_ALL);
1057 resolver.registerContentObserver(Settings.System.getUriFor(
1058 Settings.System.SCREEN_OFF_TIMEOUT),
1059 false, mSettingsObserver, UserHandle.USER_ALL);
1060 resolver.registerContentObserver(Settings.Secure.getUriFor(
1061 Settings.Secure.SLEEP_TIMEOUT),
1062 false, mSettingsObserver, UserHandle.USER_ALL);
Robert Horvath5560f382019-07-10 10:46:38 +02001063 resolver.registerContentObserver(Settings.Secure.getUriFor(
1064 Settings.Secure.ATTENTIVE_TIMEOUT),
1065 false, mSettingsObserver, UserHandle.USER_ALL);
Jeff Sharkey6e544612017-02-20 11:02:26 -07001066 resolver.registerContentObserver(Settings.Global.getUriFor(
1067 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
1068 false, mSettingsObserver, UserHandle.USER_ALL);
1069 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -07001070 Settings.System.SCREEN_BRIGHTNESS_MODE),
1071 false, mSettingsObserver, UserHandle.USER_ALL);
1072 resolver.registerContentObserver(Settings.System.getUriFor(
1073 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
1074 false, mSettingsObserver, UserHandle.USER_ALL);
1075 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -07001076 Settings.Global.THEATER_MODE_ON),
1077 false, mSettingsObserver, UserHandle.USER_ALL);
1078 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +01001079 Settings.Secure.DOZE_ALWAYS_ON),
1080 false, mSettingsObserver, UserHandle.USER_ALL);
1081 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -07001082 Settings.Secure.DOUBLE_TAP_TO_WAKE),
1083 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -07001084 resolver.registerContentObserver(Settings.Global.getUriFor(
1085 Settings.Global.DEVICE_DEMO_MODE),
1086 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Santos Cordon64a6e612018-08-22 19:27:04 +01001087 IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
Jeff Sharkey6e544612017-02-20 11:02:26 -07001088 if (vrManager != null) {
1089 try {
1090 vrManager.registerListener(mVrStateCallbacks);
1091 } catch (RemoteException e) {
1092 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
1093 }
1094 }
1095
Shibin George43f5de02016-07-06 02:12:10 +05301096 // Register for broadcasts from other components of the system.
1097 IntentFilter filter = new IntentFilter();
1098 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
1099 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
1100 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
1101
1102 filter = new IntentFilter();
1103 filter.addAction(Intent.ACTION_DREAMING_STARTED);
1104 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
1105 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
1106
1107 filter = new IntentFilter();
1108 filter.addAction(Intent.ACTION_USER_SWITCHED);
1109 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
1110
1111 filter = new IntentFilter();
1112 filter.addAction(Intent.ACTION_DOCK_EVENT);
1113 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -07001114 }
1115
Santos Cordon9b510a22018-08-24 16:42:54 +01001116 @VisibleForTesting
1117 void readConfigurationLocked() {
Jeff Brown96307042012-07-27 15:51:34 -07001118 final Resources resources = mContext.getResources();
1119
Jeff Brown037c33e2014-04-09 00:31:55 -07001120 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -08001121 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -07001122 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -08001123 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -07001124 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -07001125 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -07001126 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
1127 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -07001128 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
1129 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Robert Horvath5560f382019-07-10 10:46:38 +02001130 mAttentiveTimeoutConfig = resources.getInteger(
1131 com.android.internal.R.integer.config_attentiveTimeout);
1132 mAttentiveWarningDurationConfig = resources.getInteger(
1133 com.android.internal.R.integer.config_attentiveWarningDuration);
Jeff Brown96307042012-07-27 15:51:34 -07001134 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -04001135 com.android.internal.R.bool.config_dreamsSupported);
1136 mDreamsEnabledByDefaultConfig = resources.getBoolean(
1137 com.android.internal.R.bool.config_dreamsEnabledByDefault);
1138 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
1139 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
1140 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
1141 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -08001142 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
1143 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
1144 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
1145 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
1146 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
1147 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
1148 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
1149 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -08001150 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -07001151 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -07001152 mMinimumScreenOffTimeoutConfig = resources.getInteger(
1153 com.android.internal.R.integer.config_minimumScreenOffTimeout);
1154 mMaximumScreenDimDurationConfig = resources.getInteger(
1155 com.android.internal.R.integer.config_maximumScreenDimDuration);
1156 mMaximumScreenDimRatioConfig = resources.getFraction(
1157 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001158 mSupportsDoubleTapWakeConfig = resources.getBoolean(
1159 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
1161
Jeff Brown96307042012-07-27 15:51:34 -07001162 private void updateSettingsLocked() {
1163 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -07001164
Jeff Brownd4935962012-09-25 13:27:20 -07001165 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001166 Settings.Secure.SCREENSAVER_ENABLED,
1167 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001168 UserHandle.USER_CURRENT) != 0);
1169 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001170 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
1171 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001172 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -07001173 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001174 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1175 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -07001176 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -07001177 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1178 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1179 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -07001180 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1181 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1182 UserHandle.USER_CURRENT);
Robert Horvath5560f382019-07-10 10:46:38 +02001183 mAttentiveTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1184 Settings.Secure.ATTENTIVE_TIMEOUT, mAttentiveTimeoutConfig,
1185 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -07001186 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -07001187 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -07001188 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1189 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +01001190 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -07001191
Jason Monk27bbb2d2015-03-31 16:46:39 -04001192 if (mSupportsDoubleTapWakeConfig) {
1193 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1194 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1195 UserHandle.USER_CURRENT) != 0;
1196 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1197 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
Santos Cordon64a6e612018-08-22 19:27:04 +01001198 mNativeWrapper.nativeSetFeature(
1199 POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001200 }
1201 }
1202
Christine Franks732c0432017-06-23 18:12:46 -07001203 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
Robert Horvath84a67c62019-11-29 15:31:30 +01001204 if (!retailDemoValue.equals(
1205 mSystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, null))) {
1206 mSystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
Christine Franks732c0432017-06-23 18:12:46 -07001207 }
1208
Jeff Brownd4935962012-09-25 13:27:20 -07001209 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -07001210 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -07001211 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -07001212
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001213 mDirty |= DIRTY_SETTINGS;
1214 }
1215
Jeff Brown96307042012-07-27 15:51:34 -07001216 private void handleSettingsChangedLocked() {
1217 updateSettingsLocked();
1218 updatePowerStateLocked();
1219 }
1220
Dianne Hackborn713df152013-05-17 11:27:57 -07001221 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001222 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001223 synchronized (mLock) {
1224 if (DEBUG_SPEW) {
1225 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1226 + ", flags=0x" + Integer.toHexString(flags)
1227 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229
Jeff Brown96307042012-07-27 15:51:34 -07001230 WakeLock wakeLock;
1231 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001232 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001233 if (index >= 0) {
1234 wakeLock = mWakeLocks.get(index);
1235 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1236 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001237 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1238 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001239 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001241 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001243 UidState state = mUidState.get(uid);
1244 if (state == null) {
1245 state = new UidState(uid);
1246 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1247 mUidState.put(uid, state);
1248 }
1249 state.mNumWakeLocks++;
1250 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1251 state);
Jeff Brown96307042012-07-27 15:51:34 -07001252 try {
1253 lock.linkToDeath(wakeLock, 0);
1254 } catch (RemoteException ex) {
1255 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 }
Jeff Brown96307042012-07-27 15:51:34 -07001257 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001258 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001259 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261
Jeff Brownc12035c2014-08-13 18:52:25 -07001262 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001263 mDirty |= DIRTY_WAKE_LOCKS;
1264 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001265 if (notifyAcquire) {
1266 // This needs to be done last so we are sure we have acquired the
1267 // kernel wake lock. Otherwise we have a race where the system may
1268 // go to sleep between the time we start the accounting in battery
1269 // stats and when we actually get around to telling the kernel to
1270 // stay awake.
1271 notifyWakeLockAcquiredLocked(wakeLock);
1272 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001273 }
1274 }
1275
Jeff Brownec083212013-09-11 20:45:25 -07001276 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001277 private static boolean isScreenLock(final WakeLock wakeLock) {
1278 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1279 case PowerManager.FULL_WAKE_LOCK:
1280 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1281 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1282 return true;
1283 }
1284 return false;
1285 }
1286
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001287 private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1288 if (workSource.getWorkChains() == null) {
1289 return null;
1290 }
1291
1292 for (WorkChain workChain: workSource.getWorkChains()) {
1293 if (workChain.getSize() > 0) {
1294 return workChain;
1295 }
1296 }
1297
1298 return null;
1299 }
1300
Jeff Brownc12035c2014-08-13 18:52:25 -07001301 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001302 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1303 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001304 String opPackageName;
1305 int opUid;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001306 if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1307 WorkSource workSource = wakeLock.mWorkSource;
1308 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1309 if (workChain != null) {
1310 opPackageName = workChain.getAttributionTag();
1311 opUid = workChain.getAttributionUid();
1312 } else {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08001313 opPackageName = workSource.getPackageName(0) != null
1314 ? workSource.getPackageName(0) : wakeLock.mPackageName;
1315 opUid = workSource.getUid(0);
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001316 }
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001317 } else {
1318 opPackageName = wakeLock.mPackageName;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001319 opUid = wakeLock.mOwnerUid;
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001320 }
Michael Wrighte3001042019-02-05 00:13:14 +00001321 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1322 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1323 opUid, opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325 }
1326
Jeff Brown96307042012-07-27 15:51:34 -07001327 private void releaseWakeLockInternal(IBinder lock, int flags) {
1328 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001329 int index = findWakeLockIndexLocked(lock);
1330 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001331 if (DEBUG_SPEW) {
1332 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1333 + " [not found], flags=0x" + Integer.toHexString(flags));
1334 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 return;
1336 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001337
Jeff Brown96307042012-07-27 15:51:34 -07001338 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001339 if (DEBUG_SPEW) {
1340 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1341 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1342 }
1343
Michael Wright1208e272014-09-08 19:57:50 -07001344 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001345 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
1347
Jeff Brown3edf5272014-08-14 19:25:14 -07001348 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1349 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001352
Jeff Brown96307042012-07-27 15:51:34 -07001353 private void handleWakeLockDeath(WakeLock wakeLock) {
1354 synchronized (mLock) {
1355 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001356 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1357 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001358 }
1359
1360 int index = mWakeLocks.indexOf(wakeLock);
1361 if (index < 0) {
1362 return;
1363 }
1364
Jeff Brown3edf5272014-08-14 19:25:14 -07001365 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001366 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001367 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001368
Jeff Brown3edf5272014-08-14 19:25:14 -07001369 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1370 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001371 UidState state = wakeLock.mUidState;
1372 state.mNumWakeLocks--;
1373 if (state.mNumWakeLocks <= 0 &&
1374 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1375 mUidState.remove(state.mUid);
1376 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001377 notifyWakeLockReleasedLocked(wakeLock);
1378
1379 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1380 mDirty |= DIRTY_WAKE_LOCKS;
1381 updatePowerStateLocked();
1382 }
1383
Jeff Brown96307042012-07-27 15:51:34 -07001384 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001385 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1386 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001387 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1388 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1389 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1390 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 }
1393
Dianne Hackbornd953c532014-08-16 18:17:38 -07001394 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1395 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001396 synchronized (mLock) {
1397 int index = findWakeLockIndexLocked(lock);
1398 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001399 if (DEBUG_SPEW) {
1400 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1401 + " [not found], ws=" + ws);
1402 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001403 throw new IllegalArgumentException("Wake lock not active: " + lock
1404 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001405 }
1406
1407 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001408 if (DEBUG_SPEW) {
1409 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1410 + " [" + wakeLock.mTag + "], ws=" + ws);
1411 }
1412
Jeff Brown96307042012-07-27 15:51:34 -07001413 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001414 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1415 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001416 ws, historyTag);
1417 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001418 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001419 }
1420 }
1421 }
1422
1423 private int findWakeLockIndexLocked(IBinder lock) {
1424 final int count = mWakeLocks.size();
1425 for (int i = 0; i < count; i++) {
1426 if (mWakeLocks.get(i).mLock == lock) {
1427 return i;
1428 }
1429 }
1430 return -1;
1431 }
1432
1433 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001434 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001435 wakeLock.mNotifiedAcquired = true;
1436 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001437 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1438 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001439 restartNofifyLongTimerLocked(wakeLock);
1440 }
1441 }
1442
1443 private void enqueueNotifyLongMsgLocked(long time) {
1444 mNotifyLongScheduled = time;
1445 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1446 msg.setAsynchronous(true);
1447 mHandler.sendMessageAtTime(msg, time);
1448 }
1449
1450 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1451 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1452 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1453 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1454 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1455 }
1456 }
1457
1458 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1459 if (mSystemReady && !wakeLock.mDisabled) {
1460 wakeLock.mNotifiedLong = true;
1461 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1462 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1463 }
1464 }
1465
1466 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1467 if (wakeLock.mNotifiedLong) {
1468 wakeLock.mNotifiedLong = false;
1469 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1470 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001471 }
1472 }
1473
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001474 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1475 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1476 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1477 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1478 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1479 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001480 notifyWakeLockLongFinishedLocked(wakeLock);
1481 // Changing the wake lock will count as releasing the old wake lock(s) and
1482 // acquiring the new ones... we do this because otherwise once a wakelock
1483 // becomes long, if we just continued to treat it as long we can get in to
1484 // situations where we spam battery stats with every following change to it.
1485 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001486 }
1487 }
1488
Jeff Brown96307042012-07-27 15:51:34 -07001489 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001490 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1491 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001492 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001493 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1494 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1495 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001496 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001497 }
1498 }
1499
Jeff Brownec083212013-09-11 20:45:25 -07001500 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001501 private boolean isWakeLockLevelSupportedInternal(int level) {
1502 synchronized (mLock) {
1503 switch (level) {
1504 case PowerManager.PARTIAL_WAKE_LOCK:
1505 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1506 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1507 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001508 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001509 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001510 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001511
1512 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001513 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001514
1515 default:
1516 return false;
1517 }
1518 }
1519 }
1520
Jeff Brown96307042012-07-27 15:51:34 -07001521 // Called from native code.
1522 private void userActivityFromNative(long eventTime, int event, int flags) {
1523 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1524 }
1525
1526 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1527 synchronized (mLock) {
1528 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1529 updatePowerStateLocked();
1530 }
1531 }
1532 }
1533
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001534 private void onUserAttention() {
1535 synchronized (mLock) {
1536 if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1537 PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1538 Process.SYSTEM_UID)) {
1539 updatePowerStateLocked();
1540 }
1541 }
1542 }
1543
Jeff Brown96307042012-07-27 15:51:34 -07001544 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1545 if (DEBUG_SPEW) {
1546 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1547 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1548 + ", uid=" + uid);
1549 }
1550
Robert Horvath4fbab202019-11-29 15:36:39 +01001551 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001552 return false;
1553 }
1554
Jeff Brown3edf5272014-08-14 19:25:14 -07001555 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1556 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001557 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001558 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001559 mLastInteractivePowerHintTime = eventTime;
1560 }
1561
Jeff Brown3edf5272014-08-14 19:25:14 -07001562 mNotifier.onUserActivity(event, uid);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001563 mAttentionDetector.onUserActivity(eventTime, event);
Jeff Brown96307042012-07-27 15:51:34 -07001564
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001565 if (mUserInactiveOverrideFromWindowManager) {
1566 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001567 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001568 }
1569
Jeff Brown0a571122014-08-21 21:50:43 -07001570 if (mWakefulness == WAKEFULNESS_ASLEEP
1571 || mWakefulness == WAKEFULNESS_DOZING
1572 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1573 return false;
1574 }
1575
Pavel Grafov28939982017-10-03 15:11:52 +01001576 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1577
Jeff Brown3edf5272014-08-14 19:25:14 -07001578 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1579 if (eventTime > mLastUserActivityTimeNoChangeLights
1580 && eventTime > mLastUserActivityTime) {
1581 mLastUserActivityTimeNoChangeLights = eventTime;
1582 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001583 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1584 mDirty |= DIRTY_QUIESCENT;
1585 }
1586
Jeff Brown3edf5272014-08-14 19:25:14 -07001587 return true;
1588 }
1589 } else {
1590 if (eventTime > mLastUserActivityTime) {
1591 mLastUserActivityTime = eventTime;
1592 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001593 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1594 mDirty |= DIRTY_QUIESCENT;
1595 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001596 return true;
1597 }
Jeff Brown96307042012-07-27 15:51:34 -07001598 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001599 } finally {
1600 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001601 }
1602 return false;
1603 }
1604
Pavel Grafov28939982017-10-03 15:11:52 +01001605 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1606 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1607 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1608 profile.mLastUserActivityTime = eventTime;
1609 }
1610 }
1611
Michael Wrighte3001042019-02-05 00:13:14 +00001612 private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1613 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001614 synchronized (mLock) {
Michael Wrighte3001042019-02-05 00:13:14 +00001615 if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001616 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001617 }
1618 }
Jeff Brown96307042012-07-27 15:51:34 -07001619 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001620
Michael Wrighte3001042019-02-05 00:13:14 +00001621 private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1622 int reasonUid, String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001623 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001624 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001625 }
Jeff Brown96307042012-07-27 15:51:34 -07001626
1627 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
Robert Horvath4fbab202019-11-29 15:36:39 +01001628 || mForceSuspendActive || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001629 return false;
1630 }
1631
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001632 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1633
Jeff Brown3edf5272014-08-14 19:25:14 -07001634 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1635 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001636 Slog.i(TAG, "Waking up from "
1637 + PowerManagerInternal.wakefulnessToString(mWakefulness)
1638 + " (uid=" + reasonUid
1639 + ", reason=" + PowerManager.wakeReasonToString(reason)
1640 + ", details=" + details
1641 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001642
1643 mLastWakeTime = eventTime;
Michael Wrighte3001042019-02-05 00:13:14 +00001644 mLastWakeReason = reason;
1645 setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001646
Michael Wrighte3001042019-02-05 00:13:14 +00001647 mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001648 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001649 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Robert Horvath4fbab202019-11-29 15:36:39 +01001650
1651 if (sQuiescent) {
1652 mDirty |= DIRTY_QUIESCENT;
1653 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001654 } finally {
1655 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001656 }
Jeff Brown96307042012-07-27 15:51:34 -07001657 return true;
1658 }
1659
Jeff Brownc12035c2014-08-13 18:52:25 -07001660 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001661 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001662 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001663 updatePowerStateLocked();
1664 }
1665 }
1666 }
1667
Santos Cordon12f92eb2019-02-01 21:28:47 +00001668 /**
1669 * Puts the system in doze.
1670 *
1671 * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1672 * and only tucks itself in to SLEEP if requested with the flag
1673 * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1674 */
Jeff Brownec083212013-09-11 20:45:25 -07001675 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001676 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001677 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001678 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001679 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001680 }
1681
Jeff Brown26875502014-01-30 21:47:47 -08001682 if (eventTime < mLastWakeTime
1683 || mWakefulness == WAKEFULNESS_ASLEEP
1684 || mWakefulness == WAKEFULNESS_DOZING
Robert Horvath4fbab202019-11-29 15:36:39 +01001685 || !mSystemReady
1686 || !mBootCompleted) {
Jeff Brown96307042012-07-27 15:51:34 -07001687 return false;
1688 }
1689
Jeff Brown3edf5272014-08-14 19:25:14 -07001690 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1691 try {
Santos Cordon12f92eb2019-02-01 21:28:47 +00001692 reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1693 Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1694 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1695 + " (uid " + uid + ")...");
Jeff Brown6d8fd272014-05-20 21:24:38 -07001696
Jeff Brown3edf5272014-08-14 19:25:14 -07001697 mLastSleepTime = eventTime;
Calin Tatarua3805722018-08-09 16:41:28 +02001698 mLastSleepReason = reason;
Jeff Brown3edf5272014-08-14 19:25:14 -07001699 mSandmanSummoned = true;
Santos Cordon03044382019-09-19 16:59:01 +01001700 mDozeStartInProgress = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001701 setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001702
1703 // Report the number of wake locks that will be cleared by going to sleep.
1704 int numWakeLocksCleared = 0;
1705 final int numWakeLocks = mWakeLocks.size();
1706 for (int i = 0; i < numWakeLocks; i++) {
1707 final WakeLock wakeLock = mWakeLocks.get(i);
1708 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1709 case PowerManager.FULL_WAKE_LOCK:
1710 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1711 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1712 numWakeLocksCleared += 1;
1713 break;
1714 }
1715 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001716 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001717
1718 // Skip dozing if requested.
1719 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1720 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1721 }
1722 } finally {
1723 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001724 }
Jeff Brown96307042012-07-27 15:51:34 -07001725 return true;
1726 }
1727
Jeff Brownc12035c2014-08-13 18:52:25 -07001728 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001729 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001730 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001731 updatePowerStateLocked();
1732 }
1733 }
1734 }
1735
Jeff Brownc12035c2014-08-13 18:52:25 -07001736 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001737 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001738 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001739 }
1740
1741 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1742 || !mBootCompleted || !mSystemReady) {
1743 return false;
1744 }
1745
Jeff Brown3edf5272014-08-14 19:25:14 -07001746 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1747 try {
1748 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001749
Jeff Brown3edf5272014-08-14 19:25:14 -07001750 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001751 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001752 } finally {
1753 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1754 }
Jeff Brown26875502014-01-30 21:47:47 -08001755 return true;
1756 }
1757
1758 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001759 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001760 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001761 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1762 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001763 }
1764
1765 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1766 || !mBootCompleted || !mSystemReady) {
1767 return false;
1768 }
1769
Jeff Brown3edf5272014-08-14 19:25:14 -07001770 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1771 try {
1772 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001773
Michael Wrighte3001042019-02-05 00:13:14 +00001774 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1775 eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001776 } finally {
1777 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1778 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001779 return true;
1780 }
1781
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001782 @VisibleForTesting
Michael Wrighte3001042019-02-05 00:13:14 +00001783 void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001784 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001785 mWakefulness = wakefulness;
1786 mWakefulnessChanging = true;
1787 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon03044382019-09-19 16:59:01 +01001788
1789 // This is only valid while we are in wakefulness dozing. Set to false otherwise.
1790 mDozeStartInProgress &= (mWakefulness == WAKEFULNESS_DOZING);
1791
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001792 if (mNotifier != null) {
Michael Wrighte3001042019-02-05 00:13:14 +00001793 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001794 }
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001795 mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
Jeff Brown037c33e2014-04-09 00:31:55 -07001796 }
1797 }
1798
Santos Cordon64a6e612018-08-22 19:27:04 +01001799 @VisibleForTesting
1800 int getWakefulness() {
1801 return mWakefulness;
1802 }
1803
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001804 /**
1805 * Logs the time the device would have spent awake before user activity timeout,
1806 * had the system not been told the user was inactive.
1807 */
1808 private void logSleepTimeoutRecapturedLocked() {
1809 final long now = SystemClock.uptimeMillis();
1810 final long savedWakeTimeMs = mOverriddenTimeout - now;
1811 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001812 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001813 mOverriddenTimeout = -1;
1814 }
1815 }
1816
Jeff Brown416c49c2015-05-26 19:50:18 -07001817 private void finishWakefulnessChangeIfNeededLocked() {
1818 if (mWakefulnessChanging && mDisplayReady) {
1819 if (mWakefulness == WAKEFULNESS_DOZING
1820 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1821 return; // wait until dream has enabled dozing
Santos Cordon03044382019-09-19 16:59:01 +01001822 } else {
1823 // Doze wakelock acquired (doze started) or device is no longer dozing.
1824 mDozeStartInProgress = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001825 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001826 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1827 logSleepTimeoutRecapturedLocked();
1828 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001829 if (mWakefulness == WAKEFULNESS_AWAKE) {
Michael Wrighte3001042019-02-05 00:13:14 +00001830 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1831 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1832 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1833 Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1834 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001835 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001836 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001837 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001838 }
1839 }
1840
Jeff Brown96307042012-07-27 15:51:34 -07001841 /**
1842 * Updates the global power state based on dirty bits recorded in mDirty.
1843 *
1844 * This is the main function that performs power state transitions.
1845 * We centralize them here so that we can recompute the power state completely
1846 * each time something important changes, and ensure that we do it the same
1847 * way each time. The point is to gather all of the transition logic here.
1848 */
1849 private void updatePowerStateLocked() {
1850 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001851 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001853 if (!Thread.holdsLock(mLock)) {
1854 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1855 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001856
Jeff Brown3edf5272014-08-14 19:25:14 -07001857 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1858 try {
1859 // Phase 0: Basic state updates.
1860 updateIsPoweredLocked(mDirty);
1861 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001862 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001863
Jeff Brown3edf5272014-08-14 19:25:14 -07001864 // Phase 1: Update wakefulness.
1865 // Loop because the wake lock and user activity computations are influenced
1866 // by changes in wakefulness.
1867 final long now = SystemClock.uptimeMillis();
1868 int dirtyPhase2 = 0;
1869 for (;;) {
1870 int dirtyPhase1 = mDirty;
1871 dirtyPhase2 |= dirtyPhase1;
1872 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001873
Jeff Brown3edf5272014-08-14 19:25:14 -07001874 updateWakeLockSummaryLocked(dirtyPhase1);
1875 updateUserActivitySummaryLocked(now, dirtyPhase1);
Robert Horvath5560f382019-07-10 10:46:38 +02001876 updateAttentiveStateLocked(now, dirtyPhase1);
Jeff Brown3edf5272014-08-14 19:25:14 -07001877 if (!updateWakefulnessLocked(dirtyPhase1)) {
1878 break;
1879 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001881
Pavel Grafov28939982017-10-03 15:11:52 +01001882 // Phase 2: Lock profiles that became inactive/not kept awake.
1883 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001884
Pavel Grafov28939982017-10-03 15:11:52 +01001885 // Phase 3: Update display power state.
1886 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1887
1888 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001889 updateDreamLocked(dirtyPhase2, displayBecameReady);
1890
Pavel Grafov28939982017-10-03 15:11:52 +01001891 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001892 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001893
Pavel Grafov28939982017-10-03 15:11:52 +01001894 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001895 // Because we might release the last suspend blocker here, we need to make sure
1896 // we finished everything else first!
1897 updateSuspendBlockerLocked();
1898 } finally {
1899 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001900 }
Jeff Brown96307042012-07-27 15:51:34 -07001901 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001902
Jim Miller92e66dd2012-02-21 18:57:12 -08001903 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001904 * Check profile timeouts and notify profiles that should be locked.
1905 */
1906 private void updateProfilesLocked(long now) {
1907 final int numProfiles = mProfilePowerState.size();
1908 for (int i = 0; i < numProfiles; i++) {
1909 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1910 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1911 profile.mLockingNotified = false;
1912 } else if (!profile.mLockingNotified) {
1913 profile.mLockingNotified = true;
1914 mNotifier.onProfileTimeout(profile.mUserId);
1915 }
1916 }
1917 }
1918
1919 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1920 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1921 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1922 || (mProximityPositive &&
1923 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1924 }
1925
1926 /**
Jeff Brown96307042012-07-27 15:51:34 -07001927 * Updates the value of mIsPowered.
1928 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001929 */
Jeff Brown96307042012-07-27 15:51:34 -07001930 private void updateIsPoweredLocked(int dirty) {
1931 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001932 final boolean wasPowered = mIsPowered;
1933 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001934 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001935 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1936 mPlugType = mBatteryManagerInternal.getPlugType();
1937 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1938 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001939
Jeff Brown26875502014-01-30 21:47:47 -08001940 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001941 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001942 + ", mIsPowered=" + mIsPowered
1943 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001944 + ", mPlugType=" + mPlugType
1945 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001946 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001947
Jeff Brownf3fb8952012-10-02 20:57:05 -07001948 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001949 mDirty |= DIRTY_IS_POWERED;
1950
Jeff Brown3b971592013-01-09 18:46:37 -08001951 // Update wireless dock detection state.
1952 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001953 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001954
Jeff Brown96307042012-07-27 15:51:34 -07001955 // Treat plugging and unplugging the devices as a user activity.
1956 // Users find it disconcerting when they plug or unplug the device
1957 // and it shuts off right away.
1958 // Some devices also wake the device when plugged or unplugged because
1959 // they don't have a charging LED.
1960 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001961 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1962 dockedOnWirelessCharger)) {
Michael Wrighte3001042019-02-05 00:13:14 +00001963 wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1964 "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001965 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001966 }
1967 userActivityNoUpdateLocked(
1968 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001969
Beverlyac32c9a2018-01-31 16:10:41 -05001970 // only play charging sounds if boot is completed so charging sounds don't play
1971 // with potential notification sounds
1972 if (mBootCompleted) {
1973 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1974 && BatteryManager.isPlugWired(mPlugType)) {
Beverly478722e2019-10-14 11:16:57 -04001975 mNotifier.onWiredChargingStarted(mUserId);
Beverlyac32c9a2018-01-31 16:10:41 -05001976 } else if (dockedOnWirelessCharger) {
Beverly478722e2019-10-14 11:16:57 -04001977 mNotifier.onWirelessChargingStarted(mBatteryLevel, mUserId);
Beverlyac32c9a2018-01-31 16:10:41 -05001978 }
Jeff Brown84e27562012-12-07 13:56:34 -08001979 }
Jeff Brown96307042012-07-27 15:51:34 -07001980 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001981
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001982 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001983 }
1984 }
1985
Jeff Brown3b971592013-01-09 18:46:37 -08001986 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1987 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001988 // Don't wake when powered unless configured to do so.
1989 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1990 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001991 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001992
Jeff Brown3b971592013-01-09 18:46:37 -08001993 // Don't wake when undocked from wireless charger.
1994 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001995 if (wasPowered && !mIsPowered
1996 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1997 return false;
1998 }
Jeff Brown3b971592013-01-09 18:46:37 -08001999
2000 // Don't wake when docked on wireless charger unless we are certain of it.
2001 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07002002 if (!wasPowered && mIsPowered
2003 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08002004 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07002005 return false;
2006 }
2007
2008 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08002009 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07002010 return false;
2011 }
2012
Bryce Lee584a4452014-10-21 15:55:55 -07002013 // Don't wake while theater mode is enabled.
2014 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
2015 return false;
2016 }
2017
Adrian Roos56021892017-02-27 20:25:09 +01002018 // On Always On Display, SystemUI shows the charging indicator
2019 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
2020 return false;
2021 }
2022
Jeff Brown9fca9e92012-10-05 14:42:56 -07002023 // Otherwise wake up!
2024 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07002025 }
2026
Jeff Brown96307042012-07-27 15:51:34 -07002027 /**
2028 * Updates the value of mStayOn.
2029 * Sets DIRTY_STAY_ON if a change occurred.
2030 */
2031 private void updateStayOnLocked(int dirty) {
2032 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07002033 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07002034 if (mStayOnWhilePluggedInSetting != 0
2035 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07002036 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07002037 } else {
2038 mStayOn = false;
2039 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002040
2041 if (mStayOn != wasStayOn) {
2042 mDirty |= DIRTY_STAY_ON;
2043 }
Jeff Brown96307042012-07-27 15:51:34 -07002044 }
2045 }
2046
2047 /**
2048 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
2049 * Note that most wake-locks are ignored when the system is asleep.
2050 *
2051 * This function must have no other side-effects.
2052 */
Jeff Brownec083212013-09-11 20:45:25 -07002053 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07002054 private void updateWakeLockSummaryLocked(int dirty) {
2055 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
2056 mWakeLockSummary = 0;
2057
Pavel Grafov28939982017-10-03 15:11:52 +01002058 final int numProfiles = mProfilePowerState.size();
2059 for (int i = 0; i < numProfiles; i++) {
2060 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
2061 }
2062
Jeff Brown96307042012-07-27 15:51:34 -07002063 final int numWakeLocks = mWakeLocks.size();
2064 for (int i = 0; i < numWakeLocks; i++) {
2065 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01002066 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
2067 mWakeLockSummary |= wakeLockFlags;
2068 for (int j = 0; j < numProfiles; j++) {
2069 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
2070 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
2071 profile.mWakeLockSummary |= wakeLockFlags;
2072 }
Jeff Brown96307042012-07-27 15:51:34 -07002073 }
2074 }
2075
Pavel Grafov28939982017-10-03 15:11:52 +01002076 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
2077 for (int i = 0; i < numProfiles; i++) {
2078 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2079 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08002080 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002081
Jeff Brown96307042012-07-27 15:51:34 -07002082 if (DEBUG_SPEW) {
2083 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002084 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002085 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
2086 }
2087 }
2088 }
2089
Pavel Grafov28939982017-10-03 15:11:52 +01002090 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
2091 // Cancel wake locks that make no sense based on the current state.
2092 if (mWakefulness != WAKEFULNESS_DOZING) {
2093 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
2094 }
2095 if (mWakefulness == WAKEFULNESS_ASLEEP
2096 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2097 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
2098 | WAKE_LOCK_BUTTON_BRIGHT);
2099 if (mWakefulness == WAKEFULNESS_ASLEEP) {
2100 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
2101 }
2102 }
2103
2104 // Infer implied wake locks where necessary based on the current state.
2105 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
2106 if (mWakefulness == WAKEFULNESS_AWAKE) {
2107 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
2108 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
2109 wakeLockSummary |= WAKE_LOCK_CPU;
2110 }
2111 }
2112 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
2113 wakeLockSummary |= WAKE_LOCK_CPU;
2114 }
2115
2116 return wakeLockSummary;
2117 }
2118
2119 /** Get wake lock summary flags that correspond to the given wake lock. */
2120 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
2121 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
2122 case PowerManager.PARTIAL_WAKE_LOCK:
2123 if (!wakeLock.mDisabled) {
2124 // We only respect this if the wake lock is not disabled.
2125 return WAKE_LOCK_CPU;
2126 }
2127 break;
2128 case PowerManager.FULL_WAKE_LOCK:
2129 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
2130 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
2131 return WAKE_LOCK_SCREEN_BRIGHT;
2132 case PowerManager.SCREEN_DIM_WAKE_LOCK:
2133 return WAKE_LOCK_SCREEN_DIM;
2134 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
2135 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
2136 case PowerManager.DOZE_WAKE_LOCK:
2137 return WAKE_LOCK_DOZE;
2138 case PowerManager.DRAW_WAKE_LOCK:
2139 return WAKE_LOCK_DRAW;
2140 }
2141 return 0;
2142 }
2143
2144 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
2145 if (wakeLock.mWorkSource != null) {
2146 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08002147 final int uid = wakeLock.mWorkSource.getUid(k);
Pavel Grafov28939982017-10-03 15:11:52 +01002148 if (userId == UserHandle.getUserId(uid)) {
2149 return true;
2150 }
2151 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00002152
Suprabh Shuklaf7cffa72019-11-08 17:03:03 -08002153 final List<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
Narayan Kamath2f916ed2017-12-29 13:02:15 +00002154 if (workChains != null) {
2155 for (int k = 0; k < workChains.size(); k++) {
2156 final int uid = workChains.get(k).getAttributionUid();
2157 if (userId == UserHandle.getUserId(uid)) {
2158 return true;
2159 }
2160 }
2161 }
Pavel Grafov28939982017-10-03 15:11:52 +01002162 }
2163 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
2164 }
2165
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07002166 void checkForLongWakeLocks() {
2167 synchronized (mLock) {
2168 final long now = SystemClock.uptimeMillis();
2169 mNotifyLongDispatched = now;
2170 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
2171 long nextCheckTime = Long.MAX_VALUE;
2172 final int numWakeLocks = mWakeLocks.size();
2173 for (int i = 0; i < numWakeLocks; i++) {
2174 final WakeLock wakeLock = mWakeLocks.get(i);
2175 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2176 == PowerManager.PARTIAL_WAKE_LOCK) {
2177 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
2178 if (wakeLock.mAcquireTime < when) {
2179 // This wake lock has exceeded the long acquire time, report!
2180 notifyWakeLockLongStartedLocked(wakeLock);
2181 } else {
2182 // This wake lock could still become a long one, at this time.
2183 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
2184 if (checkTime < nextCheckTime) {
2185 nextCheckTime = checkTime;
2186 }
2187 }
2188 }
2189 }
2190 }
2191 mNotifyLongScheduled = 0;
2192 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2193 if (nextCheckTime != Long.MAX_VALUE) {
2194 mNotifyLongNextCheck = nextCheckTime;
2195 enqueueNotifyLongMsgLocked(nextCheckTime);
2196 } else {
2197 mNotifyLongNextCheck = 0;
2198 }
2199 }
2200 }
2201
Jeff Brown96307042012-07-27 15:51:34 -07002202 /**
2203 * Updates the value of mUserActivitySummary to summarize the user requested
2204 * state of the system such as whether the screen should be bright or dim.
2205 * Note that user activity is ignored when the system is asleep.
2206 *
2207 * This function must have no other side-effects.
2208 */
2209 private void updateUserActivitySummaryLocked(long now, int dirty) {
2210 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07002211 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08002212 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002213 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2214
2215 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08002216 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002217 || mWakefulness == WAKEFULNESS_DREAMING
2218 || mWakefulness == WAKEFULNESS_DOZING) {
Robert Horvath5560f382019-07-10 10:46:38 +02002219 final long attentiveTimeout = getAttentiveTimeoutLocked();
2220 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
2221 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout,
2222 attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01002223 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002224 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002225 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002226
2227 mUserActivitySummary = 0;
2228 if (mLastUserActivityTime >= mLastWakeTime) {
2229 nextTimeout = mLastUserActivityTime
2230 + screenOffTimeout - screenDimDuration;
2231 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002232 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002233 } else {
2234 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2235 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002236 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002237 }
2238 }
2239 }
2240 if (mUserActivitySummary == 0
2241 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2242 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002243 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002244 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2245 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002246 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2247 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2248 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2249 }
Jeff Brown96307042012-07-27 15:51:34 -07002250 }
2251 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002252
Jeff Brown05af6ad2014-09-30 20:54:30 -07002253 if (mUserActivitySummary == 0) {
2254 if (sleepTimeout >= 0) {
2255 final long anyUserActivity = Math.max(mLastUserActivityTime,
2256 mLastUserActivityTimeNoChangeLights);
2257 if (anyUserActivity >= mLastWakeTime) {
2258 nextTimeout = anyUserActivity + sleepTimeout;
2259 if (now < nextTimeout) {
2260 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2261 }
2262 }
2263 } else {
2264 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2265 nextTimeout = -1;
2266 }
2267 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002268
2269 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002270 if ((mUserActivitySummary &
2271 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002272 // Device is being kept awake by recent user activity
2273 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2274 // Save when the next timeout would have occurred
2275 mOverriddenTimeout = nextTimeout;
2276 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002277 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002278 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2279 nextTimeout = -1;
2280 }
2281
Alex Saloce5baf62019-11-15 17:10:28 -08002282 if (((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
2283 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0)
Alex Salo9e242232019-05-14 19:27:17 -07002284 && (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) == 0) {
Alex Saloce5baf62019-11-15 17:10:28 -08002285 nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout,
2286 screenDimDuration);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08002287 }
2288
Pavel Grafov28939982017-10-03 15:11:52 +01002289 if (nextProfileTimeout > 0) {
2290 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2291 }
2292
Jeff Brown05af6ad2014-09-30 20:54:30 -07002293 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002294 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002295 }
2296 } else {
2297 mUserActivitySummary = 0;
2298 }
2299
2300 if (DEBUG_SPEW) {
2301 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002302 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002303 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2304 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2305 }
2306 }
2307 }
2308
Pavel Grafov28939982017-10-03 15:11:52 +01002309 private void scheduleUserInactivityTimeout(long timeMs) {
2310 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2311 msg.setAsynchronous(true);
2312 mHandler.sendMessageAtTime(msg, timeMs);
2313 }
2314
Robert Horvath5560f382019-07-10 10:46:38 +02002315 private void scheduleAttentiveTimeout(long timeMs) {
2316 final Message msg = mHandler.obtainMessage(MSG_ATTENTIVE_TIMEOUT);
2317 msg.setAsynchronous(true);
2318 mHandler.sendMessageAtTime(msg, timeMs);
2319 }
2320
Pavel Grafov28939982017-10-03 15:11:52 +01002321 /**
2322 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2323 */
2324 private long getNextProfileTimeoutLocked(long now) {
2325 long nextTimeout = -1;
2326 final int numProfiles = mProfilePowerState.size();
2327 for (int i = 0; i < numProfiles; i++) {
2328 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2329 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2330 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2331 nextTimeout = timeout;
2332 }
2333 }
2334 return nextTimeout;
2335 }
2336
Robert Horvath5560f382019-07-10 10:46:38 +02002337 private void updateAttentiveStateLocked(long now, int dirty) {
2338 long attentiveTimeout = getAttentiveTimeoutLocked();
2339 long goToSleepTime = mLastUserActivityTime + attentiveTimeout;
2340 long showWarningTime = goToSleepTime - mAttentiveWarningDurationConfig;
2341
2342 boolean warningDismissed = maybeHideInattentiveSleepWarningLocked(now, showWarningTime);
2343
2344 if (attentiveTimeout >= 0 && (warningDismissed
2345 || (dirty & (DIRTY_ATTENTIVE | DIRTY_STAY_ON | DIRTY_SCREEN_BRIGHTNESS_BOOST
2346 | DIRTY_PROXIMITY_POSITIVE | DIRTY_WAKEFULNESS | DIRTY_BOOT_COMPLETED
2347 | DIRTY_SETTINGS)) != 0)) {
2348 if (DEBUG_SPEW) {
2349 Slog.d(TAG, "Updating attentive state");
2350 }
2351
2352 mHandler.removeMessages(MSG_ATTENTIVE_TIMEOUT);
2353
2354 if (isBeingKeptFromShowingInattentiveSleepWarningLocked()) {
2355 return;
2356 }
2357
2358 long nextTimeout = -1;
2359
2360 if (now < showWarningTime) {
2361 nextTimeout = showWarningTime;
2362 } else if (now < goToSleepTime) {
2363 if (DEBUG) {
2364 long timeToSleep = goToSleepTime - now;
2365 Slog.d(TAG, "Going to sleep in " + timeToSleep
2366 + "ms if there is no user activity");
2367 }
2368 mInattentiveSleepWarningOverlayController.show();
2369 nextTimeout = goToSleepTime;
2370 } else {
2371 if (DEBUG && mWakefulness != WAKEFULNESS_ASLEEP) {
2372 Slog.i(TAG, "Going to sleep now due to long user inactivity");
2373 }
2374 }
2375
2376 if (nextTimeout >= 0) {
2377 scheduleAttentiveTimeout(nextTimeout);
2378 }
2379 }
2380 }
2381
2382 private boolean maybeHideInattentiveSleepWarningLocked(long now, long showWarningTime) {
2383 long attentiveTimeout = getAttentiveTimeoutLocked();
2384
Robert Horvath60e51fe2019-08-20 13:10:34 +02002385 if (!mInattentiveSleepWarningOverlayController.isShown()) {
2386 return false;
2387 }
2388
2389 if (mWakefulness != WAKEFULNESS_AWAKE) {
2390 mInattentiveSleepWarningOverlayController.dismiss(false);
2391 return true;
2392 } else if (attentiveTimeout < 0 || isBeingKeptFromShowingInattentiveSleepWarningLocked()
2393 || now < showWarningTime) {
2394 mInattentiveSleepWarningOverlayController.dismiss(true);
Robert Horvath5560f382019-07-10 10:46:38 +02002395 return true;
2396 }
2397
2398 return false;
2399 }
2400
2401 private boolean isAttentiveTimeoutExpired(long now) {
2402 long attentiveTimeout = getAttentiveTimeoutLocked();
2403 return attentiveTimeout >= 0 && now > mLastUserActivityTime + attentiveTimeout;
2404 }
2405
Jeff Brown96307042012-07-27 15:51:34 -07002406 /**
2407 * Called when a user activity timeout has occurred.
2408 * Simply indicates that something about user activity has changed so that the new
2409 * state can be recomputed when the power state is updated.
2410 *
2411 * This function must have no other side-effects besides setting the dirty
2412 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2413 */
2414 private void handleUserActivityTimeout() { // runs on handler thread
2415 synchronized (mLock) {
2416 if (DEBUG_SPEW) {
2417 Slog.d(TAG, "handleUserActivityTimeout");
2418 }
2419
2420 mDirty |= DIRTY_USER_ACTIVITY;
2421 updatePowerStateLocked();
2422 }
2423 }
2424
Robert Horvath5560f382019-07-10 10:46:38 +02002425 private void handleAttentiveTimeout() { // runs on handler thread
2426 synchronized (mLock) {
2427 if (DEBUG_SPEW) {
2428 Slog.d(TAG, "handleAttentiveTimeout");
2429 }
2430
2431 mDirty |= DIRTY_ATTENTIVE;
2432 updatePowerStateLocked();
2433 }
2434 }
2435
2436 private long getAttentiveTimeoutLocked() {
2437 long timeout = mAttentiveTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002438 if (timeout <= 0) {
2439 return -1;
2440 }
Robert Horvath5560f382019-07-10 10:46:38 +02002441
2442 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2443 }
2444
2445 private long getSleepTimeoutLocked(long attentiveTimeout) {
2446 long timeout = mSleepTimeoutSetting;
2447 if (timeout <= 0) {
2448 return -1;
2449 }
2450 if (attentiveTimeout >= 0) {
2451 timeout = Math.min(timeout, attentiveTimeout);
2452 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002453 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2454 }
2455
Robert Horvath5560f382019-07-10 10:46:38 +02002456 private long getScreenOffTimeoutLocked(long sleepTimeout, long attentiveTimeout) {
Pavel Grafov28939982017-10-03 15:11:52 +01002457 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002458 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2459 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2460 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002461 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002462 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002463 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002464 if (sleepTimeout >= 0) {
2465 timeout = Math.min(timeout, sleepTimeout);
2466 }
Robert Horvath5560f382019-07-10 10:46:38 +02002467 if (attentiveTimeout >= 0) {
2468 timeout = Math.min(timeout, attentiveTimeout);
2469 }
Jeff Brown27736f52014-05-20 17:17:10 -07002470 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002471 }
2472
Pavel Grafov28939982017-10-03 15:11:52 +01002473 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002474 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002475 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002476 }
2477
2478 /**
2479 * Updates the wakefulness of the device.
2480 *
Jeff Brown26875502014-01-30 21:47:47 -08002481 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002482 * based on the current wake locks and user activity state. It may modify mDirty
2483 * if the wakefulness changes.
2484 *
2485 * Returns true if the wakefulness changed and we need to restart power state calculation.
2486 */
2487 private boolean updateWakefulnessLocked(int dirty) {
2488 boolean changed = false;
2489 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002490 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
Robert Horvath73298fa2020-02-07 16:51:49 +01002491 | DIRTY_DOCK_STATE | DIRTY_ATTENTIVE | DIRTY_SETTINGS
2492 | DIRTY_SCREEN_BRIGHTNESS_BOOST)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002493 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2494 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002495 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002496 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002497 final long time = SystemClock.uptimeMillis();
Robert Horvath5560f382019-07-10 10:46:38 +02002498 if (isAttentiveTimeoutExpired(time)) {
2499 changed = goToSleepNoUpdateLocked(time, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
2500 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, Process.SYSTEM_UID);
2501 } else if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002502 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002503 } else {
2504 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002505 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002506 }
Jeff Brown96307042012-07-27 15:51:34 -07002507 }
2508 }
2509 return changed;
2510 }
2511
Jeff Brown645832d2012-10-03 14:57:03 -07002512 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002513 * Returns true if the device should automatically nap and start dreaming when the user
2514 * activity timeout has expired and it's bedtime.
2515 */
2516 private boolean shouldNapAtBedTimeLocked() {
2517 return mDreamsActivateOnSleepSetting
2518 || (mDreamsActivateOnDockSetting
2519 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2520 }
2521
2522 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002523 * Returns true if the device should go to sleep now.
2524 * Also used when exiting a dream to determine whether we should go back
2525 * to being fully awake or else go to sleep for good.
2526 */
Jeff Brown96307042012-07-27 15:51:34 -07002527 private boolean isItBedTimeYetLocked() {
Robert Horvath5560f382019-07-10 10:46:38 +02002528 if (!mBootCompleted) {
2529 return false;
2530 }
2531
2532 long now = SystemClock.uptimeMillis();
2533 if (isAttentiveTimeoutExpired(now)) {
2534 return !isBeingKeptFromInattentiveSleepLocked();
2535 } else {
2536 return !isBeingKeptAwakeLocked();
2537 }
Jeff Brown645832d2012-10-03 14:57:03 -07002538 }
2539
2540 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002541 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002542 * or the stay on while powered setting. We also keep the phone awake when
2543 * the proximity sensor returns a positive result so that the device does not
2544 * lock while in a phone call. This function only controls whether the device
2545 * will go to sleep or dream which is independent of whether it will be allowed
2546 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002547 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002548 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002549 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002550 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002551 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002552 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002553 | USER_ACTIVITY_SCREEN_DIM)) != 0
2554 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002555 }
2556
2557 /**
Robert Horvath5560f382019-07-10 10:46:38 +02002558 * Returns true if the device is prevented from going into inattentive sleep by the stay on
2559 * while powered setting. We also keep the device awake when the proximity sensor returns a
2560 * positive result so that the device does not lock while in a phone call. This function only
2561 * controls whether the device will go to sleep which is independent of whether it will be
2562 * allowed to suspend.
2563 */
2564 private boolean isBeingKeptFromInattentiveSleepLocked() {
2565 return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive
2566 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2567 | USER_ACTIVITY_SCREEN_DIM)) != 0;
2568 }
2569
2570 private boolean isBeingKeptFromShowingInattentiveSleepWarningLocked() {
2571 return mStayOn || mScreenBrightnessBoostInProgress || mProximityPositive || !mBootCompleted;
2572 }
2573
2574 /**
Jeff Brown96307042012-07-27 15:51:34 -07002575 * Determines whether to post a message to the sandman to update the dream state.
2576 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002577 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002578 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002579 | DIRTY_USER_ACTIVITY
Robert Horvath5560f382019-07-10 10:46:38 +02002580 | DIRTY_ATTENTIVE
Jeff Brown645832d2012-10-03 14:57:03 -07002581 | DIRTY_WAKE_LOCKS
2582 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002583 | DIRTY_SETTINGS
2584 | DIRTY_IS_POWERED
2585 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002586 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002587 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2588 if (mDisplayReady) {
2589 scheduleSandmanLocked();
2590 }
Jeff Brown96307042012-07-27 15:51:34 -07002591 }
2592 }
2593
2594 private void scheduleSandmanLocked() {
2595 if (!mSandmanScheduled) {
2596 mSandmanScheduled = true;
2597 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2598 msg.setAsynchronous(true);
2599 mHandler.sendMessage(msg);
2600 }
2601 }
2602
2603 /**
Jeff Brown26875502014-01-30 21:47:47 -08002604 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002605 *
2606 * We do this asynchronously because we must call out of the power manager to start
2607 * the dream and we don't want to hold our lock while doing so. There is a risk that
2608 * the device will wake or go to sleep in the meantime so we have to handle that case.
2609 */
2610 private void handleSandman() { // runs on handler thread
2611 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002612 final boolean startDreaming;
2613 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002614 synchronized (mLock) {
2615 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002616 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002617 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002618 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002619 mSandmanSummoned = false;
2620 } else {
2621 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002622 }
2623 }
2624
Jeff Brown96307042012-07-27 15:51:34 -07002625 // Start dreaming if needed.
2626 // We only control the dream on the handler thread, so we don't need to worry about
2627 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002628 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002629 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002630 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002631 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002632 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002633 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002634 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002635 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002636 } else {
2637 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002638 }
2639
Santos Cordon03044382019-09-19 16:59:01 +01002640 // At this point, we either attempted to start the dream or no attempt will be made,
2641 // so stop holding the display suspend blocker for Doze.
2642 mDozeStartInProgress = false;
2643
Jeff Brown96307042012-07-27 15:51:34 -07002644 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002645 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002646 // Remember the initial battery level when the dream started.
2647 if (startDreaming && isDreaming) {
2648 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2649 if (wakefulness == WAKEFULNESS_DOZING) {
2650 Slog.i(TAG, "Dozing...");
2651 } else {
2652 Slog.i(TAG, "Dreaming...");
2653 }
2654 }
2655
2656 // If preconditions changed, wait for the next iteration to determine
2657 // whether the dream should continue (or be restarted).
2658 if (mSandmanSummoned || mWakefulness != wakefulness) {
2659 return; // wait for next cycle
2660 }
2661
2662 // Determine whether the dream should continue.
Robert Horvath5560f382019-07-10 10:46:38 +02002663 long now = SystemClock.uptimeMillis();
Jeff Brown26875502014-01-30 21:47:47 -08002664 if (wakefulness == WAKEFULNESS_DREAMING) {
2665 if (isDreaming && canDreamLocked()) {
2666 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002667 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002668 - mDreamsBatteryLevelDrainCutoffConfig
2669 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002670 // If the user activity timeout expired and the battery appears
2671 // to be draining faster than it is charging then stop dreaming
2672 // and go to sleep.
2673 Slog.i(TAG, "Stopping dream because the battery appears to "
2674 + "be draining faster than it is charging. "
2675 + "Battery level when dream started: "
2676 + mBatteryLevelWhenDreamStarted + "%. "
2677 + "Battery level now: " + mBatteryLevel + "%.");
2678 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002679 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002680 }
Jeff Brown96307042012-07-27 15:51:34 -07002681 }
Jeff Brown26875502014-01-30 21:47:47 -08002682
2683 // Dream has ended or will be stopped. Update the power state.
2684 if (isItBedTimeYetLocked()) {
Robert Horvath5560f382019-07-10 10:46:38 +02002685 int flags = 0;
2686 if (isAttentiveTimeoutExpired(now)) {
2687 flags |= PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE;
2688 }
2689 goToSleepNoUpdateLocked(now, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, flags,
2690 Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002691 updatePowerStateLocked();
2692 } else {
Robert Horvath5560f382019-07-10 10:46:38 +02002693 wakeUpNoUpdateLocked(now,
Michael Wrighte3001042019-02-05 00:13:14 +00002694 PowerManager.WAKE_REASON_UNKNOWN,
2695 "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2696 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002697 updatePowerStateLocked();
2698 }
2699 } else if (wakefulness == WAKEFULNESS_DOZING) {
2700 if (isDreaming) {
2701 return; // continue dozing
2702 }
2703
2704 // Doze has ended or will be stopped. Update the power state.
Robert Horvath5560f382019-07-10 10:46:38 +02002705 reallyGoToSleepNoUpdateLocked(now, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002706 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002707 }
Jeff Brown96307042012-07-27 15:51:34 -07002708 }
2709
Jeff Brown26875502014-01-30 21:47:47 -08002710 // Stop dream.
2711 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002712 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002713 }
2714 }
2715
2716 /**
Jeff Brown26875502014-01-30 21:47:47 -08002717 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002718 */
2719 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002720 if (mWakefulness != WAKEFULNESS_DREAMING
2721 || !mDreamsSupportedConfig
2722 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002723 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002724 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002725 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2726 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002727 || !mBootCompleted) {
2728 return false;
2729 }
2730 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002731 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002732 return false;
2733 }
2734 if (!mIsPowered
2735 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2736 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2737 return false;
2738 }
2739 if (mIsPowered
2740 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2741 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2742 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002743 }
2744 }
Jeff Brown26875502014-01-30 21:47:47 -08002745 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002746 }
2747
Jeff Brown96307042012-07-27 15:51:34 -07002748 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002749 * Returns true if the device is allowed to doze in its current state.
2750 */
2751 private boolean canDozeLocked() {
2752 return mWakefulness == WAKEFULNESS_DOZING;
2753 }
2754
2755 /**
Jeff Brown96307042012-07-27 15:51:34 -07002756 * Updates the display power state asynchronously.
2757 * When the update is finished, mDisplayReady will be set to true. The display
2758 * controller posts a message to tell us when the actual display power state
2759 * has been updated so we come back here to double-check and finish up.
2760 *
2761 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002762 *
2763 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002764 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002765 private boolean updateDisplayPowerStateLocked(int dirty) {
2766 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002767 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2768 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002769 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2770 DIRTY_QUIESCENT)) != 0) {
Robert Horvath4fbab202019-11-29 15:36:39 +01002771 if ((dirty & DIRTY_QUIESCENT) != 0) {
2772 sQuiescent = false;
2773 }
2774
Jeff Brown970d4132014-07-19 11:33:47 -07002775 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002776
Jeff Browne333e672014-10-28 13:48:55 -07002777 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002778 final boolean autoBrightness;
Fiona Campbelld4eb2952019-11-04 17:19:56 +00002779 final float screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002780 if (!mBootCompleted) {
2781 // Keep the brightness steady during boot. This requires the
2782 // bootloader brightness and the default brightness to be identical.
2783 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002784 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002785 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002786 autoBrightness = false;
Fiona Campbelld4eb2952019-11-04 17:19:56 +00002787 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManagerFloat;
Michael Wrightd8460232018-01-16 18:04:59 +00002788 } else {
2789 autoBrightness = (mScreenBrightnessModeSetting ==
2790 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
Fiona Campbelld4eb2952019-11-04 17:19:56 +00002791 screenBrightnessOverride = PowerManager.BRIGHTNESS_INVALID_FLOAT;
Jeff Brown96307042012-07-27 15:51:34 -07002792 }
Jeff Browne333e672014-10-28 13:48:55 -07002793
2794 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002795 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002796 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002797 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002798 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002799
jackqdyulei92681e82017-02-28 11:26:28 -08002800 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2801
Jeff Brown970d4132014-07-19 11:33:47 -07002802 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2803 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002804 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2805 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002806 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2807 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2808 }
2809 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2810 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2811 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002812 }
Jeff Brown970d4132014-07-19 11:33:47 -07002813 mDisplayPowerRequest.dozeScreenBrightness =
Fiona Campbelld4eb2952019-11-04 17:19:56 +00002814 mDozeScreenBrightnessOverrideFromDreamManagerFloat;
Jeff Brown970d4132014-07-19 11:33:47 -07002815 } else {
2816 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
Fiona Campbelld4eb2952019-11-04 17:19:56 +00002817 mDisplayPowerRequest.dozeScreenBrightness =
2818 PowerManager.BRIGHTNESS_INVALID_FLOAT;
Jeff Brown970d4132014-07-19 11:33:47 -07002819 }
2820
Jeff Brown131206b2014-04-08 17:27:14 -07002821 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002822 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002823 mRequestWaitForNegativeProximity = false;
2824
2825 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002826 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002827 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002828 + ", mWakefulness=" + mWakefulness
2829 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2830 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002831 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002832 + ", screenBrightnessOverride=" + screenBrightnessOverride
2833 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002834 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002835 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002836 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002837 }
2838 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002839 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002840 }
2841
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002842 private void updateScreenBrightnessBoostLocked(int dirty) {
2843 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2844 if (mScreenBrightnessBoostInProgress) {
2845 final long now = SystemClock.uptimeMillis();
2846 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2847 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2848 final long boostTimeout = mLastScreenBrightnessBoostTime +
2849 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2850 if (boostTimeout > now) {
2851 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2852 msg.setAsynchronous(true);
2853 mHandler.sendMessageAtTime(msg, boostTimeout);
2854 return;
2855 }
Jeff Browne333e672014-10-28 13:48:55 -07002856 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002857 mScreenBrightnessBoostInProgress = false;
2858 userActivityNoUpdateLocked(now,
2859 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002860 }
Jeff Browne333e672014-10-28 13:48:55 -07002861 }
2862 }
2863
Santos Cordon3107d292016-09-20 15:50:35 -07002864 private boolean shouldBoostScreenBrightness() {
2865 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2866 }
2867
Jeff Brown96307042012-07-27 15:51:34 -07002868 private static boolean isValidBrightness(int value) {
2869 return value >= 0 && value <= 255;
2870 }
2871
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002872 @VisibleForTesting
2873 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002874 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002875 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002876 }
2877
Jeff Brown2175e9c2014-09-12 16:11:07 -07002878 if (mWakefulness == WAKEFULNESS_DOZING) {
2879 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2880 return DisplayPowerRequest.POLICY_DOZE;
2881 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002882 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002883 return DisplayPowerRequest.POLICY_OFF;
2884 }
2885 // Fall through and preserve the current screen policy if not configured to
2886 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002887 }
2888
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002889 // It is important that POLICY_VR check happens after the wakefulness checks above so
2890 // that VR-mode does not prevent displays from transitioning to the correct state when
2891 // dozing or sleeping.
2892 if (mIsVrModeEnabled) {
2893 return DisplayPowerRequest.POLICY_VR;
2894 }
2895
Jeff Brown96307042012-07-27 15:51:34 -07002896 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2897 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002898 || !mBootCompleted
2899 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002900 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002901 }
2902
Jeff Brown970d4132014-07-19 11:33:47 -07002903 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002904 }
2905
Jeff Brown131206b2014-04-08 17:27:14 -07002906 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2907 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002908 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002909
Jeff Brown96307042012-07-27 15:51:34 -07002910 @Override
2911 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002912 synchronized (mLock) {
2913 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2914 updatePowerStateLocked();
2915 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002916 }
2917
2918 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002919 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002920 synchronized (mLock) {
2921 mProximityPositive = true;
2922 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2923 updatePowerStateLocked();
2924 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002925 }
2926
2927 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002928 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002929 synchronized (mLock) {
2930 mProximityPositive = false;
2931 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2932 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2933 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2934 updatePowerStateLocked();
2935 }
Jeff Brown96307042012-07-27 15:51:34 -07002936 }
Jeff Brown131206b2014-04-08 17:27:14 -07002937
2938 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002939 public void onDisplayStateChange(int state) {
2940 // This method is only needed to support legacy display blanking behavior
2941 // where the display's power state is coupled to suspend or to the power HAL.
2942 // The order of operations matters here.
2943 synchronized (mLock) {
2944 if (mDisplayState != state) {
2945 mDisplayState = state;
2946 if (state == Display.STATE_OFF) {
2947 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2948 setHalInteractiveModeLocked(false);
2949 }
2950 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2951 setHalAutoSuspendModeLocked(true);
2952 }
2953 } else {
2954 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2955 setHalAutoSuspendModeLocked(false);
2956 }
2957 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2958 setHalInteractiveModeLocked(true);
2959 }
2960 }
2961 }
2962 }
2963 }
2964
2965 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002966 public void acquireSuspendBlocker() {
2967 mDisplaySuspendBlocker.acquire();
2968 }
2969
2970 @Override
2971 public void releaseSuspendBlocker() {
2972 mDisplaySuspendBlocker.release();
2973 }
2974
2975 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002976 public String toString() {
2977 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002978 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002979 }
2980 }
Jeff Brown96307042012-07-27 15:51:34 -07002981 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002982
Jeff Brown96307042012-07-27 15:51:34 -07002983 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002984 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002985 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002986
Jeff Brown96307042012-07-27 15:51:34 -07002987 /**
2988 * Updates the suspend blocker that keeps the CPU alive.
2989 *
2990 * This function must have no other side-effects.
2991 */
2992 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002993 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002994 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2995 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002996 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002997
2998 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002999 // FIXME We should consider just leaving auto-suspend enabled forever since
3000 // we already hold the necessary wakelocks.
3001 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
3002 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08003003 }
Jeff Brown27f7a862012-12-12 15:43:31 -08003004
3005 // First acquire suspend blockers if needed.
3006 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
3007 mWakeLockSuspendBlocker.acquire();
3008 mHoldingWakeLockSuspendBlocker = true;
3009 }
3010 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
3011 mDisplaySuspendBlocker.acquire();
3012 mHoldingDisplaySuspendBlocker = true;
3013 }
3014
Jeff Brown7b5be5e2014-11-12 18:45:31 -08003015 // Inform the power HAL about interactive mode.
3016 // Although we could set interactive strictly based on the wakefulness
3017 // as reported by isInteractive(), it is actually more desirable to track
3018 // the display policy state instead so that the interactive state observed
3019 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
3020 // Refer to getDesiredScreenPolicyLocked() for details.
3021 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
3022 // When becoming non-interactive, we want to defer sending this signal
3023 // until the display is actually ready so that all transitions have
3024 // completed. This is probably a good sign that things have gotten
3025 // too tangled over here...
3026 if (interactive || mDisplayReady) {
3027 setHalInteractiveModeLocked(interactive);
3028 }
3029 }
3030
Jeff Brown27f7a862012-12-12 15:43:31 -08003031 // Then release suspend blockers if needed.
3032 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
3033 mWakeLockSuspendBlocker.release();
3034 mHoldingWakeLockSuspendBlocker = false;
3035 }
3036 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
3037 mDisplaySuspendBlocker.release();
3038 mHoldingDisplaySuspendBlocker = false;
3039 }
Jeff Brown26875502014-01-30 21:47:47 -08003040
3041 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08003042 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
3043 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08003044 }
Jeff Brown96307042012-07-27 15:51:34 -07003045 }
3046
Jeff Brownec083212013-09-11 20:45:25 -07003047 /**
3048 * Return true if we must keep a suspend blocker active on behalf of the display.
3049 * We do so if the screen is on or is in transition between states.
3050 */
Jeff Brown26875502014-01-30 21:47:47 -08003051 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07003052 if (!mDisplayReady) {
3053 return true;
3054 }
Jeff Brown970d4132014-07-19 11:33:47 -07003055 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07003056 // If we asked for the screen to be on but it is off due to the proximity
3057 // sensor then we may suspend but only if the configuration allows it.
3058 // On some hardware it may not be safe to suspend because the proximity
3059 // sensor may not be correctly configured as a wake-up source.
3060 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
3061 || !mSuspendWhenScreenOffDueToProximityConfig) {
3062 return true;
3063 }
3064 }
Santos Cordond9701ab2019-08-01 18:33:20 +01003065
3066 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE
3067 && mDisplayPowerRequest.dozeScreenState == Display.STATE_ON) {
3068 // Although we are in DOZE and would normally allow the device to suspend,
3069 // the doze service has explicitly requested the display to remain in the ON
3070 // state which means we should hold the display suspend blocker.
3071 return true;
3072 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08003073 if (mScreenBrightnessBoostInProgress) {
3074 return true;
3075 }
Santos Cordon03044382019-09-19 16:59:01 +01003076
3077 // When we transition to DOZING, we have to keep the display suspend blocker
3078 // up until the Doze service has a change to acquire the DOZE wakelock.
3079 // Here we wait for mWakefulnessChanging to become false since the wakefulness
3080 // transition to DOZING isn't considered "changed" until the doze wake lock is
3081 // acquired.
3082 if (mWakefulness == WAKEFULNESS_DOZING && mDozeStartInProgress) {
3083 return true;
3084 }
3085
Jeff Brown26875502014-01-30 21:47:47 -08003086 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07003087 return false;
3088 }
3089
Jeff Brown037c33e2014-04-09 00:31:55 -07003090 private void setHalAutoSuspendModeLocked(boolean enable) {
3091 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08003092 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07003093 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08003094 }
Jeff Brown037c33e2014-04-09 00:31:55 -07003095 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07003096 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
3097 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01003098 mNativeWrapper.nativeSetAutoSuspend(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07003099 } finally {
3100 Trace.traceEnd(Trace.TRACE_TAG_POWER);
3101 }
Jeff Brown26875502014-01-30 21:47:47 -08003102 }
3103 }
3104
Jeff Brown037c33e2014-04-09 00:31:55 -07003105 private void setHalInteractiveModeLocked(boolean enable) {
3106 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08003107 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07003108 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08003109 }
Jeff Brown037c33e2014-04-09 00:31:55 -07003110 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07003111 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
3112 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01003113 mNativeWrapper.nativeSetInteractive(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07003114 } finally {
3115 Trace.traceEnd(Trace.TRACE_TAG_POWER);
3116 }
Jeff Brown26875502014-01-30 21:47:47 -08003117 }
3118 }
3119
Jeff Brown037c33e2014-04-09 00:31:55 -07003120 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07003121 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08003122 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05003123 }
3124 }
3125
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003126 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003127 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003128 if (DEBUG) {
3129 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
3130 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003131 if (mIsPowered) {
3132 return false;
3133 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003134
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003135 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003136
John Spurlock8d4e6cb2014-09-14 11:10:22 -04003137 return true;
3138 }
3139 }
3140
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003141 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07003142 synchronized (mLock) {
3143 return mDeviceIdleMode;
3144 }
3145 }
3146
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003147 boolean isLightDeviceIdleModeInternal() {
3148 synchronized (mLock) {
3149 return mLightDeviceIdleMode;
3150 }
3151 }
3152
Jeff Brown96307042012-07-27 15:51:34 -07003153 private void handleBatteryStateChangedLocked() {
3154 mDirty |= DIRTY_BATTERY_STATE;
3155 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04003156 }
3157
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003158 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Nikita Ioffe779d6be2020-02-06 23:17:17 +00003159 @Nullable final String reason, boolean wait) {
3160 if (PowerManager.REBOOT_USERSPACE.equals(reason)) {
3161 UserspaceRebootLogger.noteUserspaceRebootWasRequested();
3162 }
Jeff Brown96307042012-07-27 15:51:34 -07003163 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07003164 if (RescueParty.isAttemptingFactoryReset()) {
3165 // If we're stuck in a really low-level reboot loop, and a
3166 // rescue party is trying to prompt the user for a factory data
3167 // reset, we must GET TO DA CHOPPA!
3168 PowerManagerService.lowLevelReboot(reason);
3169 } else {
3170 throw new IllegalStateException("Too early to call shutdown() or reboot()");
3171 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003172 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003173
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003174 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07003175 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003176 public void run() {
3177 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003178 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003179 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003180 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003181 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07003182 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07003183 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003184 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003185 }
San Mehat1e512792010-01-07 10:40:29 -08003186 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003187 };
Jeff Brown96307042012-07-27 15:51:34 -07003188
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003189 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00003190 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07003191 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00003192 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003193
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003194 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07003195 if (wait) {
3196 synchronized (runnable) {
3197 while (true) {
3198 try {
3199 runnable.wait();
3200 } catch (InterruptedException e) {
3201 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05003202 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08003203 }
Doug Zongker50a21f42009-11-19 12:49:53 -08003204 }
3205 }
3206
Jeff Brown96307042012-07-27 15:51:34 -07003207 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08003208 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07003209 @Override
Jeff Brown96307042012-07-27 15:51:34 -07003210 public void run() {
3211 throw new RuntimeException(message);
3212 }
Dan Egnor60d87622009-12-16 16:32:58 -08003213 };
3214 try {
3215 t.start();
3216 t.join();
3217 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07003218 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08003219 }
3220 }
3221
jackqdyulei92681e82017-02-28 11:26:28 -08003222 @VisibleForTesting
3223 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
3224 PowerSaveState state = mBatterySaverPolicy.
Kweku Adams9f488e22019-01-14 16:25:08 -08003225 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
jackqdyulei92681e82017-02-28 11:26:28 -08003226 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
3227 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
3228 }
3229
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003230 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07003231 Settings.Global.putInt(mContext.getContentResolver(),
3232 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 }
3234
Pavel Grafov28939982017-10-03 15:11:52 +01003235 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
3236 if (userId < 0) {
3237 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
3238 return;
3239 }
Jeff Brown96307042012-07-27 15:51:34 -07003240 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01003241 // System-wide timeout
3242 if (userId == UserHandle.USER_SYSTEM) {
3243 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
3244 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
3245 mProfilePowerState.delete(userId);
3246 } else {
3247 final ProfilePowerState profile = mProfilePowerState.get(userId);
3248 if (profile != null) {
3249 profile.mScreenOffTimeout = timeMs;
3250 } else {
3251 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
3252 // We need to recalculate wake locks for the new profile state.
3253 mDirty |= DIRTY_WAKE_LOCKS;
3254 }
3255 }
Jeff Brown96307042012-07-27 15:51:34 -07003256 mDirty |= DIRTY_SETTINGS;
3257 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
3259 }
3260
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003261 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003262 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07003263 if (mDeviceIdleMode == enabled) {
3264 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003265 }
Felipe Lemeea014392016-09-06 13:59:54 -07003266 mDeviceIdleMode = enabled;
3267 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003268 }
Felipe Lemeea014392016-09-06 13:59:54 -07003269 if (enabled) {
3270 EventLogTags.writeDeviceIdleOnPhase("power");
3271 } else {
3272 EventLogTags.writeDeviceIdleOffPhase("power");
3273 }
3274 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003275 }
3276
3277 boolean setLightDeviceIdleModeInternal(boolean enabled) {
3278 synchronized (mLock) {
3279 if (mLightDeviceIdleMode != enabled) {
3280 mLightDeviceIdleMode = enabled;
3281 return true;
3282 }
3283 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003284 }
3285 }
3286
3287 void setDeviceIdleWhitelistInternal(int[] appids) {
3288 synchronized (mLock) {
3289 mDeviceIdleWhitelist = appids;
3290 if (mDeviceIdleMode) {
3291 updateWakeLockDisabledStatesLocked();
3292 }
3293 }
3294 }
3295
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003296 void setDeviceIdleTempWhitelistInternal(int[] appids) {
3297 synchronized (mLock) {
3298 mDeviceIdleTempWhitelist = appids;
3299 if (mDeviceIdleMode) {
3300 updateWakeLockDisabledStatesLocked();
3301 }
3302 }
3303 }
3304
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003305 void startUidChangesInternal() {
3306 synchronized (mLock) {
3307 mUidsChanging = true;
3308 }
3309 }
3310
3311 void finishUidChangesInternal() {
3312 synchronized (mLock) {
3313 mUidsChanging = false;
3314 if (mUidsChanged) {
3315 updateWakeLockDisabledStatesLocked();
3316 mUidsChanged = false;
3317 }
3318 }
3319 }
3320
3321 private void handleUidStateChangeLocked() {
3322 if (mUidsChanging) {
3323 mUidsChanged = true;
3324 } else {
3325 updateWakeLockDisabledStatesLocked();
3326 }
3327 }
3328
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003329 void updateUidProcStateInternal(int uid, int procState) {
3330 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003331 UidState state = mUidState.get(uid);
3332 if (state == null) {
3333 state = new UidState(uid);
3334 mUidState.put(uid, state);
3335 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07003336 final boolean oldShouldAllow = state.mProcState
3337 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003338 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07003339 if (state.mNumWakeLocks > 0) {
3340 if (mDeviceIdleMode) {
3341 handleUidStateChangeLocked();
3342 } else if (!state.mActive && oldShouldAllow !=
3343 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
3344 // If this uid is not active, but the process state has changed such
3345 // that we may still want to allow it to hold a wake lock, then take care of it.
3346 handleUidStateChangeLocked();
3347 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003348 }
3349 }
3350 }
3351
3352 void uidGoneInternal(int uid) {
3353 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003354 final int index = mUidState.indexOfKey(uid);
3355 if (index >= 0) {
3356 UidState state = mUidState.valueAt(index);
3357 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
3358 state.mActive = false;
3359 mUidState.removeAt(index);
3360 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
3361 handleUidStateChangeLocked();
3362 }
3363 }
3364 }
3365 }
3366
3367 void uidActiveInternal(int uid) {
3368 synchronized (mLock) {
3369 UidState state = mUidState.get(uid);
3370 if (state == null) {
3371 state = new UidState(uid);
3372 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3373 mUidState.put(uid, state);
3374 }
3375 state.mActive = true;
3376 if (state.mNumWakeLocks > 0) {
3377 handleUidStateChangeLocked();
3378 }
3379 }
3380 }
3381
3382 void uidIdleInternal(int uid) {
3383 synchronized (mLock) {
3384 UidState state = mUidState.get(uid);
3385 if (state != null) {
3386 state.mActive = false;
3387 if (state.mNumWakeLocks > 0) {
3388 handleUidStateChangeLocked();
3389 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003390 }
3391 }
3392 }
3393
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003394 private void updateWakeLockDisabledStatesLocked() {
3395 boolean changed = false;
3396 final int numWakeLocks = mWakeLocks.size();
3397 for (int i = 0; i < numWakeLocks; i++) {
3398 final WakeLock wakeLock = mWakeLocks.get(i);
3399 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003400 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003401 if (setWakeLockDisabledStateLocked(wakeLock)) {
3402 changed = true;
3403 if (wakeLock.mDisabled) {
3404 // This wake lock is no longer being respected.
3405 notifyWakeLockReleasedLocked(wakeLock);
3406 } else {
3407 notifyWakeLockAcquiredLocked(wakeLock);
3408 }
3409 }
3410 }
3411 }
3412 if (changed) {
3413 mDirty |= DIRTY_WAKE_LOCKS;
3414 updatePowerStateLocked();
3415 }
3416 }
3417
3418 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3419 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3420 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003421 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003422 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3423 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003424 // Cached inactive processes are never allowed to hold wake locks.
3425 if (mConstants.NO_CACHED_WAKE_LOCKS) {
Santos Cordon12f92eb2019-02-01 21:28:47 +00003426 disabled = mForceSuspendActive
3427 || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003428 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Santos Cordon12f92eb2019-02-01 21:28:47 +00003429 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003430 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003431 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003432 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003433 // for application uids that are not whitelisted.
3434 final UidState state = wakeLock.mUidState;
3435 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3436 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3437 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003438 state.mProcState >
3439 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003440 disabled = true;
3441 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003442 }
3443 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003444 if (wakeLock.mDisabled != disabled) {
3445 wakeLock.mDisabled = disabled;
3446 return true;
3447 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003448 }
3449 return false;
3450 }
3451
Jeff Brown96307042012-07-27 15:51:34 -07003452 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3453 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003454 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003455 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003456
Jeff Brown96307042012-07-27 15:51:34 -07003457 private void setAttentionLightInternal(boolean on, int color) {
Ivailo Karamanolevf773e102020-01-16 16:10:42 +01003458 LogicalLight light;
Jeff Brown96307042012-07-27 15:51:34 -07003459 synchronized (mLock) {
3460 if (!mSystemReady) {
3461 return;
3462 }
3463 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003464 }
Jeff Brown96307042012-07-27 15:51:34 -07003465
3466 // Control light outside of lock.
Ivailo Karamanolevf773e102020-01-16 16:10:42 +01003467 light.setFlashing(color, LogicalLight.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003468 }
3469
Lucas Dupin16cfe452018-02-08 13:14:50 -08003470 private void setDozeAfterScreenOffInternal(boolean on) {
3471 synchronized (mLock) {
3472 mDozeAfterScreenOff = on;
3473 }
3474 }
3475
Yogisha Dixit9c20afa2020-01-15 15:55:51 +00003476 private void suppressAmbientDisplayInternal(String token, boolean suppress) {
3477 if (DEBUG_SPEW) {
3478 Slog.d(TAG, "Suppress ambient display for token " + token + ": " + suppress);
3479 }
3480
3481 if (suppress) {
3482 mAmbientDisplaySuppressionTokens.add(token);
3483 } else {
3484 mAmbientDisplaySuppressionTokens.remove(token);
3485 }
3486
3487 Settings.Secure.putInt(mContext.getContentResolver(),
3488 Settings.Secure.SUPPRESS_DOZE,
3489 Math.min(mAmbientDisplaySuppressionTokens.size(), 1));
3490 }
3491
3492 private String createAmbientDisplayToken(String token, int callingUid) {
3493 return callingUid + "_" + token;
3494 }
3495
Jeff Browne333e672014-10-28 13:48:55 -07003496 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3497 synchronized (mLock) {
3498 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3499 || eventTime < mLastScreenBrightnessBoostTime) {
3500 return;
3501 }
3502
3503 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3504 mLastScreenBrightnessBoostTime = eventTime;
Kweku Adamsf94be8a2019-06-14 13:39:14 -07003505 mScreenBrightnessBoostInProgress = true;
Jeff Browne333e672014-10-28 13:48:55 -07003506 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3507
3508 userActivityNoUpdateLocked(eventTime,
3509 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3510 updatePowerStateLocked();
3511 }
3512 }
3513
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003514 private boolean isScreenBrightnessBoostedInternal() {
3515 synchronized (mLock) {
3516 return mScreenBrightnessBoostInProgress;
3517 }
3518 }
3519
Jeff Browne333e672014-10-28 13:48:55 -07003520 /**
3521 * Called when a screen brightness boost timeout has occurred.
3522 *
3523 * This function must have no other side-effects besides setting the dirty
3524 * bit and calling update power state.
3525 */
3526 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3527 synchronized (mLock) {
3528 if (DEBUG_SPEW) {
3529 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3530 }
3531
3532 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3533 updatePowerStateLocked();
3534 }
3535 }
3536
Fiona Campbelld4eb2952019-11-04 17:19:56 +00003537 // TODO(brightnessfloat): change to float
Jeff Brown96307042012-07-27 15:51:34 -07003538 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3539 synchronized (mLock) {
3540 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3541 mScreenBrightnessOverrideFromWindowManager = brightness;
Fiona Campbelld4eb2952019-11-04 17:19:56 +00003542 mScreenBrightnessOverrideFromWindowManagerFloat =
3543 BrightnessSynchronizer.brightnessIntToFloat(mContext, brightness);
Jeff Brown96307042012-07-27 15:51:34 -07003544 mDirty |= DIRTY_SETTINGS;
3545 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003546 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003547 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003548 }
3549
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003550 private void setUserInactiveOverrideFromWindowManagerInternal() {
3551 synchronized (mLock) {
3552 mUserInactiveOverrideFromWindowManager = true;
3553 mDirty |= DIRTY_USER_ACTIVITY;
3554 updatePowerStateLocked();
3555 }
3556 }
3557
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003558 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3559 synchronized (mLock) {
3560 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3561 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003562 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003563 mDirty |= DIRTY_SETTINGS;
3564 updatePowerStateLocked();
3565 }
3566 }
3567 }
3568
Jeff Brown970d4132014-07-19 11:33:47 -07003569 private void setDozeOverrideFromDreamManagerInternal(
3570 int screenState, int screenBrightness) {
3571 synchronized (mLock) {
3572 if (mDozeScreenStateOverrideFromDreamManager != screenState
3573 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3574 mDozeScreenStateOverrideFromDreamManager = screenState;
3575 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
Fiona Campbelld4eb2952019-11-04 17:19:56 +00003576 mDozeScreenBrightnessOverrideFromDreamManagerFloat =
3577 BrightnessSynchronizer.brightnessIntToFloat(mContext,
3578 mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003579 mDirty |= DIRTY_SETTINGS;
3580 updatePowerStateLocked();
3581 }
3582 }
3583 }
3584
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003585 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3586 synchronized (mLock) {
3587 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3588 mDrawWakeLockOverrideFromSidekick = keepState;
3589 mDirty |= DIRTY_SETTINGS;
3590 updatePowerStateLocked();
3591 }
3592 }
3593 }
3594
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003595 @VisibleForTesting
3596 void setVrModeEnabled(boolean enabled) {
3597 mIsVrModeEnabled = enabled;
3598 }
3599
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003600 private void powerHintInternal(int hintId, int data) {
3601 // Maybe filter the event.
3602 switch (hintId) {
3603 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3604 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3605 return;
3606 }
3607 break;
3608 }
3609
Santos Cordon64a6e612018-08-22 19:27:04 +01003610 mNativeWrapper.nativeSendPowerHint(hintId, data);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003611 }
3612
Alex Kershaw2418ea92018-10-19 17:17:49 +01003613 @VisibleForTesting
3614 boolean wasDeviceIdleForInternal(long ms) {
3615 synchronized (mLock) {
3616 return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3617 }
3618 }
3619
3620 @VisibleForTesting
3621 void onUserActivity() {
3622 synchronized (mLock) {
3623 mLastUserActivityTime = SystemClock.uptimeMillis();
3624 }
3625 }
3626
Santos Cordon12f92eb2019-02-01 21:28:47 +00003627 private boolean forceSuspendInternal(int uid) {
3628 try {
3629 synchronized (mLock) {
3630 mForceSuspendActive = true;
3631 // Place the system in an non-interactive state
3632 goToSleepInternal(SystemClock.uptimeMillis(),
3633 PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3634 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3635
3636 // Disable all the partial wake locks as well
3637 updateWakeLockDisabledStatesLocked();
3638 }
3639
3640 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3641 boolean success = mNativeWrapper.nativeForceSuspend();
3642 if (!success) {
3643 Slog.i(TAG, "Force-Suspending failed in native.");
3644 }
3645 return success;
3646 } finally {
3647 synchronized (mLock) {
3648 mForceSuspendActive = false;
3649 // Re-enable wake locks once again.
3650 updateWakeLockDisabledStatesLocked();
3651 }
3652 }
3653 }
3654
Jeff Brown96307042012-07-27 15:51:34 -07003655 /**
3656 * Low-level function turn the device off immediately, without trying
3657 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003658 *
3659 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003660 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003661 public static void lowLevelShutdown(String reason) {
3662 if (reason == null) {
3663 reason = "";
3664 }
3665 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003666 }
3667
3668 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003669 * Low-level function to reboot the device. On success, this
3670 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003671 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003672 *
3673 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003674 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003675 public static void lowLevelReboot(String reason) {
3676 if (reason == null) {
3677 reason = "";
3678 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003679
3680 // If the reason is "quiescent", it means that the boot process should proceed
3681 // without turning on the screen/lights.
3682 // The "quiescent" property is sticky, meaning that any number
3683 // of subsequent reboots should honor the property until it is reset.
3684 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3685 sQuiescent = true;
3686 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003687 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3688 sQuiescent = true;
3689 reason = reason.substring(0,
3690 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3691 }
3692
3693 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3694 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3695 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003696 }
3697
3698 if (sQuiescent) {
3699 // Pass the optional "quiescent" argument to the bootloader to let it know
3700 // that it should not turn the screen/lights on.
3701 reason = reason + ",quiescent";
3702 }
3703
3704 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003705 try {
Tao Bao90237f72015-05-21 16:25:19 -07003706 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003707 } catch (InterruptedException e) {
3708 Thread.currentThread().interrupt();
3709 }
Tao Bao90237f72015-05-21 16:25:19 -07003710 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003711 }
3712
3713 @Override // Watchdog.Monitor implementation
3714 public void monitor() {
3715 // Grab and release lock for watchdog monitor to detect deadlocks.
3716 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003717 }
Jeff Brown96307042012-07-27 15:51:34 -07003718 }
3719
Jeff Brown6f357d32014-01-15 20:40:55 -08003720 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003721 pw.println("POWER MANAGER (dumpsys power)\n");
3722
Jeff Brown3b971592013-01-09 18:46:37 -08003723 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003724 synchronized (mLock) {
3725 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003726 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003727 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003728 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3729 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003730 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003731 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003732 pw.println(" mBatteryLevel=" + mBatteryLevel);
3733 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003734 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003735 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003736 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003737 pw.println(" mBootCompleted=" + mBootCompleted);
3738 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003739 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3740 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003741 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003742 pw.print(" mNotifyLongScheduled=");
3743 if (mNotifyLongScheduled == 0) {
3744 pw.print("(none)");
3745 } else {
3746 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3747 }
3748 pw.println();
3749 pw.print(" mNotifyLongDispatched=");
3750 if (mNotifyLongDispatched == 0) {
3751 pw.print("(none)");
3752 } else {
3753 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3754 }
3755 pw.println();
3756 pw.print(" mNotifyLongNextCheck=");
3757 if (mNotifyLongNextCheck == 0) {
3758 pw.print("(none)");
3759 } else {
3760 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3761 }
3762 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003763 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3764 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3765 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003766 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003767 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003768 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003769 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3770 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003771 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003772 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3773 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Calin Tatarua3805722018-08-09 16:41:28 +02003774 pw.println(" mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
Jeff Brown96307042012-07-27 15:51:34 -07003775 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3776 pw.println(" mLastUserActivityTimeNoChangeLights="
3777 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003778 pw.println(" mLastInteractivePowerHintTime="
3779 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003780 pw.println(" mLastScreenBrightnessBoostTime="
3781 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3782 pw.println(" mScreenBrightnessBoostInProgress="
3783 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003784 pw.println(" mDisplayReady=" + mDisplayReady);
3785 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003786 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003787
3788 pw.println();
3789 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003790 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3791 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3792 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3793 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003794 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3795 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003796 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3797 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3798 pw.println(" mTheaterModeEnabled="
3799 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003800 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3801 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003802 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003803 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3804 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3805 + mDreamsActivatedOnSleepByDefaultConfig);
3806 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3807 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003808 pw.println(" mDreamsEnabledOnBatteryConfig="
3809 + mDreamsEnabledOnBatteryConfig);
3810 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3811 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3812 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3813 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3814 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3815 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003816 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003817 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003818 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003819 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003820 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3821 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3822 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Robert Horvath5560f382019-07-10 10:46:38 +02003823 pw.println(" mAttentiveTimeoutConfig=" + mAttentiveTimeoutConfig);
3824 pw.println(" mAttentiveTimeoutSetting=" + mAttentiveTimeoutSetting);
3825 pw.println(" mAttentiveWarningDurationConfig=" + mAttentiveWarningDurationConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003826 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003827 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003828 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3829 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3830 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3831 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003832 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
Fiona Campbelld4eb2952019-11-04 17:19:56 +00003833 pw.println(" mScreenBrightnessOverrideFromWindowManagerFloat="
3834 + mScreenBrightnessOverrideFromWindowManagerFloat);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003835 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3836 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003837 pw.println(" mUserInactiveOverrideFromWindowManager="
3838 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003839 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3840 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003841 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003842 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3843 + mDozeScreenBrightnessOverrideFromDreamManager);
Fiona Campbelld4eb2952019-11-04 17:19:56 +00003844 pw.println(" mScreenBrightnessSettingMinimumFloat=" + mScreenBrightnessSettingMinimum);
3845 pw.println(" mScreenBrightnessSettingMaximumFloat=" + mScreenBrightnessSettingMaximum);
3846 pw.println(" mScreenBrightnessSettingDefaultFloat=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003847 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003848 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003849 pw.println(" mForegroundProfile=" + mForegroundProfile);
Beverly478722e2019-10-14 11:16:57 -04003850 pw.println(" mUserId=" + mUserId);
Jeff Brown96307042012-07-27 15:51:34 -07003851
Robert Horvath5560f382019-07-10 10:46:38 +02003852 final long attentiveTimeout = getAttentiveTimeoutLocked();
3853 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
3854 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01003855 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003856 pw.println();
Robert Horvath5560f382019-07-10 10:46:38 +02003857 pw.println("Attentive timeout: " + attentiveTimeout + " ms");
Jeff Brown05af6ad2014-09-30 20:54:30 -07003858 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003859 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3860 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3861
Jeff Brown96307042012-07-27 15:51:34 -07003862 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003863 pw.print("UID states (changing=");
3864 pw.print(mUidsChanging);
3865 pw.print(" changed=");
3866 pw.print(mUidsChanged);
3867 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003868 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003869 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003870 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003871 pw.print(": ");
3872 if (state.mActive) pw.print(" ACTIVE ");
3873 else pw.print("INACTIVE ");
3874 pw.print(" count=");
3875 pw.print(state.mNumWakeLocks);
3876 pw.print(" state=");
3877 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003878 }
3879
3880 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003881 pw.println("Looper state:");
3882 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3883
3884 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003885 pw.println("Wake Locks: size=" + mWakeLocks.size());
3886 for (WakeLock wl : mWakeLocks) {
3887 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003888 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003889
Jeff Brown96307042012-07-27 15:51:34 -07003890 pw.println();
3891 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3892 for (SuspendBlocker sb : mSuspendBlockers) {
3893 pw.println(" " + sb);
3894 }
3895
Jeff Brownc38c9be2012-10-04 13:16:19 -07003896 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003897 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003898
jackqdyulei455e90a2017-02-09 15:29:16 -08003899 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003900 mBatterySaverStateMachine.dump(pw);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08003901 mAttentionDetector.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003902
Pavel Grafov28939982017-10-03 15:11:52 +01003903 pw.println();
3904 final int numProfiles = mProfilePowerState.size();
3905 pw.println("Profile power states: size=" + numProfiles);
3906 for (int i = 0; i < numProfiles; i++) {
3907 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3908 pw.print(" mUserId=");
3909 pw.print(profile.mUserId);
3910 pw.print(" mScreenOffTimeout=");
3911 pw.print(profile.mScreenOffTimeout);
3912 pw.print(" mWakeLockSummary=");
3913 pw.print(profile.mWakeLockSummary);
3914 pw.print(" mLastUserActivityTime=");
3915 pw.print(profile.mLastUserActivityTime);
3916 pw.print(" mLockingNotified=");
3917 pw.println(profile.mLockingNotified);
3918 }
3919
Jeff Brown3b971592013-01-09 18:46:37 -08003920 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003921 }
3922
Jeff Brown3b971592013-01-09 18:46:37 -08003923 if (wcd != null) {
3924 wcd.dump(pw);
3925 }
Santos Cordon9204cc82019-11-21 11:45:28 +00003926
3927 if (mNotifier != null) {
3928 mNotifier.dump(pw);
3929 }
Jeff Brown96307042012-07-27 15:51:34 -07003930 }
3931
Netta P958d0a52017-02-07 11:20:55 -08003932 private void dumpProto(FileDescriptor fd) {
3933 final WirelessChargerDetector wcd;
3934 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3935
3936 synchronized (mLock) {
3937 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003938 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3939 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3940 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3941 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3942 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3943 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003944 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003945 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003946 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003947 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3948 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3949 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3950 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3951 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003952 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003953 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003954 mHalAutoSuspendModeEnabled);
3955 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003956 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003957 mHalInteractiveModeEnabled);
3958
Kweku Adamse6b00c22017-10-23 16:46:45 -07003959 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003960 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003961 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003962 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3963 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003964 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003965 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3966 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003967 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003968 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3969 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003970 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003971 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3972 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003973 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003974 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3975 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003976 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003977 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3978 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003979 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003980 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3981 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003982 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003983 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3984 proto.end(activeWakeLocksToken);
3985
Kweku Adamse6b00c22017-10-23 16:46:45 -07003986 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3987 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3988 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003989
Kweku Adamse6b00c22017-10-23 16:46:45 -07003990 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003991 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003992 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003993 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3994 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003995 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003996 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3997 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003998 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003999 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
4000 proto.end(userActivityToken);
4001
4002 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004003 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08004004 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07004005 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
4006 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07004007 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
4008 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
4009 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08004010
4011 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004012 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08004013 }
4014 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07004015 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08004016 }
4017
Kweku Adamse6b00c22017-10-23 16:46:45 -07004018 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
4019 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
4020 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08004021 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004022 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08004023 mLastUserActivityTimeNoChangeLights);
4024 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004025 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08004026 mLastInteractivePowerHintTime);
4027 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004028 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08004029 mLastScreenBrightnessBoostTime);
4030 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004031 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08004032 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07004033 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08004034 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004035 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08004036 mHoldingWakeLockSuspendBlocker);
4037 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07004038 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08004039 mHoldingDisplaySuspendBlocker);
4040
4041 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07004042 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08004043 proto.write(
4044 PowerServiceSettingsAndConfigurationDumpProto
4045 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
4046 mDecoupleHalAutoSuspendModeFromDisplayConfig);
4047 proto.write(
4048 PowerServiceSettingsAndConfigurationDumpProto
4049 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
4050 mDecoupleHalInteractiveModeFromDisplayConfig);
4051 proto.write(
4052 PowerServiceSettingsAndConfigurationDumpProto
4053 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
4054 mWakeUpWhenPluggedOrUnpluggedConfig);
4055 proto.write(
4056 PowerServiceSettingsAndConfigurationDumpProto
4057 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
4058 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
4059 proto.write(
4060 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
4061 mTheaterModeEnabled);
4062 proto.write(
4063 PowerServiceSettingsAndConfigurationDumpProto
4064 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
4065 mSuspendWhenScreenOffDueToProximityConfig);
4066 proto.write(
4067 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
4068 mDreamsSupportedConfig);
4069 proto.write(
4070 PowerServiceSettingsAndConfigurationDumpProto
4071 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
4072 mDreamsEnabledByDefaultConfig);
4073 proto.write(
4074 PowerServiceSettingsAndConfigurationDumpProto
4075 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
4076 mDreamsActivatedOnSleepByDefaultConfig);
4077 proto.write(
4078 PowerServiceSettingsAndConfigurationDumpProto
4079 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
4080 mDreamsActivatedOnDockByDefaultConfig);
4081 proto.write(
4082 PowerServiceSettingsAndConfigurationDumpProto
4083 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
4084 mDreamsEnabledOnBatteryConfig);
4085 proto.write(
4086 PowerServiceSettingsAndConfigurationDumpProto
4087 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
4088 mDreamsBatteryLevelMinimumWhenPoweredConfig);
4089 proto.write(
4090 PowerServiceSettingsAndConfigurationDumpProto
4091 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
4092 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
4093 proto.write(
4094 PowerServiceSettingsAndConfigurationDumpProto
4095 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
4096 mDreamsBatteryLevelDrainCutoffConfig);
4097 proto.write(
4098 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
4099 mDreamsEnabledSetting);
4100 proto.write(
4101 PowerServiceSettingsAndConfigurationDumpProto
4102 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
4103 mDreamsActivateOnSleepSetting);
4104 proto.write(
4105 PowerServiceSettingsAndConfigurationDumpProto
4106 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
4107 mDreamsActivateOnDockSetting);
4108 proto.write(
4109 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08004110 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08004111 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08004112 PowerServiceSettingsAndConfigurationDumpProto
4113 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
4114 mMinimumScreenOffTimeoutConfig);
4115 proto.write(
4116 PowerServiceSettingsAndConfigurationDumpProto
4117 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
4118 mMaximumScreenDimDurationConfig);
4119 proto.write(
4120 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
4121 mMaximumScreenDimRatioConfig);
4122 proto.write(
4123 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
4124 mScreenOffTimeoutSetting);
4125 proto.write(
4126 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
4127 mSleepTimeoutSetting);
4128 proto.write(
Robert Horvath5560f382019-07-10 10:46:38 +02004129 PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_SETTING_MS,
4130 mAttentiveTimeoutSetting);
4131 proto.write(
4132 PowerServiceSettingsAndConfigurationDumpProto.ATTENTIVE_TIMEOUT_CONFIG_MS,
4133 mAttentiveTimeoutConfig);
4134 proto.write(
4135 PowerServiceSettingsAndConfigurationDumpProto
4136 .ATTENTIVE_WARNING_DURATION_CONFIG_MS,
4137 mAttentiveWarningDurationConfig);
4138 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08004139 PowerServiceSettingsAndConfigurationDumpProto
4140 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01004141 // Clamp to int32
4142 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08004143 proto.write(
4144 PowerServiceSettingsAndConfigurationDumpProto
4145 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
4146 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
4147
4148 final long stayOnWhilePluggedInToken =
4149 proto.start(
4150 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
4151 proto.write(
4152 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
4153 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
4154 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
4155 proto.write(
4156 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
4157 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
4158 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
4159 proto.write(
4160 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
4161 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
4162 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
4163 != 0));
4164 proto.end(stayOnWhilePluggedInToken);
4165
4166 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08004167 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
4168 mScreenBrightnessModeSetting);
4169 proto.write(
4170 PowerServiceSettingsAndConfigurationDumpProto
4171 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
Fiona Campbelld4eb2952019-11-04 17:19:56 +00004172 mScreenBrightnessOverrideFromWindowManagerFloat);
Netta P958d0a52017-02-07 11:20:55 -08004173 proto.write(
4174 PowerServiceSettingsAndConfigurationDumpProto
4175 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
4176 mUserActivityTimeoutOverrideFromWindowManager);
4177 proto.write(
4178 PowerServiceSettingsAndConfigurationDumpProto
4179 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
4180 mUserInactiveOverrideFromWindowManager);
4181 proto.write(
4182 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08004183 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
4184 mDozeScreenStateOverrideFromDreamManager);
4185 proto.write(
4186 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004187 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
4188 mDrawWakeLockOverrideFromSidekick);
4189 proto.write(
4190 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08004191 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
4192 mDozeScreenBrightnessOverrideFromDreamManager);
4193
4194 final long screenBrightnessSettingLimitsToken =
4195 proto.start(
4196 PowerServiceSettingsAndConfigurationDumpProto
4197 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
4198 proto.write(
4199 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4200 .SETTING_MINIMUM,
4201 mScreenBrightnessSettingMinimum);
4202 proto.write(
4203 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4204 .SETTING_MAXIMUM,
4205 mScreenBrightnessSettingMaximum);
4206 proto.write(
4207 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
4208 .SETTING_DEFAULT,
4209 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08004210 proto.end(screenBrightnessSettingLimitsToken);
4211
4212 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08004213 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
4214 mDoubleTapWakeEnabled);
4215 proto.write(
4216 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
4217 mIsVrModeEnabled);
4218 proto.end(settingsAndConfigurationToken);
4219
Robert Horvath5560f382019-07-10 10:46:38 +02004220 final long attentiveTimeout = getAttentiveTimeoutLocked();
4221 final long sleepTimeout = getSleepTimeoutLocked(attentiveTimeout);
4222 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout, attentiveTimeout);
Pavel Grafov28939982017-10-03 15:11:52 +01004223 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Robert Horvath5560f382019-07-10 10:46:38 +02004224 proto.write(PowerManagerServiceDumpProto.ATTENTIVE_TIMEOUT_MS, attentiveTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07004225 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
4226 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
4227 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
4228 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
4229 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08004230
4231 for (int i = 0; i < mUidState.size(); i++) {
4232 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07004233 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08004234 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07004235 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
4236 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
4237 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
4238 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08004239 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
4240 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08004241 proto.end(uIDToken);
4242 }
4243
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004244 mBatterySaverStateMachine.dumpProto(proto,
4245 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
4246
Jeffrey Huangcb782852019-12-05 11:28:11 -08004247 mHandler.getLooper().dumpDebug(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08004248
4249 for (WakeLock wl : mWakeLocks) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08004250 wl.dumpDebug(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08004251 }
4252
4253 for (SuspendBlocker sb : mSuspendBlockers) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08004254 sb.dumpDebug(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08004255 }
4256 wcd = mWirelessChargerDetector;
4257 }
4258
4259 if (wcd != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08004260 wcd.dumpDebug(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08004261 }
4262 proto.flush();
4263 }
4264
Daichi Hirono82ab9802016-03-02 13:23:29 +09004265 private void incrementBootCount() {
4266 synchronized (mLock) {
4267 int count;
4268 try {
4269 count = Settings.Global.getInt(
4270 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
4271 } catch (SettingNotFoundException e) {
4272 count = 0;
4273 }
4274 Settings.Global.putInt(
4275 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
4276 }
4277 }
4278
Jeff Brown96307042012-07-27 15:51:34 -07004279 private static WorkSource copyWorkSource(WorkSource workSource) {
4280 return workSource != null ? new WorkSource(workSource) : null;
4281 }
4282
Santos Cordon9b510a22018-08-24 16:42:54 +01004283 @VisibleForTesting
4284 final class BatteryReceiver extends BroadcastReceiver {
Jeff Brown96307042012-07-27 15:51:34 -07004285 @Override
4286 public void onReceive(Context context, Intent intent) {
4287 synchronized (mLock) {
4288 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05004289 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05004290 }
4291 }
4292
John Spurlockf4f6b4c2012-08-25 12:08:03 -04004293 private final class DreamReceiver extends BroadcastReceiver {
4294 @Override
4295 public void onReceive(Context context, Intent intent) {
4296 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07004297 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04004298 }
4299 }
4300 }
4301
Santos Cordon9b510a22018-08-24 16:42:54 +01004302 @VisibleForTesting
4303 final class UserSwitchedReceiver extends BroadcastReceiver {
Jeff Brownd4935962012-09-25 13:27:20 -07004304 @Override
4305 public void onReceive(Context context, Intent intent) {
4306 synchronized (mLock) {
4307 handleSettingsChangedLocked();
4308 }
4309 }
4310 }
4311
Jeff Brownec6aa592012-10-17 20:30:25 -07004312 private final class DockReceiver extends BroadcastReceiver {
4313 @Override
4314 public void onReceive(Context context, Intent intent) {
4315 synchronized (mLock) {
4316 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
4317 Intent.EXTRA_DOCK_STATE_UNDOCKED);
4318 if (mDockState != dockState) {
4319 mDockState = dockState;
4320 mDirty |= DIRTY_DOCK_STATE;
4321 updatePowerStateLocked();
4322 }
4323 }
4324 }
4325 }
4326
Jeff Brown96307042012-07-27 15:51:34 -07004327 private final class SettingsObserver extends ContentObserver {
4328 public SettingsObserver(Handler handler) {
4329 super(handler);
4330 }
4331
4332 @Override
4333 public void onChange(boolean selfChange, Uri uri) {
4334 synchronized (mLock) {
4335 handleSettingsChangedLocked();
4336 }
4337 }
4338 }
4339
Ruben Brunkc7be3be2016-04-01 17:07:51 -07004340 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07004341 @Override
4342 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07004343 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07004344
4345 synchronized (mLock) {
4346 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07004347 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07004348 mDirty |= DIRTY_VR_MODE_CHANGED;
4349 updatePowerStateLocked();
4350 }
4351 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07004352 }
4353 };
4354
Jeff Brown96307042012-07-27 15:51:34 -07004355 /**
4356 * Handler for asynchronous operations performed by the power manager.
4357 */
4358 private final class PowerManagerHandler extends Handler {
4359 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07004360 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07004361 }
4362
4363 @Override
4364 public void handleMessage(Message msg) {
4365 switch (msg.what) {
4366 case MSG_USER_ACTIVITY_TIMEOUT:
4367 handleUserActivityTimeout();
4368 break;
4369 case MSG_SANDMAN:
4370 handleSandman();
4371 break;
Jeff Browne333e672014-10-28 13:48:55 -07004372 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
4373 handleScreenBrightnessBoostTimeout();
4374 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004375 case MSG_CHECK_FOR_LONG_WAKELOCKS:
4376 checkForLongWakeLocks();
4377 break;
Robert Horvath5560f382019-07-10 10:46:38 +02004378 case MSG_ATTENTIVE_TIMEOUT:
4379 handleAttentiveTimeout();
4380 break;
Jeff Brown96307042012-07-27 15:51:34 -07004381 }
4382 }
4383 }
4384
4385 /**
4386 * Represents a wake lock that has been acquired by an application.
4387 */
Santos Cordon9204cc82019-11-21 11:45:28 +00004388 /* package */ final class WakeLock implements IBinder.DeathRecipient {
Jeff Brown96307042012-07-27 15:51:34 -07004389 public final IBinder mLock;
4390 public int mFlags;
4391 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004392 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07004393 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004394 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004395 public final int mOwnerUid;
4396 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004397 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004398 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07004399 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004400 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004401 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07004402
Dianne Hackborn713df152013-05-17 11:27:57 -07004403 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004404 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
4405 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07004406 mLock = lock;
4407 mFlags = flags;
4408 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004409 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07004410 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004411 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004412 mOwnerUid = ownerUid;
4413 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004414 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07004415 }
4416
4417 @Override
4418 public void binderDied() {
4419 PowerManagerService.this.handleWakeLockDeath(this);
4420 }
4421
4422 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4423 int ownerUid, int ownerPid) {
4424 return mFlags == flags
4425 && mTag.equals(tag)
4426 && hasSameWorkSource(workSource)
4427 && mOwnerUid == ownerUid
4428 && mOwnerPid == ownerPid;
4429 }
4430
Dianne Hackborn713df152013-05-17 11:27:57 -07004431 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004432 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07004433 if (!mPackageName.equals(packageName)) {
4434 throw new IllegalStateException("Existing wake lock package name changed: "
4435 + mPackageName + " to " + packageName);
4436 }
4437 if (mOwnerUid != ownerUid) {
4438 throw new IllegalStateException("Existing wake lock uid changed: "
4439 + mOwnerUid + " to " + ownerUid);
4440 }
4441 if (mOwnerPid != ownerPid) {
4442 throw new IllegalStateException("Existing wake lock pid changed: "
4443 + mOwnerPid + " to " + ownerPid);
4444 }
Jeff Brown96307042012-07-27 15:51:34 -07004445 mFlags = flags;
4446 mTag = tag;
4447 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004448 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004449 }
4450
4451 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00004452 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07004453 }
4454
4455 public void updateWorkSource(WorkSource workSource) {
4456 mWorkSource = copyWorkSource(workSource);
4457 }
4458
4459 @Override
4460 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004461 StringBuilder sb = new StringBuilder();
4462 sb.append(getLockLevelString());
4463 sb.append(" '");
4464 sb.append(mTag);
4465 sb.append("'");
4466 sb.append(getLockFlagsString());
4467 if (mDisabled) {
4468 sb.append(" DISABLED");
4469 }
4470 if (mNotifiedAcquired) {
4471 sb.append(" ACQ=");
4472 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4473 }
4474 if (mNotifiedLong) {
4475 sb.append(" LONG");
4476 }
4477 sb.append(" (uid=");
4478 sb.append(mOwnerUid);
4479 if (mOwnerPid != 0) {
4480 sb.append(" pid=");
4481 sb.append(mOwnerPid);
4482 }
4483 if (mWorkSource != null) {
4484 sb.append(" ws=");
4485 sb.append(mWorkSource);
4486 }
4487 sb.append(")");
4488 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004489 }
4490
Jeffrey Huangcb782852019-12-05 11:28:11 -08004491 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
Netta P958d0a52017-02-07 11:20:55 -08004492 final long wakeLockToken = proto.start(fieldId);
4493 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4494 proto.write(WakeLockProto.TAG, mTag);
4495
4496 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4497 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4498 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4499 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4500 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4501 proto.end(wakeLockFlagsToken);
4502
4503 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4504 if (mNotifiedAcquired) {
4505 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4506 }
4507 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4508 proto.write(WakeLockProto.UID, mOwnerUid);
4509 proto.write(WakeLockProto.PID, mOwnerPid);
4510
4511 if (mWorkSource != null) {
Jeffrey Huangcb782852019-12-05 11:28:11 -08004512 mWorkSource.dumpDebug(proto, WakeLockProto.WORK_SOURCE);
Netta P958d0a52017-02-07 11:20:55 -08004513 }
4514 proto.end(wakeLockToken);
4515 }
4516
Jeff Brown26875502014-01-30 21:47:47 -08004517 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004518 private String getLockLevelString() {
4519 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4520 case PowerManager.FULL_WAKE_LOCK:
4521 return "FULL_WAKE_LOCK ";
4522 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4523 return "SCREEN_BRIGHT_WAKE_LOCK ";
4524 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4525 return "SCREEN_DIM_WAKE_LOCK ";
4526 case PowerManager.PARTIAL_WAKE_LOCK:
4527 return "PARTIAL_WAKE_LOCK ";
4528 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4529 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004530 case PowerManager.DOZE_WAKE_LOCK:
4531 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004532 case PowerManager.DRAW_WAKE_LOCK:
4533 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004534 default:
4535 return "??? ";
4536 }
4537 }
4538
4539 private String getLockFlagsString() {
4540 String result = "";
4541 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4542 result += " ACQUIRE_CAUSES_WAKEUP";
4543 }
4544 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4545 result += " ON_AFTER_RELEASE";
4546 }
4547 return result;
4548 }
4549 }
4550
4551 private final class SuspendBlockerImpl implements SuspendBlocker {
4552 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004553 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004554 private int mReferenceCount;
4555
4556 public SuspendBlockerImpl(String name) {
4557 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004558 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004559 }
4560
4561 @Override
4562 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004563 try {
Jeff Brown96307042012-07-27 15:51:34 -07004564 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004565 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004566 + "\" was finalized without being released!");
4567 mReferenceCount = 0;
Santos Cordon64a6e612018-08-22 19:27:04 +01004568 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004569 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004570 }
4571 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004572 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004573 }
4574 }
4575
Craig Mautner75fc9de2012-06-18 16:53:27 -07004576 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004577 public void acquire() {
4578 synchronized (this) {
4579 mReferenceCount += 1;
4580 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004581 if (DEBUG_SPEW) {
4582 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4583 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004584 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +01004585 mNativeWrapper.nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004586 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004587 }
4588 }
4589
Craig Mautner75fc9de2012-06-18 16:53:27 -07004590 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004591 public void release() {
4592 synchronized (this) {
4593 mReferenceCount -= 1;
4594 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004595 if (DEBUG_SPEW) {
4596 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4597 }
Santos Cordon64a6e612018-08-22 19:27:04 +01004598 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004599 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004600 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004601 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004602 + "\" was released without being acquired!", new Throwable());
4603 mReferenceCount = 0;
4604 }
4605 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004606 }
Jeff Brown96307042012-07-27 15:51:34 -07004607
4608 @Override
4609 public String toString() {
4610 synchronized (this) {
4611 return mName + ": ref count=" + mReferenceCount;
4612 }
4613 }
Netta P958d0a52017-02-07 11:20:55 -08004614
Jeffrey Huangcb782852019-12-05 11:28:11 -08004615 public void dumpDebug(ProtoOutputStream proto, long fieldId) {
Netta P958d0a52017-02-07 11:20:55 -08004616 final long sbToken = proto.start(fieldId);
4617 synchronized (this) {
4618 proto.write(SuspendBlockerProto.NAME, mName);
4619 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4620 }
4621 proto.end(sbToken);
4622 }
Jeff Brown96307042012-07-27 15:51:34 -07004623 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004624
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004625 static final class UidState {
4626 final int mUid;
4627 int mNumWakeLocks;
4628 int mProcState;
4629 boolean mActive;
4630
4631 UidState(int uid) {
4632 mUid = uid;
4633 }
4634 }
4635
Santos Cordon64a6e612018-08-22 19:27:04 +01004636 @VisibleForTesting
4637 final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004638 @Override
4639 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4640 FileDescriptor err, String[] args, ShellCallback callback,
4641 ResultReceiver resultReceiver) {
4642 (new PowerManagerShellCommand(this)).exec(
4643 this, in, out, err, args, callback, resultReceiver);
4644 }
4645
Jeff Brown6f357d32014-01-15 20:40:55 -08004646 @Override // Binder call
4647 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4648 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004649 if (uid < 0) {
4650 uid = Binder.getCallingUid();
4651 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004652 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004653 }
4654
4655 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004656 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004657 if (!mSystemReady) {
4658 // Service not ready yet, so who the heck cares about power hints, bah.
4659 return;
4660 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004661 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004662 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004663 }
4664
4665 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004666 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004667 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004668 if (lock == null) {
4669 throw new IllegalArgumentException("lock must not be null");
4670 }
4671 if (packageName == null) {
4672 throw new IllegalArgumentException("packageName must not be null");
4673 }
4674 PowerManager.validateWakeLockParameters(flags, tag);
4675
4676 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004677 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4678 mContext.enforceCallingOrSelfPermission(
4679 android.Manifest.permission.DEVICE_POWER, null);
4680 }
Narayan Kamath81822022017-12-08 11:56:01 +00004681 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004682 mContext.enforceCallingOrSelfPermission(
4683 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4684 } else {
4685 ws = null;
4686 }
4687
4688 final int uid = Binder.getCallingUid();
4689 final int pid = Binder.getCallingPid();
4690 final long ident = Binder.clearCallingIdentity();
4691 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004692 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004693 } finally {
4694 Binder.restoreCallingIdentity(ident);
4695 }
4696 }
4697
4698 @Override // Binder call
4699 public void releaseWakeLock(IBinder lock, int flags) {
4700 if (lock == null) {
4701 throw new IllegalArgumentException("lock must not be null");
4702 }
4703
4704 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4705
4706 final long ident = Binder.clearCallingIdentity();
4707 try {
4708 releaseWakeLockInternal(lock, flags);
4709 } finally {
4710 Binder.restoreCallingIdentity(ident);
4711 }
4712 }
4713
4714 @Override // Binder call
4715 public void updateWakeLockUids(IBinder lock, int[] uids) {
4716 WorkSource ws = null;
4717
4718 if (uids != null) {
4719 ws = new WorkSource();
4720 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4721 // one at a time?
4722 for (int i = 0; i < uids.length; i++) {
4723 ws.add(uids[i]);
4724 }
4725 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004726 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004727 }
4728
4729 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004730 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004731 if (lock == null) {
4732 throw new IllegalArgumentException("lock must not be null");
4733 }
4734
4735 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004736 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004737 mContext.enforceCallingOrSelfPermission(
4738 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4739 } else {
4740 ws = null;
4741 }
4742
Dianne Hackbornd953c532014-08-16 18:17:38 -07004743 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004744 final long ident = Binder.clearCallingIdentity();
4745 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004746 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004747 } finally {
4748 Binder.restoreCallingIdentity(ident);
4749 }
4750 }
4751
4752 @Override // Binder call
4753 public boolean isWakeLockLevelSupported(int level) {
4754 final long ident = Binder.clearCallingIdentity();
4755 try {
4756 return isWakeLockLevelSupportedInternal(level);
4757 } finally {
4758 Binder.restoreCallingIdentity(ident);
4759 }
4760 }
4761
4762 @Override // Binder call
4763 public void userActivity(long eventTime, int event, int flags) {
4764 final long now = SystemClock.uptimeMillis();
4765 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004766 != PackageManager.PERMISSION_GRANTED
4767 && mContext.checkCallingOrSelfPermission(
4768 android.Manifest.permission.USER_ACTIVITY)
4769 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004770 // Once upon a time applications could call userActivity().
4771 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4772 // request instead of throwing a SecurityException so we don't break old apps.
4773 synchronized (mLock) {
4774 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4775 mLastWarningAboutUserActivityPermission = now;
4776 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004777 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4778 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004779 + " pid=" + Binder.getCallingPid()
4780 + " uid=" + Binder.getCallingUid());
4781 }
4782 }
4783 return;
4784 }
4785
Jim Millerdca15d22015-06-16 20:55:13 -07004786 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004787 throw new IllegalArgumentException("event time must not be in the future");
4788 }
4789
4790 final int uid = Binder.getCallingUid();
4791 final long ident = Binder.clearCallingIdentity();
4792 try {
4793 userActivityInternal(eventTime, event, flags, uid);
4794 } finally {
4795 Binder.restoreCallingIdentity(ident);
4796 }
4797 }
4798
4799 @Override // Binder call
Michael Wrighte3001042019-02-05 00:13:14 +00004800 public void wakeUp(long eventTime, @WakeReason int reason, String details,
4801 String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004802 if (eventTime > SystemClock.uptimeMillis()) {
4803 throw new IllegalArgumentException("event time must not be in the future");
4804 }
4805
4806 mContext.enforceCallingOrSelfPermission(
4807 android.Manifest.permission.DEVICE_POWER, null);
4808
Jeff Brownc12035c2014-08-13 18:52:25 -07004809 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004810 final long ident = Binder.clearCallingIdentity();
4811 try {
Michael Wrighte3001042019-02-05 00:13:14 +00004812 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004813 } finally {
4814 Binder.restoreCallingIdentity(ident);
4815 }
4816 }
4817
4818 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004819 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004820 if (eventTime > SystemClock.uptimeMillis()) {
4821 throw new IllegalArgumentException("event time must not be in the future");
4822 }
4823
4824 mContext.enforceCallingOrSelfPermission(
4825 android.Manifest.permission.DEVICE_POWER, null);
4826
Jeff Brownc12035c2014-08-13 18:52:25 -07004827 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004828 final long ident = Binder.clearCallingIdentity();
4829 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004830 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004831 } finally {
4832 Binder.restoreCallingIdentity(ident);
4833 }
4834 }
4835
4836 @Override // Binder call
4837 public void nap(long eventTime) {
4838 if (eventTime > SystemClock.uptimeMillis()) {
4839 throw new IllegalArgumentException("event time must not be in the future");
4840 }
4841
4842 mContext.enforceCallingOrSelfPermission(
4843 android.Manifest.permission.DEVICE_POWER, null);
4844
Jeff Brownc12035c2014-08-13 18:52:25 -07004845 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004846 final long ident = Binder.clearCallingIdentity();
4847 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004848 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004849 } finally {
4850 Binder.restoreCallingIdentity(ident);
4851 }
4852 }
4853
Fiona Campbelld4eb2952019-11-04 17:19:56 +00004854 public float getBrightnessConstraint(int constraint) {
4855 switch (constraint) {
4856 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM:
4857 return mScreenBrightnessMinimum;
4858 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM:
4859 return mScreenBrightnessMaximum;
4860 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT:
4861 return mScreenBrightnessDefault;
4862 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DIM:
4863 return mScreenBrightnessDim;
4864 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DOZE:
4865 return mScreenBrightnessDoze;
4866 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MINIMUM_VR:
4867 return mScreenBrightnessMinimumVr;
4868 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_MAXIMUM_VR:
4869 return mScreenBrightnessMaximumVr;
4870 case PowerManager.BRIGHTNESS_CONSTRAINT_TYPE_DEFAULT_VR:
4871 return mScreenBrightnessDefaultVr;
4872 default:
4873 return PowerManager.BRIGHTNESS_INVALID_FLOAT;
4874 }
4875 }
4876
Jeff Brown6f357d32014-01-15 20:40:55 -08004877 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004878 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004879 final long ident = Binder.clearCallingIdentity();
4880 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004881 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004882 } finally {
4883 Binder.restoreCallingIdentity(ident);
4884 }
4885 }
4886
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004887 @Override // Binder call
4888 public boolean isPowerSaveMode() {
4889 final long ident = Binder.clearCallingIdentity();
4890 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004891 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004892 } finally {
4893 Binder.restoreCallingIdentity(ident);
4894 }
4895 }
4896
jackqdyulei455e90a2017-02-09 15:29:16 -08004897 // Binder call
4898 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4899 final long ident = Binder.clearCallingIdentity();
4900 try {
Kweku Adams9f488e22019-01-14 16:25:08 -08004901 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
jackqdyulei455e90a2017-02-09 15:29:16 -08004902 } finally {
4903 Binder.restoreCallingIdentity(ident);
4904 }
4905 }
4906
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004907 @Override // Binder call
Salvador Martinezc8c4c5d2019-03-11 11:11:37 -07004908 public boolean setPowerSaveModeEnabled(boolean enabled) {
Salvador Martineza80bbab2018-09-24 10:36:11 -07004909 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4910 != PackageManager.PERMISSION_GRANTED) {
4911 mContext.enforceCallingOrSelfPermission(
4912 android.Manifest.permission.DEVICE_POWER, null);
4913 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004914 final long ident = Binder.clearCallingIdentity();
4915 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004916 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004917 } finally {
4918 Binder.restoreCallingIdentity(ident);
4919 }
4920 }
4921
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004922 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004923 public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
Salvador Martinez812ea752018-10-19 13:03:20 -07004924 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4925 "updateDynamicPowerSavings");
4926 final long ident = Binder.clearCallingIdentity();
4927 try {
4928 final ContentResolver resolver = mContext.getContentResolver();
4929 boolean success = Settings.Global.putInt(resolver,
4930 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4931 disableThreshold);
4932 if (success) {
4933 // abort updating if we weren't able to succeed on the threshold
4934 success &= Settings.Global.putInt(resolver,
4935 Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004936 powerSaveHint ? 1 : 0);
Salvador Martinez812ea752018-10-19 13:03:20 -07004937 }
4938 return success;
4939 } finally {
4940 Binder.restoreCallingIdentity(ident);
4941 }
4942 }
4943
4944 @Override // Binder call
Kweku Adams9f488e22019-01-14 16:25:08 -08004945 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4946 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4947 != PackageManager.PERMISSION_GRANTED) {
4948 mContext.enforceCallingOrSelfPermission(
4949 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4950 }
4951 final long ident = Binder.clearCallingIdentity();
4952 try {
4953 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4954 } finally {
4955 Binder.restoreCallingIdentity(ident);
4956 }
4957 }
4958
4959 @Override // Binder call
4960 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4961 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4962 != PackageManager.PERMISSION_GRANTED) {
4963 mContext.enforceCallingOrSelfPermission(
4964 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4965 }
4966 final long ident = Binder.clearCallingIdentity();
4967 try {
4968 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4969 } finally {
4970 Binder.restoreCallingIdentity(ident);
4971 }
4972 }
4973
4974 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004975 public int getPowerSaveModeTrigger() {
Salvador Martinez812ea752018-10-19 13:03:20 -07004976 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4977 final long ident = Binder.clearCallingIdentity();
4978 try {
4979 return Settings.Global.getInt(mContext.getContentResolver(),
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004980 Settings.Global.AUTOMATIC_POWER_SAVE_MODE,
4981 PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE);
Salvador Martinez812ea752018-10-19 13:03:20 -07004982 } finally {
4983 Binder.restoreCallingIdentity(ident);
4984 }
4985 }
4986
4987 @Override // Binder call
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004988 public boolean isDeviceIdleMode() {
4989 final long ident = Binder.clearCallingIdentity();
4990 try {
4991 return isDeviceIdleModeInternal();
4992 } finally {
4993 Binder.restoreCallingIdentity(ident);
4994 }
4995 }
4996
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004997 @Override // Binder call
4998 public boolean isLightDeviceIdleMode() {
4999 final long ident = Binder.clearCallingIdentity();
5000 try {
5001 return isLightDeviceIdleModeInternal();
5002 } finally {
5003 Binder.restoreCallingIdentity(ident);
5004 }
5005 }
5006
Jeff Brown6f357d32014-01-15 20:40:55 -08005007 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07005008 * Gets the reason for the last time the phone had to reboot.
5009 *
5010 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08005011 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07005012 */
5013 @Override // Binder call
5014 public int getLastShutdownReason() {
5015 mContext.enforceCallingOrSelfPermission(
5016 android.Manifest.permission.DEVICE_POWER, null);
5017
5018 final long ident = Binder.clearCallingIdentity();
5019 try {
Robert Horvath84a67c62019-11-29 15:31:30 +01005020 return getLastShutdownReasonInternal();
Salvador Martineza6f7b252017-04-10 10:46:15 -07005021 } finally {
5022 Binder.restoreCallingIdentity(ident);
5023 }
5024 }
5025
Calin Tatarua3805722018-08-09 16:41:28 +02005026 @Override // Binder call
5027 public int getLastSleepReason() {
5028 mContext.enforceCallingOrSelfPermission(
5029 android.Manifest.permission.DEVICE_POWER, null);
5030
5031 final long ident = Binder.clearCallingIdentity();
5032 try {
5033 return getLastSleepReasonInternal();
5034 } finally {
5035 Binder.restoreCallingIdentity(ident);
5036 }
5037 }
5038
Salvador Martineza6f7b252017-04-10 10:46:15 -07005039 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08005040 * Reboots the device.
5041 *
5042 * @param confirm If true, shows a reboot confirmation dialog.
5043 * @param reason The reason for the reboot, or null if none.
5044 * @param wait If true, this call waits for the reboot to complete and does not return.
5045 */
5046 @Override // Binder call
Nikita Ioffe779d6be2020-02-06 23:17:17 +00005047 public void reboot(boolean confirm, @Nullable String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08005048 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08005049 if (PowerManager.REBOOT_RECOVERY.equals(reason)
5050 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08005051 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
5052 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005053
5054 final long ident = Binder.clearCallingIdentity();
5055 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07005056 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
5057 } finally {
5058 Binder.restoreCallingIdentity(ident);
5059 }
5060 }
5061
5062 /**
5063 * Reboots the device into safe mode
5064 *
5065 * @param confirm If true, shows a reboot confirmation dialog.
5066 * @param wait If true, this call waits for the reboot to complete and does not return.
5067 */
5068 @Override // Binder call
5069 public void rebootSafeMode(boolean confirm, boolean wait) {
5070 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
5071
5072 final long ident = Binder.clearCallingIdentity();
5073 try {
5074 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
5075 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08005076 } finally {
5077 Binder.restoreCallingIdentity(ident);
5078 }
5079 }
5080
5081 /**
5082 * Shuts down the device.
5083 *
5084 * @param confirm If true, shows a shutdown confirmation dialog.
5085 * @param wait If true, this call waits for the shutdown to complete and does not return.
5086 */
5087 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07005088 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08005089 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
5090
5091 final long ident = Binder.clearCallingIdentity();
5092 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07005093 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08005094 } finally {
5095 Binder.restoreCallingIdentity(ident);
5096 }
5097 }
5098
5099 /**
5100 * Crash the runtime (causing a complete restart of the Android framework).
5101 * Requires REBOOT permission. Mostly for testing. Should not return.
5102 */
5103 @Override // Binder call
5104 public void crash(String message) {
5105 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
5106
5107 final long ident = Binder.clearCallingIdentity();
5108 try {
5109 crashInternal(message);
5110 } finally {
5111 Binder.restoreCallingIdentity(ident);
5112 }
5113 }
5114
5115 /**
5116 * Set the setting that determines whether the device stays on when plugged in.
5117 * The argument is a bit string, with each bit specifying a power source that,
5118 * when the device is connected to that source, causes the device to stay on.
5119 * See {@link android.os.BatteryManager} for the list of power sources that
5120 * can be specified. Current values include
5121 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
5122 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
5123 *
5124 * Used by "adb shell svc power stayon ..."
5125 *
5126 * @param val an {@code int} containing the bits that specify which power sources
5127 * should cause the device to stay on.
5128 */
5129 @Override // Binder call
5130 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01005131 int uid = Binder.getCallingUid();
5132 // if uid is of root's, we permit this operation straight away
5133 if (uid != Process.ROOT_UID) {
5134 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
5135 Settings.getPackageNameForUid(mContext, uid), true)) {
5136 return;
5137 }
5138 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005139
5140 final long ident = Binder.clearCallingIdentity();
5141 try {
5142 setStayOnSettingInternal(val);
5143 } finally {
5144 Binder.restoreCallingIdentity(ident);
5145 }
5146 }
5147
5148 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08005149 * Used by the phone application to make the attention LED flash when ringing.
5150 */
5151 @Override // Binder call
5152 public void setAttentionLight(boolean on, int color) {
5153 mContext.enforceCallingOrSelfPermission(
5154 android.Manifest.permission.DEVICE_POWER, null);
5155
5156 final long ident = Binder.clearCallingIdentity();
5157 try {
5158 setAttentionLightInternal(on, color);
5159 } finally {
5160 Binder.restoreCallingIdentity(ident);
5161 }
5162 }
5163
5164 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08005165 public void setDozeAfterScreenOff(boolean on) {
5166 mContext.enforceCallingOrSelfPermission(
5167 android.Manifest.permission.DEVICE_POWER, null);
5168
5169 final long ident = Binder.clearCallingIdentity();
5170 try {
5171 setDozeAfterScreenOffInternal(on);
5172 } finally {
5173 Binder.restoreCallingIdentity(ident);
5174 }
5175 }
5176
5177 @Override // Binder call
Yogisha Dixit9c20afa2020-01-15 15:55:51 +00005178 public boolean isAmbientDisplayAvailable() {
5179 mContext.enforceCallingOrSelfPermission(
5180 android.Manifest.permission.READ_DREAM_STATE, null);
5181
5182 final long ident = Binder.clearCallingIdentity();
5183 try {
5184 return mAmbientDisplayConfiguration.ambientDisplayAvailable();
5185 } finally {
5186 Binder.restoreCallingIdentity(ident);
5187 }
5188 }
5189
5190 @Override // Binder call
5191 public void suppressAmbientDisplay(@NonNull String token, boolean suppress) {
5192 mContext.enforceCallingOrSelfPermission(
5193 android.Manifest.permission.WRITE_DREAM_STATE, null);
5194
5195 final int uid = Binder.getCallingUid();
5196 final long ident = Binder.clearCallingIdentity();
5197 try {
5198 suppressAmbientDisplayInternal(createAmbientDisplayToken(token, uid), suppress);
5199 } finally {
5200 Binder.restoreCallingIdentity(ident);
5201 }
5202 }
5203
5204 @Override // Binder call
5205 public boolean isAmbientDisplaySuppressedForToken(@NonNull String token) {
5206 mContext.enforceCallingOrSelfPermission(
5207 android.Manifest.permission.READ_DREAM_STATE, null);
5208
5209 final int uid = Binder.getCallingUid();
5210 final long ident = Binder.clearCallingIdentity();
5211 try {
5212 return mAmbientDisplaySuppressionTokens.contains(
5213 createAmbientDisplayToken(token, uid));
5214 } finally {
5215 Binder.restoreCallingIdentity(ident);
5216 }
5217 }
5218
5219 @Override // Binder call
5220 public boolean isAmbientDisplaySuppressed() {
5221 mContext.enforceCallingOrSelfPermission(
5222 android.Manifest.permission.READ_DREAM_STATE, null);
5223
5224 final long ident = Binder.clearCallingIdentity();
5225 try {
5226 return mAmbientDisplaySuppressionTokens.size() > 0;
5227 } finally {
5228 Binder.restoreCallingIdentity(ident);
5229 }
5230 }
5231
5232 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07005233 public void boostScreenBrightness(long eventTime) {
5234 if (eventTime > SystemClock.uptimeMillis()) {
5235 throw new IllegalArgumentException("event time must not be in the future");
5236 }
5237
5238 mContext.enforceCallingOrSelfPermission(
5239 android.Manifest.permission.DEVICE_POWER, null);
5240
5241 final int uid = Binder.getCallingUid();
5242 final long ident = Binder.clearCallingIdentity();
5243 try {
5244 boostScreenBrightnessInternal(eventTime, uid);
5245 } finally {
5246 Binder.restoreCallingIdentity(ident);
5247 }
5248 }
5249
5250 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07005251 public boolean isScreenBrightnessBoosted() {
5252 final long ident = Binder.clearCallingIdentity();
5253 try {
5254 return isScreenBrightnessBoostedInternal();
5255 } finally {
5256 Binder.restoreCallingIdentity(ident);
5257 }
5258 }
5259
Santos Cordon12f92eb2019-02-01 21:28:47 +00005260 @Override // binder call
5261 public boolean forceSuspend() {
5262 mContext.enforceCallingOrSelfPermission(
5263 android.Manifest.permission.DEVICE_POWER, null);
5264
5265 final int uid = Binder.getCallingUid();
5266 final long ident = Binder.clearCallingIdentity();
5267 try {
5268 return forceSuspendInternal(uid);
5269 } finally {
5270 Binder.restoreCallingIdentity(ident);
5271 }
5272 }
5273
Bryce Lee84d6c0f2015-03-17 10:43:08 -07005274 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08005275 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06005276 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08005277
5278 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08005279
5280 boolean isDumpProto = false;
5281 for (String arg : args) {
5282 if (arg.equals("--proto")) {
5283 isDumpProto = true;
5284 }
5285 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005286 try {
Netta P958d0a52017-02-07 11:20:55 -08005287 if (isDumpProto) {
5288 dumpProto(fd);
5289 } else {
5290 dumpInternal(pw);
5291 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005292 } finally {
5293 Binder.restoreCallingIdentity(ident);
5294 }
5295 }
5296 }
5297
Salvador Martineza6f7b252017-04-10 10:46:15 -07005298 @VisibleForTesting
Santos Cordon64a6e612018-08-22 19:27:04 +01005299 BinderService getBinderServiceInstance() {
5300 return mBinderService;
5301 }
5302
5303 @VisibleForTesting
5304 LocalService getLocalServiceInstance() {
5305 return mLocalService;
5306 }
5307
5308 @VisibleForTesting
Robert Horvath84a67c62019-11-29 15:31:30 +01005309 int getLastShutdownReasonInternal() {
5310 String line = mSystemProperties.get(SYSTEM_PROPERTY_REBOOT_REASON, null);
Salvador Martineza6f7b252017-04-10 10:46:15 -07005311 switch (line) {
5312 case REASON_SHUTDOWN:
5313 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
5314 case REASON_REBOOT:
5315 return PowerManager.SHUTDOWN_REASON_REBOOT;
5316 case REASON_USERREQUESTED:
5317 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
5318 case REASON_THERMAL_SHUTDOWN:
5319 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07005320 case REASON_LOW_BATTERY:
5321 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
5322 case REASON_BATTERY_THERMAL_STATE:
5323 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07005324 default:
5325 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
5326 }
5327 }
5328
Calin Tatarua3805722018-08-09 16:41:28 +02005329 private int getLastSleepReasonInternal() {
5330 synchronized (mLock) {
5331 return mLastSleepReason;
5332 }
5333 }
5334
Santos Cordon623526b2019-04-09 17:02:38 +01005335 private PowerManager.WakeData getLastWakeupInternal() {
5336 synchronized (mLock) {
5337 return new WakeData(mLastWakeTime, mLastWakeReason);
5338 }
5339 }
5340
Santos Cordond9701ab2019-08-01 18:33:20 +01005341 @VisibleForTesting
5342 final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08005343 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07005344 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
5345 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
5346 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
5347 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08005348 }
Jeff Brown970d4132014-07-19 11:33:47 -07005349 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08005350 }
5351
Jeff Brown6f357d32014-01-15 20:40:55 -08005352 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07005353 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
5354 switch (screenState) {
5355 case Display.STATE_UNKNOWN:
5356 case Display.STATE_OFF:
5357 case Display.STATE_DOZE:
5358 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07005359 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07005360 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07005361 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07005362 break;
5363 default:
5364 screenState = Display.STATE_UNKNOWN;
5365 break;
5366 }
5367 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
5368 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
5369 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
5370 }
5371 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
5372 }
5373
Jeff Brown6f357d32014-01-15 20:40:55 -08005374 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07005375 public void setUserInactiveOverrideFromWindowManager() {
5376 setUserInactiveOverrideFromWindowManagerInternal();
5377 }
5378
5379 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08005380 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07005381 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08005382 }
5383
5384 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00005385 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
5386 setDrawWakeLockOverrideFromSidekickInternal(keepState);
5387 }
5388
5389 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01005390 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
5391 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08005392 }
5393
5394 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08005395 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Kweku Adams9f488e22019-01-14 16:25:08 -08005396 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005397 }
5398
5399 @Override
5400 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08005401 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07005402 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005403
5404 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07005405 public boolean setDeviceIdleMode(boolean enabled) {
5406 return setDeviceIdleModeInternal(enabled);
5407 }
5408
5409 @Override
5410 public boolean setLightDeviceIdleMode(boolean enabled) {
5411 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07005412 }
5413
5414 @Override
5415 public void setDeviceIdleWhitelist(int[] appids) {
5416 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07005417 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07005418
5419 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07005420 public void setDeviceIdleTempWhitelist(int[] appids) {
5421 setDeviceIdleTempWhitelistInternal(appids);
5422 }
5423
5424 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07005425 public void startUidChanges() {
5426 startUidChangesInternal();
5427 }
5428
5429 @Override
5430 public void finishUidChanges() {
5431 finishUidChangesInternal();
5432 }
5433
5434 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07005435 public void updateUidProcState(int uid, int procState) {
5436 updateUidProcStateInternal(uid, procState);
5437 }
5438
5439 @Override
5440 public void uidGone(int uid) {
5441 uidGoneInternal(uid);
5442 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01005443
5444 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07005445 public void uidActive(int uid) {
5446 uidActiveInternal(uid);
5447 }
5448
5449 @Override
5450 public void uidIdle(int uid) {
5451 uidIdleInternal(uid);
5452 }
5453
5454 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01005455 public void powerHint(int hintId, int data) {
5456 powerHintInternal(hintId, data);
5457 }
Alex Kershaw2418ea92018-10-19 17:17:49 +01005458
5459 @Override
5460 public boolean wasDeviceIdleFor(long ms) {
5461 return wasDeviceIdleForInternal(ms);
5462 }
Santos Cordon623526b2019-04-09 17:02:38 +01005463
5464 @Override
5465 public WakeData getLastWakeup() {
5466 return getLastWakeupInternal();
5467 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005469}