blob: e1b3e4d6fbcf34d0bb6dd238ba455a29e78c72de [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jeff Brown4f8ecd82012-06-18 18:29:13 -070017package com.android.server.power;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080018
Beverlyae79ab92017-12-11 09:20:02 -050019import static android.os.PowerManagerInternal.WAKEFULNESS_ASLEEP;
20import static android.os.PowerManagerInternal.WAKEFULNESS_AWAKE;
21import static android.os.PowerManagerInternal.WAKEFULNESS_DOZING;
22import static android.os.PowerManagerInternal.WAKEFULNESS_DREAMING;
23
Tony Mantlerb8009fd2016-03-14 15:55:35 -070024import android.annotation.IntDef;
Kweku Adams9f488e22019-01-14 16:25:08 -080025import android.annotation.NonNull;
Pavel Grafov28939982017-10-03 15:11:52 +010026import android.annotation.UserIdInt;
Jason Monkafae4bd2015-12-15 14:20:06 -050027import android.app.ActivityManager;
Pavel Grafov28939982017-10-03 15:11:52 +010028import android.app.SynchronousUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080030import android.content.ContentResolver;
31import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
34import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070035import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080036import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080037import android.hardware.SensorManager;
38import android.hardware.SystemSensorManager;
Issei Suzukica19e6e2019-02-26 12:39:11 +010039import android.hardware.display.AmbientDisplayConfiguration;
Jeff Brown4ccb8232014-01-16 22:16:42 -080040import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070041import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Ruchi Kandoi0d434042016-10-03 09:12:02 -070042import android.hardware.power.V1_0.PowerHint;
Jeff Brown96307042012-07-27 15:51:34 -070043import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070044import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070045import android.os.BatteryManagerInternal;
Kweku Adams9f488e22019-01-14 16:25:08 -080046import android.os.BatterySaverPolicyConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.Binder;
48import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.IBinder;
50import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070051import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080052import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -070054import android.os.PowerManager.ServiceType;
Santos Cordon623526b2019-04-09 17:02:38 +010055import android.os.PowerManager.WakeData;
Michael Wrighte3001042019-02-05 00:13:14 +000056import android.os.PowerManager.WakeReason;
Jeff Brown6f357d32014-01-15 20:40:55 -080057import android.os.PowerManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080058import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.Process;
60import android.os.RemoteException;
Jocelyn Dangf2c38c12017-03-31 14:03:37 -070061import android.os.ResultReceiver;
62import android.os.ShellCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070064import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070065import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070066import android.os.UserHandle;
Christine Franks732c0432017-06-23 18:12:46 -070067import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070068import android.os.WorkSource;
Narayan Kamath2f916ed2017-12-29 13:02:15 +000069import android.os.WorkSource.WorkChain;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.provider.Settings;
Daichi Hirono82ab9802016-03-02 13:23:29 +090071import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080072import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070073import android.service.vr.IVrManager;
74import android.service.vr.IVrStateCallbacks;
Dianne Hackborn0ef403e2017-01-24 18:22:15 -080075import android.util.KeyValueListParser;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070076import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080077import android.util.Slog;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -070078import android.util.SparseArray;
Jeff Brown96307042012-07-27 15:51:34 -070079import android.util.TimeUtils;
Netta P958d0a52017-02-07 11:20:55 -080080import android.util.proto.ProtoOutputStream;
Jeff Brown037c33e2014-04-09 00:31:55 -070081import android.view.Display;
Makoto Onukiaae89532017-11-08 14:32:03 -080082
jackqdyulei92681e82017-02-28 11:26:28 -080083import com.android.internal.annotations.VisibleForTesting;
Jason Monkafae4bd2015-12-15 14:20:06 -050084import com.android.internal.app.IAppOpsService;
85import com.android.internal.app.IBatteryStats;
86import com.android.internal.os.BackgroundThread;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060087import com.android.internal.util.DumpUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050088import com.android.server.EventLogTags;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060089import com.android.server.LockGuard;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070090import com.android.server.RescueParty;
Jason Monkafae4bd2015-12-15 14:20:06 -050091import com.android.server.ServiceThread;
92import com.android.server.SystemService;
Michael Wright64c820d2017-03-21 12:36:55 +000093import com.android.server.UiThread;
Jason Monkafae4bd2015-12-15 14:20:06 -050094import com.android.server.Watchdog;
95import com.android.server.am.BatteryStatsService;
96import com.android.server.lights.Light;
97import com.android.server.lights.LightsManager;
Adrian Roose99bc052017-11-20 17:55:31 +010098import com.android.server.policy.WindowManagerPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -080099import com.android.server.power.batterysaver.BatterySaverController;
Kweku Adams7fb72a42019-01-08 16:08:49 -0800100import com.android.server.power.batterysaver.BatterySaverPolicy;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700101import com.android.server.power.batterysaver.BatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700102import com.android.server.power.batterysaver.BatterySavingStats;
Makoto Onuki66a78122017-11-14 15:03:21 -0800103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.io.FileDescriptor;
105import java.io.PrintWriter;
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700106import java.lang.annotation.Retention;
107import java.lang.annotation.RetentionPolicy;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.ArrayList;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700109import java.util.Arrays;
Narayan Kamath607223f2018-02-19 14:09:02 +0000110import java.util.Objects;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Jeff Brown96307042012-07-27 15:51:34 -0700112/**
113 * The power manager service is responsible for coordinating power management
114 * functions on the device.
115 */
Jeff Brown2175e9c2014-09-12 16:11:07 -0700116public final class PowerManagerService extends SystemService
Jeff Brown96307042012-07-27 15:51:34 -0700117 implements Watchdog.Monitor {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118 private static final String TAG = "PowerManagerService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Santos Cordon4ddb8012017-09-20 15:25:44 -0700120 private static final boolean DEBUG = false;
Jeff Brown96307042012-07-27 15:51:34 -0700121 private static final boolean DEBUG_SPEW = DEBUG && true;
Jeff Brown88c997a2012-06-22 13:57:45 -0700122
Jeff Brown96307042012-07-27 15:51:34 -0700123 // Message: Sent when a user activity timeout occurs to update the power state.
124 private static final int MSG_USER_ACTIVITY_TIMEOUT = 1;
Jeff Brown26875502014-01-30 21:47:47 -0800125 // Message: Sent when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -0700126 private static final int MSG_SANDMAN = 2;
Jeff Browne333e672014-10-28 13:48:55 -0700127 // Message: Sent when the screen brightness boost expires.
128 private static final int MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 3;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700129 // Message: Polling to look for long held wake locks.
130 private static final int MSG_CHECK_FOR_LONG_WAKELOCKS = 4;
Jeff Brown7304c342012-05-11 18:42:42 -0700131
Jeff Brown96307042012-07-27 15:51:34 -0700132 // Dirty bit: mWakeLocks changed
133 private static final int DIRTY_WAKE_LOCKS = 1 << 0;
134 // Dirty bit: mWakefulness changed
135 private static final int DIRTY_WAKEFULNESS = 1 << 1;
136 // Dirty bit: user activity was poked or may have timed out
137 private static final int DIRTY_USER_ACTIVITY = 1 << 2;
138 // Dirty bit: actual display power state was updated asynchronously
139 private static final int DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED = 1 << 3;
140 // Dirty bit: mBootCompleted changed
141 private static final int DIRTY_BOOT_COMPLETED = 1 << 4;
142 // Dirty bit: settings changed
143 private static final int DIRTY_SETTINGS = 1 << 5;
144 // Dirty bit: mIsPowered changed
145 private static final int DIRTY_IS_POWERED = 1 << 6;
146 // Dirty bit: mStayOn changed
147 private static final int DIRTY_STAY_ON = 1 << 7;
148 // Dirty bit: battery state changed
149 private static final int DIRTY_BATTERY_STATE = 1 << 8;
Jeff Brown93cbbb22012-10-04 13:18:36 -0700150 // Dirty bit: proximity state changed
151 private static final int DIRTY_PROXIMITY_POSITIVE = 1 << 9;
Jeff Brownec6aa592012-10-17 20:30:25 -0700152 // Dirty bit: dock state changed
Jeff Brown3ee549c2014-09-22 20:14:39 -0700153 private static final int DIRTY_DOCK_STATE = 1 << 10;
Jeff Browne333e672014-10-28 13:48:55 -0700154 // Dirty bit: brightness boost changed
155 private static final int DIRTY_SCREEN_BRIGHTNESS_BOOST = 1 << 11;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800156 // Dirty bit: sQuiescent changed
157 private static final int DIRTY_QUIESCENT = 1 << 12;
Santos Cordon3107d292016-09-20 15:50:35 -0700158 // Dirty bit: VR Mode enabled changed
159 private static final int DIRTY_VR_MODE_CHANGED = 1 << 13;
Jeff Brown7304c342012-05-11 18:42:42 -0700160
Jeff Brown96307042012-07-27 15:51:34 -0700161 // Summarizes the state of all active wakelocks.
162 private static final int WAKE_LOCK_CPU = 1 << 0;
163 private static final int WAKE_LOCK_SCREEN_BRIGHT = 1 << 1;
164 private static final int WAKE_LOCK_SCREEN_DIM = 1 << 2;
165 private static final int WAKE_LOCK_BUTTON_BRIGHT = 1 << 3;
166 private static final int WAKE_LOCK_PROXIMITY_SCREEN_OFF = 1 << 4;
Jeff Brown10428742012-10-09 15:47:30 -0700167 private static final int WAKE_LOCK_STAY_AWAKE = 1 << 5; // only set if already awake
Jeff Brown26875502014-01-30 21:47:47 -0800168 private static final int WAKE_LOCK_DOZE = 1 << 6;
Jeff Brownc2932a12014-11-20 18:04:05 -0800169 private static final int WAKE_LOCK_DRAW = 1 << 7;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jeff Brown96307042012-07-27 15:51:34 -0700171 // Summarizes the user activity state.
172 private static final int USER_ACTIVITY_SCREEN_BRIGHT = 1 << 0;
173 private static final int USER_ACTIVITY_SCREEN_DIM = 1 << 1;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700174 private static final int USER_ACTIVITY_SCREEN_DREAM = 1 << 2;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175
Jeff Brown27736f52014-05-20 17:17:10 -0700176 // Default timeout in milliseconds. This is only used until the settings
177 // provider populates the actual default value (R.integer.def_screen_off_timeout).
Jeff Brown96307042012-07-27 15:51:34 -0700178 private static final int DEFAULT_SCREEN_OFF_TIMEOUT = 15 * 1000;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700179 private static final int DEFAULT_SLEEP_TIMEOUT = -1;
Jeff Brownff532542012-10-02 21:18:04 -0700180
Jeff Browne333e672014-10-28 13:48:55 -0700181 // Screen brightness boost timeout.
182 // Hardcoded for now until we decide what the right policy should be.
183 // This should perhaps be a setting.
184 private static final int SCREEN_BRIGHTNESS_BOOST_TIMEOUT = 5 * 1000;
185
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700186 // How long a partial wake lock must be held until we consider it a long wake lock.
187 static final long MIN_LONG_WAKE_CHECK_INTERVAL = 60*1000;
188
Jason Monk27bbb2d2015-03-31 16:46:39 -0400189 // Power features defined in hardware/libhardware/include/hardware/power.h.
190 private static final int POWER_FEATURE_DOUBLE_TAP_TO_WAKE = 1;
191
192 // Default setting for double tap to wake.
193 private static final int DEFAULT_DOUBLE_TAP_TO_WAKE = 0;
194
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800195 // System property indicating that the screen should remain off until an explicit user action
196 private static final String SYSTEM_PROPERTY_QUIESCENT = "ro.boot.quiescent";
197
Christine Franks732c0432017-06-23 18:12:46 -0700198 // System Property indicating that retail demo mode is currently enabled.
199 private static final String SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED = "sys.retaildemo.enabled";
200
Wei Wang72b77cc2019-02-07 14:10:23 -0800201 // Possible reasons for shutting down or reboot for use in REBOOT_PROPERTY(sys.boot.reason)
202 // which is set by bootstat
Salvador Martineza6f7b252017-04-10 10:46:15 -0700203 private static final String REASON_SHUTDOWN = "shutdown";
204 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700205 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
206 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700207 private static final String REASON_LOW_BATTERY = "shutdown,battery";
208 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700209
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700210 private static final String TRACE_SCREEN_ON = "Screen turning on";
211
212 /** If turning screen on takes more than this long, we show a warning on logcat. */
213 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
214
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700215 /** Constants for {@link #shutdownOrRebootInternal} */
216 @Retention(RetentionPolicy.SOURCE)
217 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
218 public @interface HaltMode {}
219 private static final int HALT_MODE_SHUTDOWN = 0;
220 private static final int HALT_MODE_REBOOT = 1;
221 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
222
Mark Salyzyn74ce8b32018-06-05 09:06:54 -0700223 // property for last reboot reason
224 private static final String REBOOT_PROPERTY = "sys.boot.reason";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700225
Jeff Brownb880d882014-02-10 19:47:07 -0800226 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700227 private final ServiceThread mHandlerThread;
228 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100229 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800230 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800231 private final BatterySaverController mBatterySaverController;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700232 private final BatterySaverStateMachine mBatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700233 private final BatterySavingStats mBatterySavingStats;
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800234 private final AttentionDetector mAttentionDetector;
Santos Cordon64a6e612018-08-22 19:27:04 +0100235 private final BinderService mBinderService;
236 private final LocalService mLocalService;
237 private final NativeWrapper mNativeWrapper;
238 private final Injector mInjector;
Jeff Brown2c43c332014-06-12 22:38:59 -0700239
Adam Lesinski182f73f2013-12-05 16:48:06 -0800240 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700241 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800242 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700243 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700244 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700245 private WindowManagerPolicy mPolicy;
246 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800247 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700248 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800249 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800250 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700251
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600252 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700253
254 // A bitfield that indicates what parts of the power state have
255 // changed and need to be recalculated.
256 private int mDirty;
257
258 // Indicates whether the device is awake or asleep or somewhere in between.
259 // This is distinct from the screen power state, which is managed separately.
260 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800261 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700262
Jeff Brown26875502014-01-30 21:47:47 -0800263 // True if the sandman has just been summoned for the first time since entering the
264 // dreaming or dozing state. Indicates whether a new dream should begin.
265 private boolean mSandmanSummoned;
266
Jeff Brown96307042012-07-27 15:51:34 -0700267 // True if MSG_SANDMAN has been scheduled.
268 private boolean mSandmanScheduled;
269
270 // Table of all suspend blockers.
271 // There should only be a few of these.
272 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
273
274 // Table of all wake locks acquired by applications.
275 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
276
277 // A bitfield that summarizes the state of all active wakelocks.
278 private int mWakeLockSummary;
279
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700280 // Have we scheduled a message to check for long wake locks? This is when we will check.
281 private long mNotifyLongScheduled;
282
283 // Last time we checked for long wake locks.
284 private long mNotifyLongDispatched;
285
286 // The time we decided to do next long check.
287 private long mNotifyLongNextCheck;
288
Jeff Brown96307042012-07-27 15:51:34 -0700289 // If true, instructs the display controller to wait for the proximity sensor to
290 // go negative before turning the screen on.
291 private boolean mRequestWaitForNegativeProximity;
292
293 // Timestamp of the last time the device was awoken or put to sleep.
294 private long mLastWakeTime;
295 private long mLastSleepTime;
296
Calin Tatarua3805722018-08-09 16:41:28 +0200297 // Last reason the device went to sleep.
Michael Wrighte3001042019-02-05 00:13:14 +0000298 private @WakeReason int mLastWakeReason;
Calin Tatarua3805722018-08-09 16:41:28 +0200299 private int mLastSleepReason;
300
Jeff Brown96307042012-07-27 15:51:34 -0700301 // Timestamp of the last call to user activity.
302 private long mLastUserActivityTime;
303 private long mLastUserActivityTimeNoChangeLights;
304
Jeff Brown0a571122014-08-21 21:50:43 -0700305 // Timestamp of last interactive power hint.
306 private long mLastInteractivePowerHintTime;
307
Jeff Browne333e672014-10-28 13:48:55 -0700308 // Timestamp of the last screen brightness boost.
309 private long mLastScreenBrightnessBoostTime;
310 private boolean mScreenBrightnessBoostInProgress;
311
Jeff Brown96307042012-07-27 15:51:34 -0700312 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700313 private int mUserActivitySummary;
314
315 // The desired display power state. The actual state may lag behind the
316 // requested because it is updated asynchronously by the display power controller.
317 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
318
Jeff Brown96307042012-07-27 15:51:34 -0700319 // True if the display power state has been fully applied, which means the display
320 // is actually on or actually off or whatever was requested.
321 private boolean mDisplayReady;
322
Jeff Brown27f7a862012-12-12 15:43:31 -0800323 // The suspend blocker used to keep the CPU alive when an application has acquired
324 // a wake lock.
325 private final SuspendBlocker mWakeLockSuspendBlocker;
326
327 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700328 private boolean mHoldingWakeLockSuspendBlocker;
329
Jeff Brown27f7a862012-12-12 15:43:31 -0800330 // The suspend blocker used to keep the CPU alive when the display is on, the
331 // display is getting ready or there is user activity (in which case the display
332 // must be on).
333 private final SuspendBlocker mDisplaySuspendBlocker;
334
335 // True if the display suspend blocker has been acquired.
336 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700337
338 // True if systemReady() has been called.
339 private boolean mSystemReady;
340
341 // True if boot completed occurred. We keep the screen on until this happens.
342 private boolean mBootCompleted;
343
Jeff Brown26875502014-01-30 21:47:47 -0800344 // True if auto-suspend mode is enabled.
345 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700346 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800347
348 // True if interactive mode is enabled.
349 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700350 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800351
Jeff Brown96307042012-07-27 15:51:34 -0700352 // True if the device is plugged into a power source.
353 private boolean mIsPowered;
354
Jeff Brownf3fb8952012-10-02 20:57:05 -0700355 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
356 private int mPlugType;
357
Jeff Brown016ff142012-10-15 16:47:22 -0700358 // The current battery level percentage.
359 private int mBatteryLevel;
360
361 // The battery level percentage at the time the dream started.
362 // This is used to terminate a dream and go to sleep if the battery is
363 // draining faster than it is charging and the user activity timeout has expired.
364 private int mBatteryLevelWhenDreamStarted;
365
Jeff Brownec6aa592012-10-17 20:30:25 -0700366 // The current dock state.
367 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
368
Jeff Brown26875502014-01-30 21:47:47 -0800369 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700370 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800371
372 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700373 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800374
Jeff Brown96307042012-07-27 15:51:34 -0700375 // True if the device should wake up when plugged or unplugged.
376 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
377
Bryce Lee584a4452014-10-21 15:55:55 -0700378 // True if the device should wake up when plugged or unplugged in theater mode.
379 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
380
Jeff Brownec083212013-09-11 20:45:25 -0700381 // True if the device should suspend when the screen is off due to proximity.
382 private boolean mSuspendWhenScreenOffDueToProximityConfig;
383
Jeff Brown96307042012-07-27 15:51:34 -0700384 // True if dreams are supported on this device.
385 private boolean mDreamsSupportedConfig;
386
John Spurlocked108f32012-10-18 16:49:24 -0400387 // Default value for dreams enabled
388 private boolean mDreamsEnabledByDefaultConfig;
389
390 // Default value for dreams activate-on-sleep
391 private boolean mDreamsActivatedOnSleepByDefaultConfig;
392
393 // Default value for dreams activate-on-dock
394 private boolean mDreamsActivatedOnDockByDefaultConfig;
395
Jeff Brown26875502014-01-30 21:47:47 -0800396 // True if dreams can run while not plugged in.
397 private boolean mDreamsEnabledOnBatteryConfig;
398
399 // Minimum battery level to allow dreaming when powered.
400 // Use -1 to disable this safety feature.
401 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
402
403 // Minimum battery level to allow dreaming when not powered.
404 // Use -1 to disable this safety feature.
405 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
406
407 // If the battery level drops by this percentage and the user activity timeout
408 // has expired, then assume the device is receiving insufficient current to charge
409 // effectively and terminate the dream. Use -1 to disable this safety feature.
410 private int mDreamsBatteryLevelDrainCutoffConfig;
411
Jeff Brown96307042012-07-27 15:51:34 -0700412 // True if dreams are enabled by the user.
413 private boolean mDreamsEnabledSetting;
414
John Spurlock1a868b72012-08-22 09:56:51 -0400415 // True if dreams should be activated on sleep.
416 private boolean mDreamsActivateOnSleepSetting;
417
Jeff Brownec6aa592012-10-17 20:30:25 -0700418 // True if dreams should be activated on dock.
419 private boolean mDreamsActivateOnDockSetting;
420
Jeff Brown2175e9c2014-09-12 16:11:07 -0700421 // True if doze should not be started until after the screen off transition.
Lucas Dupin16cfe452018-02-08 13:14:50 -0800422 private boolean mDozeAfterScreenOff;
Jeff Brown2175e9c2014-09-12 16:11:07 -0700423
Jeff Brown27736f52014-05-20 17:17:10 -0700424 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100425 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700426
427 // The screen dim duration, in milliseconds.
428 // This is subtracted from the end of the screen off timeout so the
429 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100430 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700431
432 // The maximum screen dim time expressed as a ratio relative to the screen
433 // off timeout. If the screen off timeout is very short then we want the
434 // dim timeout to also be quite short so that most of the time is spent on.
435 // Otherwise the user won't get much screen on time before dimming occurs.
436 private float mMaximumScreenDimRatioConfig;
437
Jason Monk27bbb2d2015-03-31 16:46:39 -0400438 // Whether device supports double tap to wake.
439 private boolean mSupportsDoubleTapWakeConfig;
440
Jeff Brown96307042012-07-27 15:51:34 -0700441 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100442 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700443
Jeff Brown05af6ad2014-09-30 20:54:30 -0700444 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100445 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700446
Jeff Brown96307042012-07-27 15:51:34 -0700447 // The maximum allowable screen off timeout according to the device
448 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100449 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700450
451 // The stay on while plugged in setting.
452 // A bitfield of battery conditions under which to make the screen stay on.
453 private int mStayOnWhilePluggedInSetting;
454
455 // True if the device should stay on.
456 private boolean mStayOn;
457
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800458 // True if the lights should stay off until an explicit user action.
459 private static boolean sQuiescent;
460
Jeff Brown93cbbb22012-10-04 13:18:36 -0700461 // True if the proximity sensor reads a positive result.
462 private boolean mProximityPositive;
463
Jeff Brown96307042012-07-27 15:51:34 -0700464 // Screen brightness setting limits.
465 private int mScreenBrightnessSettingMinimum;
466 private int mScreenBrightnessSettingMaximum;
467 private int mScreenBrightnessSettingDefault;
468
469 // The screen brightness setting, from 0 to 255.
470 // Use -1 if no value has been set.
471 private int mScreenBrightnessSetting;
472
473 // The screen brightness mode.
474 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
475 private int mScreenBrightnessModeSetting;
476
477 // The screen brightness setting override from the window manager
478 // to allow the current foreground activity to override the brightness.
479 // Use -1 to disable.
480 private int mScreenBrightnessOverrideFromWindowManager = -1;
481
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700482 // The window manager has determined the user to be inactive via other means.
483 // Set this to false to disable.
484 private boolean mUserInactiveOverrideFromWindowManager;
485
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700486 // The next possible user activity timeout after being explicitly told the user is inactive.
487 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
488 private long mOverriddenTimeout = -1;
489
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700490 // The user activity timeout override from the window manager
491 // to allow the current foreground activity to override the user activity timeout.
492 // Use -1 to disable.
493 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
494
Jeff Brown970d4132014-07-19 11:33:47 -0700495 // The screen state to use while dozing.
496 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
497
498 // The screen brightness to use while dozing.
499 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
500
Ivan Podogov56bc6d02018-02-26 16:04:24 +0000501 // Keep display state when dozing.
502 private boolean mDrawWakeLockOverrideFromSidekick;
503
Jeff Brown9ba8d782012-10-01 16:38:23 -0700504 // Time when we last logged a warning about calling userActivity() without permission.
505 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
506
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700507 // True if the battery level is currently considered low.
508 private boolean mBatteryLevelLow;
509
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700510 // True if we are currently in device idle mode.
511 private boolean mDeviceIdleMode;
512
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700513 // True if we are currently in light device idle mode.
514 private boolean mLightDeviceIdleMode;
515
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700516 // Set of app ids that we will always respect the wake locks for.
517 int[] mDeviceIdleWhitelist = new int[0];
518
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700519 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
520 int[] mDeviceIdleTempWhitelist = new int[0];
521
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700522 private final SparseArray<UidState> mUidState = new SparseArray<>();
523
524 // We are currently in the middle of a batch change of uids.
525 private boolean mUidsChanging;
526
527 // Some uids have actually changed while mUidsChanging was true.
528 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700529
Bryce Lee584a4452014-10-21 15:55:55 -0700530 // True if theater mode is enabled
531 private boolean mTheaterModeEnabled;
532
Adrian Roos56021892017-02-27 20:25:09 +0100533 // True if always on display is enabled
534 private boolean mAlwaysOnEnabled;
535
Jason Monk27bbb2d2015-03-31 16:46:39 -0400536 // True if double tap to wake is enabled
537 private boolean mDoubleTapWakeEnabled;
538
Santos Cordon3107d292016-09-20 15:50:35 -0700539 // True if we are currently in VR Mode.
540 private boolean mIsVrModeEnabled;
541
Santos Cordon12f92eb2019-02-01 21:28:47 +0000542 // True if we in the process of performing a forceSuspend
543 private boolean mForceSuspendActive;
544
Santos Cordon03044382019-09-19 16:59:01 +0100545 // Transition to Doze is in progress. We have transitioned to WAKEFULNESS_DOZING,
546 // but the DreamService has not yet been told to start (it's an async process).
547 private boolean mDozeStartInProgress;
548
Pavel Grafov28939982017-10-03 15:11:52 +0100549 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
550 @Override
551 public void onUserSwitching(int newUserId) throws RemoteException {}
552
553 @Override
554 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
555 final long now = SystemClock.uptimeMillis();
556 synchronized(mLock) {
557 mForegroundProfile = newProfileId;
558 maybeUpdateForegroundProfileLastActivityLocked(now);
559 }
560 }
561 }
562
563 // User id corresponding to activity the user is currently interacting with.
564 private @UserIdInt int mForegroundProfile;
565
566 // Per-profile state to track when a profile should be locked.
567 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
568
569 private static final class ProfilePowerState {
570 // Profile user id.
571 final @UserIdInt int mUserId;
572 // Maximum time to lock set by admin.
573 long mScreenOffTimeout;
574 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
575 int mWakeLockSummary;
576 // Last user activity that happened in an app running in the profile.
577 long mLastUserActivityTime;
578 // Whether profile has been locked last time it timed out.
579 boolean mLockingNotified;
580
581 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
582 mUserId = userId;
583 mScreenOffTimeout = screenOffTimeout;
584 // Not accurate but at least won't cause immediate locking of the profile.
585 mLastUserActivityTime = SystemClock.uptimeMillis();
586 }
587 }
588
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800589 /**
590 * All times are in milliseconds. These constants are kept synchronized with the system
591 * global Settings. Any access to this class or its fields should be done while
592 * holding the PowerManagerService.mLock lock.
593 */
594 private final class Constants extends ContentObserver {
595 // Key names stored in the settings value.
596 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
597
598 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
599
600 // Prevent processes that are cached from holding wake locks?
601 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
602
603 private ContentResolver mResolver;
604 private final KeyValueListParser mParser = new KeyValueListParser(',');
605
606 public Constants(Handler handler) {
607 super(handler);
608 }
609
610 public void start(ContentResolver resolver) {
611 mResolver = resolver;
612 mResolver.registerContentObserver(Settings.Global.getUriFor(
613 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
614 updateConstants();
615 }
616
617 @Override
618 public void onChange(boolean selfChange, Uri uri) {
619 updateConstants();
620 }
621
622 private void updateConstants() {
623 synchronized (mLock) {
624 try {
625 mParser.setString(Settings.Global.getString(mResolver,
626 Settings.Global.POWER_MANAGER_CONSTANTS));
627 } catch (IllegalArgumentException e) {
628 // Failed to parse the settings string, log this and move on
629 // with defaults.
630 Slog.e(TAG, "Bad alarm manager settings", e);
631 }
632
633 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
634 DEFAULT_NO_CACHED_WAKE_LOCKS);
635 }
636 }
637
638 void dump(PrintWriter pw) {
639 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
640
641 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
642 pw.println(NO_CACHED_WAKE_LOCKS);
643 }
Netta P958d0a52017-02-07 11:20:55 -0800644
645 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700646 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
647 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800648 NO_CACHED_WAKE_LOCKS);
649 proto.end(constantsToken);
650 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800651 }
652
Santos Cordon64a6e612018-08-22 19:27:04 +0100653 /**
654 * Wrapper around the static-native methods of PowerManagerService.
655 *
656 * This class exists to allow us to mock static native methods in our tests. If mocking static
657 * methods becomes easier than this in the future, we can delete this class.
658 */
659 @VisibleForTesting
660 public static class NativeWrapper {
661 /** Wrapper for PowerManager.nativeInit */
662 public void nativeInit(PowerManagerService service) {
663 service.nativeInit();
664 }
665
666 /** Wrapper for PowerManager.nativeAcquireSuspectBlocker */
667 public void nativeAcquireSuspendBlocker(String name) {
668 PowerManagerService.nativeAcquireSuspendBlocker(name);
669 }
670
671 /** Wrapper for PowerManager.nativeReleaseSuspendBlocker */
672 public void nativeReleaseSuspendBlocker(String name) {
673 PowerManagerService.nativeReleaseSuspendBlocker(name);
674 }
675
676 /** Wrapper for PowerManager.nativeSetInteractive */
677 public void nativeSetInteractive(boolean enable) {
678 PowerManagerService.nativeSetInteractive(enable);
679 }
680
681 /** Wrapper for PowerManager.nativeSetAutoSuspend */
682 public void nativeSetAutoSuspend(boolean enable) {
683 PowerManagerService.nativeSetAutoSuspend(enable);
684 }
685
686 /** Wrapper for PowerManager.nativeSendPowerHint */
687 public void nativeSendPowerHint(int hintId, int data) {
688 PowerManagerService.nativeSendPowerHint(hintId, data);
689 }
690
691 /** Wrapper for PowerManager.nativeSetFeature */
692 public void nativeSetFeature(int featureId, int data) {
693 PowerManagerService.nativeSetFeature(featureId, data);
694 }
Santos Cordon12f92eb2019-02-01 21:28:47 +0000695
696 /** Wrapper for PowerManager.nativeForceSuspend */
697 public boolean nativeForceSuspend() {
698 return PowerManagerService.nativeForceSuspend();
699 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100700 }
701
702 @VisibleForTesting
703 static class Injector {
704 Notifier createNotifier(Looper looper, Context context, IBatteryStats batteryStats,
705 SuspendBlocker suspendBlocker, WindowManagerPolicy policy) {
706 return new Notifier(looper, context, batteryStats, suspendBlocker, policy);
707 }
708
709 SuspendBlocker createSuspendBlocker(PowerManagerService service, String name) {
710 SuspendBlocker suspendBlocker = service.new SuspendBlockerImpl(name);
711 service.mSuspendBlockers.add(suspendBlocker);
712 return suspendBlocker;
713 }
714
715 BatterySaverPolicy createBatterySaverPolicy(
716 Object lock, Context context, BatterySavingStats batterySavingStats) {
717 return new BatterySaverPolicy(lock, context, batterySavingStats);
718 }
719
720 NativeWrapper createNativeWrapper() {
721 return new NativeWrapper();
722 }
Santos Cordon9b510a22018-08-24 16:42:54 +0100723
724 WirelessChargerDetector createWirelessChargerDetector(
725 SensorManager sensorManager, SuspendBlocker suspendBlocker, Handler handler) {
726 return new WirelessChargerDetector(sensorManager, suspendBlocker, handler);
727 }
728
729 AmbientDisplayConfiguration createAmbientDisplayConfiguration(Context context) {
730 return new AmbientDisplayConfiguration(context);
731 }
Santos Cordon64a6e612018-08-22 19:27:04 +0100732 }
733
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800734 final Constants mConstants;
735
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700736 private native void nativeInit();
Jeff Brown96307042012-07-27 15:51:34 -0700737 private static native void nativeAcquireSuspendBlocker(String name);
738 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700739 private static native void nativeSetInteractive(boolean enable);
740 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700741 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400742 private static native void nativeSetFeature(int featureId, int data);
Santos Cordon12f92eb2019-02-01 21:28:47 +0000743 private static native boolean nativeForceSuspend();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800744
Jeff Brownb880d882014-02-10 19:47:07 -0800745 public PowerManagerService(Context context) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100746 this(context, new Injector());
747 }
748
749 @VisibleForTesting
750 PowerManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800751 super(context);
Santos Cordon64a6e612018-08-22 19:27:04 +0100752
Jeff Brownb880d882014-02-10 19:47:07 -0800753 mContext = context;
Santos Cordon64a6e612018-08-22 19:27:04 +0100754 mBinderService = new BinderService();
755 mLocalService = new LocalService();
756 mNativeWrapper = injector.createNativeWrapper();
757 mInjector = injector;
758
Jeff Brown2c43c332014-06-12 22:38:59 -0700759 mHandlerThread = new ServiceThread(TAG,
760 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
761 mHandlerThread.start();
762 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800763 mConstants = new Constants(mHandler);
Santos Cordon9b510a22018-08-24 16:42:54 +0100764 mAmbientDisplayConfiguration = mInjector.createAmbientDisplayConfiguration(context);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800765 mAttentionDetector = new AttentionDetector(this::onUserAttention, mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800766
Makoto Onukibd7a6252018-05-10 13:41:39 -0700767 mBatterySavingStats = new BatterySavingStats(mLock);
Santos Cordon64a6e612018-08-22 19:27:04 +0100768 mBatterySaverPolicy =
769 mInjector.createBatterySaverPolicy(mLock, mContext, mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700770 mBatterySaverController = new BatterySaverController(mLock, mContext,
Santos Cordon64a6e612018-08-22 19:27:04 +0100771 BackgroundThread.get().getLooper(), mBatterySaverPolicy,
772 mBatterySavingStats);
Makoto Onukibd7a6252018-05-10 13:41:39 -0700773 mBatterySaverStateMachine = new BatterySaverStateMachine(
774 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700775
Jeff Brown96307042012-07-27 15:51:34 -0700776 synchronized (mLock) {
Santos Cordon64a6e612018-08-22 19:27:04 +0100777 mWakeLockSuspendBlocker =
778 mInjector.createSuspendBlocker(this, "PowerManagerService.WakeLocks");
779 mDisplaySuspendBlocker =
780 mInjector.createSuspendBlocker(this, "PowerManagerService.Display");
781 if (mDisplaySuspendBlocker != null) {
782 mDisplaySuspendBlocker.acquire();
783 mHoldingDisplaySuspendBlocker = true;
784 }
Jeff Brown037c33e2014-04-09 00:31:55 -0700785 mHalAutoSuspendModeEnabled = false;
786 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800787
Jeff Brown96307042012-07-27 15:51:34 -0700788 mWakefulness = WAKEFULNESS_AWAKE;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800789 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
790
Santos Cordon64a6e612018-08-22 19:27:04 +0100791 mNativeWrapper.nativeInit(this);
792 mNativeWrapper.nativeSetAutoSuspend(false);
793 mNativeWrapper.nativeSetInteractive(true);
794 mNativeWrapper.nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800796 }
797
Jeff Brown6f357d32014-01-15 20:40:55 -0800798 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800799 public void onStart() {
Santos Cordon64a6e612018-08-22 19:27:04 +0100800 publishBinderService(Context.POWER_SERVICE, mBinderService);
801 publishLocalService(PowerManagerInternal.class, mLocalService);
Jeff Brown9e316a12012-10-08 19:17:06 -0700802
803 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800804 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700805 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800806
Jeff Brown6d2a9492014-08-07 19:06:49 -0700807 @Override
808 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700809 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600810 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
811 incrementBootCount();
812
813 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700814 final long now = SystemClock.uptimeMillis();
815 mBootCompleted = true;
816 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700817
818 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700819 userActivityNoUpdateLocked(
820 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
821 updatePowerStateLocked();
822 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700823 }
824 }
825
Jeff Brown21392762014-06-13 19:00:36 -0700826 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700827 synchronized (mLock) {
828 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700829 mAppOps = appOps;
830 mDreamManager = getLocalService(DreamManagerInternal.class);
831 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
832 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700833 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
Lucas Dupin0a5d7972019-01-16 18:52:30 -0800834 mAttentionDetector.systemReady(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800835
Adam Lesinski182f73f2013-12-05 16:48:06 -0800836 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700837 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
838 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
839 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800840
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700841 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800842
Jeff Brownc38c9be2012-10-04 13:16:19 -0700843 // The notifier runs on the system server's main looper so as not to interfere
844 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700845 mBatteryStats = BatteryStatsService.getService();
Santos Cordon64a6e612018-08-22 19:27:04 +0100846 mNotifier = mInjector.createNotifier(Looper.getMainLooper(), mContext, mBatteryStats,
847 mInjector.createSuspendBlocker(this, "PowerManagerService.Broadcasts"),
848 mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700849
Santos Cordon9b510a22018-08-24 16:42:54 +0100850 mWirelessChargerDetector = mInjector.createWirelessChargerDetector(sensorManager,
Santos Cordon64a6e612018-08-22 19:27:04 +0100851 mInjector.createSuspendBlocker(
852 this, "PowerManagerService.WirelessChargerDetector"),
Jeff Browndbcc8a22013-10-01 16:16:44 -0700853 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700854 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700855
856 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800857 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400858
Jeff Brown131206b2014-04-08 17:27:14 -0700859 // Initialize display power management.
860 mDisplayManagerInternal.initPowerManagement(
861 mDisplayPowerCallbacks, mHandler, sensorManager);
862
Pavel Grafov28939982017-10-03 15:11:52 +0100863 try {
864 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
865 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
866 } catch (RemoteException e) {
867 // Shouldn't happen since in-process.
868 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800869
Jeff Brown96307042012-07-27 15:51:34 -0700870 // Go.
871 readConfigurationLocked();
872 updateSettingsLocked();
873 mDirty |= DIRTY_BATTERY_STATE;
874 updatePowerStateLocked();
875 }
Shibin George43f5de02016-07-06 02:12:10 +0530876
Jeff Sharkey6e544612017-02-20 11:02:26 -0700877 final ContentResolver resolver = mContext.getContentResolver();
878 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800879
880 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -0700881 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -0700882
883 // Register for settings changes.
884 resolver.registerContentObserver(Settings.Secure.getUriFor(
885 Settings.Secure.SCREENSAVER_ENABLED),
886 false, mSettingsObserver, UserHandle.USER_ALL);
887 resolver.registerContentObserver(Settings.Secure.getUriFor(
888 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
889 false, mSettingsObserver, UserHandle.USER_ALL);
890 resolver.registerContentObserver(Settings.Secure.getUriFor(
891 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
892 false, mSettingsObserver, UserHandle.USER_ALL);
893 resolver.registerContentObserver(Settings.System.getUriFor(
894 Settings.System.SCREEN_OFF_TIMEOUT),
895 false, mSettingsObserver, UserHandle.USER_ALL);
896 resolver.registerContentObserver(Settings.Secure.getUriFor(
897 Settings.Secure.SLEEP_TIMEOUT),
898 false, mSettingsObserver, UserHandle.USER_ALL);
899 resolver.registerContentObserver(Settings.Global.getUriFor(
900 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
901 false, mSettingsObserver, UserHandle.USER_ALL);
902 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700903 Settings.System.SCREEN_BRIGHTNESS_MODE),
904 false, mSettingsObserver, UserHandle.USER_ALL);
905 resolver.registerContentObserver(Settings.System.getUriFor(
906 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
907 false, mSettingsObserver, UserHandle.USER_ALL);
908 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700909 Settings.Global.THEATER_MODE_ON),
910 false, mSettingsObserver, UserHandle.USER_ALL);
911 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100912 Settings.Secure.DOZE_ALWAYS_ON),
913 false, mSettingsObserver, UserHandle.USER_ALL);
914 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700915 Settings.Secure.DOUBLE_TAP_TO_WAKE),
916 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700917 resolver.registerContentObserver(Settings.Global.getUriFor(
918 Settings.Global.DEVICE_DEMO_MODE),
919 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Santos Cordon64a6e612018-08-22 19:27:04 +0100920 IVrManager vrManager = IVrManager.Stub.asInterface(getBinderService(Context.VR_SERVICE));
Jeff Sharkey6e544612017-02-20 11:02:26 -0700921 if (vrManager != null) {
922 try {
923 vrManager.registerListener(mVrStateCallbacks);
924 } catch (RemoteException e) {
925 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
926 }
927 }
928
Shibin George43f5de02016-07-06 02:12:10 +0530929 // Register for broadcasts from other components of the system.
930 IntentFilter filter = new IntentFilter();
931 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
932 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
933 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
934
935 filter = new IntentFilter();
936 filter.addAction(Intent.ACTION_DREAMING_STARTED);
937 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
938 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
939
940 filter = new IntentFilter();
941 filter.addAction(Intent.ACTION_USER_SWITCHED);
942 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
943
944 filter = new IntentFilter();
945 filter.addAction(Intent.ACTION_DOCK_EVENT);
946 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700947 }
948
Santos Cordon9b510a22018-08-24 16:42:54 +0100949 @VisibleForTesting
950 void readConfigurationLocked() {
Jeff Brown96307042012-07-27 15:51:34 -0700951 final Resources resources = mContext.getResources();
952
Jeff Brown037c33e2014-04-09 00:31:55 -0700953 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800954 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700955 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800956 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700957 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700958 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700959 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
960 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700961 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
962 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700963 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400964 com.android.internal.R.bool.config_dreamsSupported);
965 mDreamsEnabledByDefaultConfig = resources.getBoolean(
966 com.android.internal.R.bool.config_dreamsEnabledByDefault);
967 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
968 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
969 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
970 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800971 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
972 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
973 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
974 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
975 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
976 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
977 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
978 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -0800979 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -0700980 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -0700981 mMinimumScreenOffTimeoutConfig = resources.getInteger(
982 com.android.internal.R.integer.config_minimumScreenOffTimeout);
983 mMaximumScreenDimDurationConfig = resources.getInteger(
984 com.android.internal.R.integer.config_maximumScreenDimDuration);
985 mMaximumScreenDimRatioConfig = resources.getFraction(
986 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400987 mSupportsDoubleTapWakeConfig = resources.getBoolean(
988 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
990
Jeff Brown96307042012-07-27 15:51:34 -0700991 private void updateSettingsLocked() {
992 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700993
Jeff Brownd4935962012-09-25 13:27:20 -0700994 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400995 Settings.Secure.SCREENSAVER_ENABLED,
996 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700997 UserHandle.USER_CURRENT) != 0);
998 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400999 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
1000 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -07001001 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -07001002 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -04001003 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
1004 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -07001005 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -07001006 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
1007 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
1008 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -07001009 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
1010 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
1011 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -07001012 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -07001013 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -07001014 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
1015 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +01001016 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -07001017
Jason Monk27bbb2d2015-03-31 16:46:39 -04001018 if (mSupportsDoubleTapWakeConfig) {
1019 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
1020 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
1021 UserHandle.USER_CURRENT) != 0;
1022 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
1023 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
Santos Cordon64a6e612018-08-22 19:27:04 +01001024 mNativeWrapper.nativeSetFeature(
1025 POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
Jason Monk27bbb2d2015-03-31 16:46:39 -04001026 }
1027 }
1028
Christine Franks732c0432017-06-23 18:12:46 -07001029 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
1030 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
1031 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
1032 }
1033
Jeff Brownd4935962012-09-25 13:27:20 -07001034 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -07001035 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -07001036 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -07001037
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001038 mDirty |= DIRTY_SETTINGS;
1039 }
1040
Jeff Brown96307042012-07-27 15:51:34 -07001041 private void handleSettingsChangedLocked() {
1042 updateSettingsLocked();
1043 updatePowerStateLocked();
1044 }
1045
Dianne Hackborn713df152013-05-17 11:27:57 -07001046 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001047 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -07001048 synchronized (mLock) {
1049 if (DEBUG_SPEW) {
1050 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
1051 + ", flags=0x" + Integer.toHexString(flags)
1052 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054
Jeff Brown96307042012-07-27 15:51:34 -07001055 WakeLock wakeLock;
1056 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001057 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -07001058 if (index >= 0) {
1059 wakeLock = mWakeLocks.get(index);
1060 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
1061 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001062 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
1063 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001064 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001066 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001068 UidState state = mUidState.get(uid);
1069 if (state == null) {
1070 state = new UidState(uid);
1071 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
1072 mUidState.put(uid, state);
1073 }
1074 state.mNumWakeLocks++;
1075 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
1076 state);
Jeff Brown96307042012-07-27 15:51:34 -07001077 try {
1078 lock.linkToDeath(wakeLock, 0);
1079 } catch (RemoteException ex) {
1080 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
Jeff Brown96307042012-07-27 15:51:34 -07001082 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001083 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001084 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001085 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001086
Jeff Brownc12035c2014-08-13 18:52:25 -07001087 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001088 mDirty |= DIRTY_WAKE_LOCKS;
1089 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001090 if (notifyAcquire) {
1091 // This needs to be done last so we are sure we have acquired the
1092 // kernel wake lock. Otherwise we have a race where the system may
1093 // go to sleep between the time we start the accounting in battery
1094 // stats and when we actually get around to telling the kernel to
1095 // stay awake.
1096 notifyWakeLockAcquiredLocked(wakeLock);
1097 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001098 }
1099 }
1100
Jeff Brownec083212013-09-11 20:45:25 -07001101 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001102 private static boolean isScreenLock(final WakeLock wakeLock) {
1103 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1104 case PowerManager.FULL_WAKE_LOCK:
1105 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1106 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1107 return true;
1108 }
1109 return false;
1110 }
1111
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001112 private static WorkChain getFirstNonEmptyWorkChain(WorkSource workSource) {
1113 if (workSource.getWorkChains() == null) {
1114 return null;
1115 }
1116
1117 for (WorkChain workChain: workSource.getWorkChains()) {
1118 if (workChain.getSize() > 0) {
1119 return workChain;
1120 }
1121 }
1122
1123 return null;
1124 }
1125
Jeff Brownc12035c2014-08-13 18:52:25 -07001126 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001127 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1128 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001129 String opPackageName;
1130 int opUid;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001131 if (wakeLock.mWorkSource != null && !wakeLock.mWorkSource.isEmpty()) {
1132 WorkSource workSource = wakeLock.mWorkSource;
1133 WorkChain workChain = getFirstNonEmptyWorkChain(workSource);
1134 if (workChain != null) {
1135 opPackageName = workChain.getAttributionTag();
1136 opUid = workChain.getAttributionUid();
1137 } else {
1138 opPackageName = workSource.getName(0) != null
1139 ? workSource.getName(0) : wakeLock.mPackageName;
1140 opUid = workSource.get(0);
1141 }
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001142 } else {
1143 opPackageName = wakeLock.mPackageName;
Artem Iglikovc474bfd02018-09-25 11:56:09 -07001144 opUid = wakeLock.mOwnerUid;
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001145 }
Michael Wrighte3001042019-02-05 00:13:14 +00001146 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
1147 PowerManager.WAKE_REASON_APPLICATION, wakeLock.mTag,
1148 opUid, opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150 }
1151
Jeff Brown96307042012-07-27 15:51:34 -07001152 private void releaseWakeLockInternal(IBinder lock, int flags) {
1153 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001154 int index = findWakeLockIndexLocked(lock);
1155 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001156 if (DEBUG_SPEW) {
1157 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1158 + " [not found], flags=0x" + Integer.toHexString(flags));
1159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 return;
1161 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001162
Jeff Brown96307042012-07-27 15:51:34 -07001163 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001164 if (DEBUG_SPEW) {
1165 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1166 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1167 }
1168
Michael Wright1208e272014-09-08 19:57:50 -07001169 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001170 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001171 }
1172
Jeff Brown3edf5272014-08-14 19:25:14 -07001173 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1174 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
1176 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001177
Jeff Brown96307042012-07-27 15:51:34 -07001178 private void handleWakeLockDeath(WakeLock wakeLock) {
1179 synchronized (mLock) {
1180 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001181 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1182 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001183 }
1184
1185 int index = mWakeLocks.indexOf(wakeLock);
1186 if (index < 0) {
1187 return;
1188 }
1189
Jeff Brown3edf5272014-08-14 19:25:14 -07001190 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001191 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001192 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001193
Jeff Brown3edf5272014-08-14 19:25:14 -07001194 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1195 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001196 UidState state = wakeLock.mUidState;
1197 state.mNumWakeLocks--;
1198 if (state.mNumWakeLocks <= 0 &&
1199 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1200 mUidState.remove(state.mUid);
1201 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001202 notifyWakeLockReleasedLocked(wakeLock);
1203
1204 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1205 mDirty |= DIRTY_WAKE_LOCKS;
1206 updatePowerStateLocked();
1207 }
1208
Jeff Brown96307042012-07-27 15:51:34 -07001209 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001210 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1211 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001212 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1213 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1214 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1215 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 }
1218
Dianne Hackbornd953c532014-08-16 18:17:38 -07001219 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1220 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001221 synchronized (mLock) {
1222 int index = findWakeLockIndexLocked(lock);
1223 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001224 if (DEBUG_SPEW) {
1225 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1226 + " [not found], ws=" + ws);
1227 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001228 throw new IllegalArgumentException("Wake lock not active: " + lock
1229 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001230 }
1231
1232 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001233 if (DEBUG_SPEW) {
1234 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1235 + " [" + wakeLock.mTag + "], ws=" + ws);
1236 }
1237
Jeff Brown96307042012-07-27 15:51:34 -07001238 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001239 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1240 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001241 ws, historyTag);
1242 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001243 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001244 }
1245 }
1246 }
1247
1248 private int findWakeLockIndexLocked(IBinder lock) {
1249 final int count = mWakeLocks.size();
1250 for (int i = 0; i < count; i++) {
1251 if (mWakeLocks.get(i).mLock == lock) {
1252 return i;
1253 }
1254 }
1255 return -1;
1256 }
1257
1258 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001259 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001260 wakeLock.mNotifiedAcquired = true;
1261 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001262 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1263 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001264 restartNofifyLongTimerLocked(wakeLock);
1265 }
1266 }
1267
1268 private void enqueueNotifyLongMsgLocked(long time) {
1269 mNotifyLongScheduled = time;
1270 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1271 msg.setAsynchronous(true);
1272 mHandler.sendMessageAtTime(msg, time);
1273 }
1274
1275 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1276 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1277 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1278 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1279 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1280 }
1281 }
1282
1283 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1284 if (mSystemReady && !wakeLock.mDisabled) {
1285 wakeLock.mNotifiedLong = true;
1286 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1287 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1288 }
1289 }
1290
1291 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1292 if (wakeLock.mNotifiedLong) {
1293 wakeLock.mNotifiedLong = false;
1294 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1295 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001296 }
1297 }
1298
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001299 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1300 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1301 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1302 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1303 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1304 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001305 notifyWakeLockLongFinishedLocked(wakeLock);
1306 // Changing the wake lock will count as releasing the old wake lock(s) and
1307 // acquiring the new ones... we do this because otherwise once a wakelock
1308 // becomes long, if we just continued to treat it as long we can get in to
1309 // situations where we spam battery stats with every following change to it.
1310 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001311 }
1312 }
1313
Jeff Brown96307042012-07-27 15:51:34 -07001314 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001315 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1316 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001317 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001318 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1319 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1320 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001321 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001322 }
1323 }
1324
Jeff Brownec083212013-09-11 20:45:25 -07001325 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001326 private boolean isWakeLockLevelSupportedInternal(int level) {
1327 synchronized (mLock) {
1328 switch (level) {
1329 case PowerManager.PARTIAL_WAKE_LOCK:
1330 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1331 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1332 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001333 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001334 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001335 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001336
1337 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001338 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001339
1340 default:
1341 return false;
1342 }
1343 }
1344 }
1345
Jeff Brown96307042012-07-27 15:51:34 -07001346 // Called from native code.
1347 private void userActivityFromNative(long eventTime, int event, int flags) {
1348 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1349 }
1350
1351 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1352 synchronized (mLock) {
1353 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1354 updatePowerStateLocked();
1355 }
1356 }
1357 }
1358
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001359 private void onUserAttention() {
1360 synchronized (mLock) {
1361 if (userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1362 PowerManager.USER_ACTIVITY_EVENT_ATTENTION, 0 /* flags */,
1363 Process.SYSTEM_UID)) {
1364 updatePowerStateLocked();
1365 }
1366 }
1367 }
1368
Jeff Brown96307042012-07-27 15:51:34 -07001369 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1370 if (DEBUG_SPEW) {
1371 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1372 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1373 + ", uid=" + uid);
1374 }
1375
1376 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001377 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001378 return false;
1379 }
1380
Jeff Brown3edf5272014-08-14 19:25:14 -07001381 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1382 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001383 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001384 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001385 mLastInteractivePowerHintTime = eventTime;
1386 }
1387
Jeff Brown3edf5272014-08-14 19:25:14 -07001388 mNotifier.onUserActivity(event, uid);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001389 mAttentionDetector.onUserActivity(eventTime, event);
Jeff Brown96307042012-07-27 15:51:34 -07001390
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001391 if (mUserInactiveOverrideFromWindowManager) {
1392 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001393 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001394 }
1395
Jeff Brown0a571122014-08-21 21:50:43 -07001396 if (mWakefulness == WAKEFULNESS_ASLEEP
1397 || mWakefulness == WAKEFULNESS_DOZING
1398 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1399 return false;
1400 }
1401
Pavel Grafov28939982017-10-03 15:11:52 +01001402 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1403
Jeff Brown3edf5272014-08-14 19:25:14 -07001404 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1405 if (eventTime > mLastUserActivityTimeNoChangeLights
1406 && eventTime > mLastUserActivityTime) {
1407 mLastUserActivityTimeNoChangeLights = eventTime;
1408 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001409 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1410 mDirty |= DIRTY_QUIESCENT;
1411 }
1412
Jeff Brown3edf5272014-08-14 19:25:14 -07001413 return true;
1414 }
1415 } else {
1416 if (eventTime > mLastUserActivityTime) {
1417 mLastUserActivityTime = eventTime;
1418 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001419 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1420 mDirty |= DIRTY_QUIESCENT;
1421 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001422 return true;
1423 }
Jeff Brown96307042012-07-27 15:51:34 -07001424 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001425 } finally {
1426 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001427 }
1428 return false;
1429 }
1430
Pavel Grafov28939982017-10-03 15:11:52 +01001431 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1432 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1433 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1434 profile.mLastUserActivityTime = eventTime;
1435 }
1436 }
1437
Michael Wrighte3001042019-02-05 00:13:14 +00001438 private void wakeUpInternal(long eventTime, @WakeReason int reason, String details, int uid,
1439 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001440 synchronized (mLock) {
Michael Wrighte3001042019-02-05 00:13:14 +00001441 if (wakeUpNoUpdateLocked(eventTime, reason, details, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001442 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001443 }
1444 }
Jeff Brown96307042012-07-27 15:51:34 -07001445 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001446
Michael Wrighte3001042019-02-05 00:13:14 +00001447 private boolean wakeUpNoUpdateLocked(long eventTime, @WakeReason int reason, String details,
1448 int reasonUid, String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001449 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001450 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001451 }
Jeff Brown96307042012-07-27 15:51:34 -07001452
1453 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
Santos Cordon12f92eb2019-02-01 21:28:47 +00001454 || !mBootCompleted || !mSystemReady || mForceSuspendActive) {
Jeff Brown96307042012-07-27 15:51:34 -07001455 return false;
1456 }
1457
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001458 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1459
Jeff Brown3edf5272014-08-14 19:25:14 -07001460 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1461 try {
Michael Wrighte3001042019-02-05 00:13:14 +00001462 Slog.i(TAG, "Waking up from "
1463 + PowerManagerInternal.wakefulnessToString(mWakefulness)
1464 + " (uid=" + reasonUid
1465 + ", reason=" + PowerManager.wakeReasonToString(reason)
1466 + ", details=" + details
1467 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001468
1469 mLastWakeTime = eventTime;
Michael Wrighte3001042019-02-05 00:13:14 +00001470 mLastWakeReason = reason;
1471 setWakefulnessLocked(WAKEFULNESS_AWAKE, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001472
Michael Wrighte3001042019-02-05 00:13:14 +00001473 mNotifier.onWakeUp(reason, details, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001474 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001475 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001476 } finally {
1477 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001478 }
Jeff Brown96307042012-07-27 15:51:34 -07001479 return true;
1480 }
1481
Jeff Brownc12035c2014-08-13 18:52:25 -07001482 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001483 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001484 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001485 updatePowerStateLocked();
1486 }
1487 }
1488 }
1489
Santos Cordon12f92eb2019-02-01 21:28:47 +00001490 /**
1491 * Puts the system in doze.
1492 *
1493 * This method is called goToSleep for historical reasons but actually attempts to DOZE,
1494 * and only tucks itself in to SLEEP if requested with the flag
1495 * {@link PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE}.
1496 */
Jeff Brownec083212013-09-11 20:45:25 -07001497 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001498 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001499 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001500 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001501 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001502 }
1503
Jeff Brown26875502014-01-30 21:47:47 -08001504 if (eventTime < mLastWakeTime
1505 || mWakefulness == WAKEFULNESS_ASLEEP
1506 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001507 || !mBootCompleted || !mSystemReady) {
1508 return false;
1509 }
1510
Jeff Brown3edf5272014-08-14 19:25:14 -07001511 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1512 try {
Santos Cordon12f92eb2019-02-01 21:28:47 +00001513 reason = Math.min(PowerManager.GO_TO_SLEEP_REASON_MAX,
1514 Math.max(reason, PowerManager.GO_TO_SLEEP_REASON_MIN));
1515 Slog.i(TAG, "Going to sleep due to " + PowerManager.sleepReasonToString(reason)
1516 + " (uid " + uid + ")...");
Jeff Brown6d8fd272014-05-20 21:24:38 -07001517
Jeff Brown3edf5272014-08-14 19:25:14 -07001518 mLastSleepTime = eventTime;
Calin Tatarua3805722018-08-09 16:41:28 +02001519 mLastSleepReason = reason;
Jeff Brown3edf5272014-08-14 19:25:14 -07001520 mSandmanSummoned = true;
Santos Cordon03044382019-09-19 16:59:01 +01001521 mDozeStartInProgress = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001522 setWakefulnessLocked(WAKEFULNESS_DOZING, reason, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001523
1524 // Report the number of wake locks that will be cleared by going to sleep.
1525 int numWakeLocksCleared = 0;
1526 final int numWakeLocks = mWakeLocks.size();
1527 for (int i = 0; i < numWakeLocks; i++) {
1528 final WakeLock wakeLock = mWakeLocks.get(i);
1529 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1530 case PowerManager.FULL_WAKE_LOCK:
1531 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1532 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1533 numWakeLocksCleared += 1;
1534 break;
1535 }
1536 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001537 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001538
1539 // Skip dozing if requested.
1540 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1541 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1542 }
1543 } finally {
1544 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001545 }
Jeff Brown96307042012-07-27 15:51:34 -07001546 return true;
1547 }
1548
Jeff Brownc12035c2014-08-13 18:52:25 -07001549 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001550 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001551 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001552 updatePowerStateLocked();
1553 }
1554 }
1555 }
1556
Jeff Brownc12035c2014-08-13 18:52:25 -07001557 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001558 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001559 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001560 }
1561
1562 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1563 || !mBootCompleted || !mSystemReady) {
1564 return false;
1565 }
1566
Jeff Brown3edf5272014-08-14 19:25:14 -07001567 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1568 try {
1569 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001570
Jeff Brown3edf5272014-08-14 19:25:14 -07001571 mSandmanSummoned = true;
Michael Wrighte3001042019-02-05 00:13:14 +00001572 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0, eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001573 } finally {
1574 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1575 }
Jeff Brown26875502014-01-30 21:47:47 -08001576 return true;
1577 }
1578
1579 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001580 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001581 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001582 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1583 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001584 }
1585
1586 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1587 || !mBootCompleted || !mSystemReady) {
1588 return false;
1589 }
1590
Jeff Brown3edf5272014-08-14 19:25:14 -07001591 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1592 try {
1593 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001594
Michael Wrighte3001042019-02-05 00:13:14 +00001595 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT,
1596 eventTime);
Jeff Brown3edf5272014-08-14 19:25:14 -07001597 } finally {
1598 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1599 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001600 return true;
1601 }
1602
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001603 @VisibleForTesting
Michael Wrighte3001042019-02-05 00:13:14 +00001604 void setWakefulnessLocked(int wakefulness, int reason, long eventTime) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001605 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001606 mWakefulness = wakefulness;
1607 mWakefulnessChanging = true;
1608 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon03044382019-09-19 16:59:01 +01001609
1610 // This is only valid while we are in wakefulness dozing. Set to false otherwise.
1611 mDozeStartInProgress &= (mWakefulness == WAKEFULNESS_DOZING);
1612
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001613 if (mNotifier != null) {
Michael Wrighte3001042019-02-05 00:13:14 +00001614 mNotifier.onWakefulnessChangeStarted(wakefulness, reason, eventTime);
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001615 }
Lucas Dupin0a5d7972019-01-16 18:52:30 -08001616 mAttentionDetector.onWakefulnessChangeStarted(wakefulness);
Jeff Brown037c33e2014-04-09 00:31:55 -07001617 }
1618 }
1619
Santos Cordon64a6e612018-08-22 19:27:04 +01001620 @VisibleForTesting
1621 int getWakefulness() {
1622 return mWakefulness;
1623 }
1624
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001625 /**
1626 * Logs the time the device would have spent awake before user activity timeout,
1627 * had the system not been told the user was inactive.
1628 */
1629 private void logSleepTimeoutRecapturedLocked() {
1630 final long now = SystemClock.uptimeMillis();
1631 final long savedWakeTimeMs = mOverriddenTimeout - now;
1632 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001633 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001634 mOverriddenTimeout = -1;
1635 }
1636 }
1637
Jeff Brown416c49c2015-05-26 19:50:18 -07001638 private void finishWakefulnessChangeIfNeededLocked() {
1639 if (mWakefulnessChanging && mDisplayReady) {
1640 if (mWakefulness == WAKEFULNESS_DOZING
1641 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1642 return; // wait until dream has enabled dozing
Santos Cordon03044382019-09-19 16:59:01 +01001643 } else {
1644 // Doze wakelock acquired (doze started) or device is no longer dozing.
1645 mDozeStartInProgress = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001646 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001647 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1648 logSleepTimeoutRecapturedLocked();
1649 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001650 if (mWakefulness == WAKEFULNESS_AWAKE) {
Michael Wrighte3001042019-02-05 00:13:14 +00001651 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1652 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1653 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1654 Slog.w(TAG, "Screen on took " + latencyMs + " ms");
1655 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001656 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001657 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001658 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001659 }
1660 }
1661
Jeff Brown96307042012-07-27 15:51:34 -07001662 /**
1663 * Updates the global power state based on dirty bits recorded in mDirty.
1664 *
1665 * This is the main function that performs power state transitions.
1666 * We centralize them here so that we can recompute the power state completely
1667 * each time something important changes, and ensure that we do it the same
1668 * way each time. The point is to gather all of the transition logic here.
1669 */
1670 private void updatePowerStateLocked() {
1671 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001672 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001673 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001674 if (!Thread.holdsLock(mLock)) {
1675 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1676 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001677
Jeff Brown3edf5272014-08-14 19:25:14 -07001678 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1679 try {
1680 // Phase 0: Basic state updates.
1681 updateIsPoweredLocked(mDirty);
1682 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001683 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684
Jeff Brown3edf5272014-08-14 19:25:14 -07001685 // Phase 1: Update wakefulness.
1686 // Loop because the wake lock and user activity computations are influenced
1687 // by changes in wakefulness.
1688 final long now = SystemClock.uptimeMillis();
1689 int dirtyPhase2 = 0;
1690 for (;;) {
1691 int dirtyPhase1 = mDirty;
1692 dirtyPhase2 |= dirtyPhase1;
1693 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001694
Jeff Brown3edf5272014-08-14 19:25:14 -07001695 updateWakeLockSummaryLocked(dirtyPhase1);
1696 updateUserActivitySummaryLocked(now, dirtyPhase1);
1697 if (!updateWakefulnessLocked(dirtyPhase1)) {
1698 break;
1699 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001701
Pavel Grafov28939982017-10-03 15:11:52 +01001702 // Phase 2: Lock profiles that became inactive/not kept awake.
1703 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001704
Pavel Grafov28939982017-10-03 15:11:52 +01001705 // Phase 3: Update display power state.
1706 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1707
1708 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001709 updateDreamLocked(dirtyPhase2, displayBecameReady);
1710
Pavel Grafov28939982017-10-03 15:11:52 +01001711 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001712 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001713
Pavel Grafov28939982017-10-03 15:11:52 +01001714 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001715 // Because we might release the last suspend blocker here, we need to make sure
1716 // we finished everything else first!
1717 updateSuspendBlockerLocked();
1718 } finally {
1719 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
Jeff Brown96307042012-07-27 15:51:34 -07001721 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001722
Jim Miller92e66dd2012-02-21 18:57:12 -08001723 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001724 * Check profile timeouts and notify profiles that should be locked.
1725 */
1726 private void updateProfilesLocked(long now) {
1727 final int numProfiles = mProfilePowerState.size();
1728 for (int i = 0; i < numProfiles; i++) {
1729 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1730 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1731 profile.mLockingNotified = false;
1732 } else if (!profile.mLockingNotified) {
1733 profile.mLockingNotified = true;
1734 mNotifier.onProfileTimeout(profile.mUserId);
1735 }
1736 }
1737 }
1738
1739 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1740 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1741 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1742 || (mProximityPositive &&
1743 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1744 }
1745
1746 /**
Jeff Brown96307042012-07-27 15:51:34 -07001747 * Updates the value of mIsPowered.
1748 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001749 */
Jeff Brown96307042012-07-27 15:51:34 -07001750 private void updateIsPoweredLocked(int dirty) {
1751 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001752 final boolean wasPowered = mIsPowered;
1753 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001754 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001755 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1756 mPlugType = mBatteryManagerInternal.getPlugType();
1757 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1758 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001759
Jeff Brown26875502014-01-30 21:47:47 -08001760 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001761 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001762 + ", mIsPowered=" + mIsPowered
1763 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001764 + ", mPlugType=" + mPlugType
1765 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001766 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001767
Jeff Brownf3fb8952012-10-02 20:57:05 -07001768 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001769 mDirty |= DIRTY_IS_POWERED;
1770
Jeff Brown3b971592013-01-09 18:46:37 -08001771 // Update wireless dock detection state.
1772 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001773 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001774
Jeff Brown96307042012-07-27 15:51:34 -07001775 // Treat plugging and unplugging the devices as a user activity.
1776 // Users find it disconcerting when they plug or unplug the device
1777 // and it shuts off right away.
1778 // Some devices also wake the device when plugged or unplugged because
1779 // they don't have a charging LED.
1780 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001781 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1782 dockedOnWirelessCharger)) {
Michael Wrighte3001042019-02-05 00:13:14 +00001783 wakeUpNoUpdateLocked(now, PowerManager.WAKE_REASON_PLUGGED_IN,
1784 "android.server.power:PLUGGED:" + mIsPowered, Process.SYSTEM_UID,
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001785 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001786 }
1787 userActivityNoUpdateLocked(
1788 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001789
Beverlyac32c9a2018-01-31 16:10:41 -05001790 // only play charging sounds if boot is completed so charging sounds don't play
1791 // with potential notification sounds
1792 if (mBootCompleted) {
1793 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1794 && BatteryManager.isPlugWired(mPlugType)) {
Beverly91d0a632018-07-02 16:45:00 -04001795 mNotifier.onWiredChargingStarted(mForegroundProfile);
Beverlyac32c9a2018-01-31 16:10:41 -05001796 } else if (dockedOnWirelessCharger) {
Beverly91d0a632018-07-02 16:45:00 -04001797 mNotifier.onWirelessChargingStarted(mBatteryLevel, mForegroundProfile);
Beverlyac32c9a2018-01-31 16:10:41 -05001798 }
Jeff Brown84e27562012-12-07 13:56:34 -08001799 }
Jeff Brown96307042012-07-27 15:51:34 -07001800 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001801
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001802 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001803 }
1804 }
1805
Jeff Brown3b971592013-01-09 18:46:37 -08001806 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1807 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001808 // Don't wake when powered unless configured to do so.
1809 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1810 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001811 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001812
Jeff Brown3b971592013-01-09 18:46:37 -08001813 // Don't wake when undocked from wireless charger.
1814 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001815 if (wasPowered && !mIsPowered
1816 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1817 return false;
1818 }
Jeff Brown3b971592013-01-09 18:46:37 -08001819
1820 // Don't wake when docked on wireless charger unless we are certain of it.
1821 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001822 if (!wasPowered && mIsPowered
1823 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001824 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001825 return false;
1826 }
1827
1828 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001829 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001830 return false;
1831 }
1832
Bryce Lee584a4452014-10-21 15:55:55 -07001833 // Don't wake while theater mode is enabled.
1834 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1835 return false;
1836 }
1837
Adrian Roos56021892017-02-27 20:25:09 +01001838 // On Always On Display, SystemUI shows the charging indicator
1839 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1840 return false;
1841 }
1842
Jeff Brown9fca9e92012-10-05 14:42:56 -07001843 // Otherwise wake up!
1844 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001845 }
1846
Jeff Brown96307042012-07-27 15:51:34 -07001847 /**
1848 * Updates the value of mStayOn.
1849 * Sets DIRTY_STAY_ON if a change occurred.
1850 */
1851 private void updateStayOnLocked(int dirty) {
1852 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001853 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001854 if (mStayOnWhilePluggedInSetting != 0
1855 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001856 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001857 } else {
1858 mStayOn = false;
1859 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001860
1861 if (mStayOn != wasStayOn) {
1862 mDirty |= DIRTY_STAY_ON;
1863 }
Jeff Brown96307042012-07-27 15:51:34 -07001864 }
1865 }
1866
1867 /**
1868 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1869 * Note that most wake-locks are ignored when the system is asleep.
1870 *
1871 * This function must have no other side-effects.
1872 */
Jeff Brownec083212013-09-11 20:45:25 -07001873 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001874 private void updateWakeLockSummaryLocked(int dirty) {
1875 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1876 mWakeLockSummary = 0;
1877
Pavel Grafov28939982017-10-03 15:11:52 +01001878 final int numProfiles = mProfilePowerState.size();
1879 for (int i = 0; i < numProfiles; i++) {
1880 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1881 }
1882
Jeff Brown96307042012-07-27 15:51:34 -07001883 final int numWakeLocks = mWakeLocks.size();
1884 for (int i = 0; i < numWakeLocks; i++) {
1885 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001886 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1887 mWakeLockSummary |= wakeLockFlags;
1888 for (int j = 0; j < numProfiles; j++) {
1889 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1890 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1891 profile.mWakeLockSummary |= wakeLockFlags;
1892 }
Jeff Brown96307042012-07-27 15:51:34 -07001893 }
1894 }
1895
Pavel Grafov28939982017-10-03 15:11:52 +01001896 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1897 for (int i = 0; i < numProfiles; i++) {
1898 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1899 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001900 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001901
Jeff Brown96307042012-07-27 15:51:34 -07001902 if (DEBUG_SPEW) {
1903 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001904 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001905 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1906 }
1907 }
1908 }
1909
Pavel Grafov28939982017-10-03 15:11:52 +01001910 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1911 // Cancel wake locks that make no sense based on the current state.
1912 if (mWakefulness != WAKEFULNESS_DOZING) {
1913 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1914 }
1915 if (mWakefulness == WAKEFULNESS_ASLEEP
1916 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1917 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1918 | WAKE_LOCK_BUTTON_BRIGHT);
1919 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1920 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1921 }
1922 }
1923
1924 // Infer implied wake locks where necessary based on the current state.
1925 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1926 if (mWakefulness == WAKEFULNESS_AWAKE) {
1927 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1928 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1929 wakeLockSummary |= WAKE_LOCK_CPU;
1930 }
1931 }
1932 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1933 wakeLockSummary |= WAKE_LOCK_CPU;
1934 }
1935
1936 return wakeLockSummary;
1937 }
1938
1939 /** Get wake lock summary flags that correspond to the given wake lock. */
1940 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1941 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1942 case PowerManager.PARTIAL_WAKE_LOCK:
1943 if (!wakeLock.mDisabled) {
1944 // We only respect this if the wake lock is not disabled.
1945 return WAKE_LOCK_CPU;
1946 }
1947 break;
1948 case PowerManager.FULL_WAKE_LOCK:
1949 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1950 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1951 return WAKE_LOCK_SCREEN_BRIGHT;
1952 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1953 return WAKE_LOCK_SCREEN_DIM;
1954 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1955 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1956 case PowerManager.DOZE_WAKE_LOCK:
1957 return WAKE_LOCK_DOZE;
1958 case PowerManager.DRAW_WAKE_LOCK:
1959 return WAKE_LOCK_DRAW;
1960 }
1961 return 0;
1962 }
1963
1964 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
1965 if (wakeLock.mWorkSource != null) {
1966 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
1967 final int uid = wakeLock.mWorkSource.get(k);
1968 if (userId == UserHandle.getUserId(uid)) {
1969 return true;
1970 }
1971 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00001972
1973 final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
1974 if (workChains != null) {
1975 for (int k = 0; k < workChains.size(); k++) {
1976 final int uid = workChains.get(k).getAttributionUid();
1977 if (userId == UserHandle.getUserId(uid)) {
1978 return true;
1979 }
1980 }
1981 }
Pavel Grafov28939982017-10-03 15:11:52 +01001982 }
1983 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
1984 }
1985
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001986 void checkForLongWakeLocks() {
1987 synchronized (mLock) {
1988 final long now = SystemClock.uptimeMillis();
1989 mNotifyLongDispatched = now;
1990 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1991 long nextCheckTime = Long.MAX_VALUE;
1992 final int numWakeLocks = mWakeLocks.size();
1993 for (int i = 0; i < numWakeLocks; i++) {
1994 final WakeLock wakeLock = mWakeLocks.get(i);
1995 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1996 == PowerManager.PARTIAL_WAKE_LOCK) {
1997 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1998 if (wakeLock.mAcquireTime < when) {
1999 // This wake lock has exceeded the long acquire time, report!
2000 notifyWakeLockLongStartedLocked(wakeLock);
2001 } else {
2002 // This wake lock could still become a long one, at this time.
2003 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
2004 if (checkTime < nextCheckTime) {
2005 nextCheckTime = checkTime;
2006 }
2007 }
2008 }
2009 }
2010 }
2011 mNotifyLongScheduled = 0;
2012 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
2013 if (nextCheckTime != Long.MAX_VALUE) {
2014 mNotifyLongNextCheck = nextCheckTime;
2015 enqueueNotifyLongMsgLocked(nextCheckTime);
2016 } else {
2017 mNotifyLongNextCheck = 0;
2018 }
2019 }
2020 }
2021
Jeff Brown96307042012-07-27 15:51:34 -07002022 /**
2023 * Updates the value of mUserActivitySummary to summarize the user requested
2024 * state of the system such as whether the screen should be bright or dim.
2025 * Note that user activity is ignored when the system is asleep.
2026 *
2027 * This function must have no other side-effects.
2028 */
2029 private void updateUserActivitySummaryLocked(long now, int dirty) {
2030 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07002031 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08002032 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002033 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
2034
2035 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08002036 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07002037 || mWakefulness == WAKEFULNESS_DREAMING
2038 || mWakefulness == WAKEFULNESS_DOZING) {
Pavel Grafov28939982017-10-03 15:11:52 +01002039 final long sleepTimeout = getSleepTimeoutLocked();
2040 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
2041 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002042 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01002043 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07002044
2045 mUserActivitySummary = 0;
2046 if (mLastUserActivityTime >= mLastWakeTime) {
2047 nextTimeout = mLastUserActivityTime
2048 + screenOffTimeout - screenDimDuration;
2049 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002050 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002051 } else {
2052 nextTimeout = mLastUserActivityTime + screenOffTimeout;
2053 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002054 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002055 }
2056 }
2057 }
2058 if (mUserActivitySummary == 0
2059 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
2060 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07002061 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07002062 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
2063 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07002064 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
2065 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
2066 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
2067 }
Jeff Brown96307042012-07-27 15:51:34 -07002068 }
2069 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002070
Jeff Brown05af6ad2014-09-30 20:54:30 -07002071 if (mUserActivitySummary == 0) {
2072 if (sleepTimeout >= 0) {
2073 final long anyUserActivity = Math.max(mLastUserActivityTime,
2074 mLastUserActivityTimeNoChangeLights);
2075 if (anyUserActivity >= mLastWakeTime) {
2076 nextTimeout = anyUserActivity + sleepTimeout;
2077 if (now < nextTimeout) {
2078 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2079 }
2080 }
2081 } else {
2082 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2083 nextTimeout = -1;
2084 }
2085 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002086
2087 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002088 if ((mUserActivitySummary &
2089 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002090 // Device is being kept awake by recent user activity
2091 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2092 // Save when the next timeout would have occurred
2093 mOverriddenTimeout = nextTimeout;
2094 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002095 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002096 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2097 nextTimeout = -1;
2098 }
2099
Alex Salo9e242232019-05-14 19:27:17 -07002100 if ((mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
2101 && (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) == 0) {
Lucas Dupin0a5d7972019-01-16 18:52:30 -08002102 nextTimeout = mAttentionDetector.updateUserActivity(nextTimeout);
2103 }
2104
Pavel Grafov28939982017-10-03 15:11:52 +01002105 if (nextProfileTimeout > 0) {
2106 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2107 }
2108
Jeff Brown05af6ad2014-09-30 20:54:30 -07002109 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002110 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002111 }
2112 } else {
2113 mUserActivitySummary = 0;
2114 }
2115
2116 if (DEBUG_SPEW) {
2117 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002118 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002119 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2120 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2121 }
2122 }
2123 }
2124
Pavel Grafov28939982017-10-03 15:11:52 +01002125 private void scheduleUserInactivityTimeout(long timeMs) {
2126 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2127 msg.setAsynchronous(true);
2128 mHandler.sendMessageAtTime(msg, timeMs);
2129 }
2130
2131 /**
2132 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2133 */
2134 private long getNextProfileTimeoutLocked(long now) {
2135 long nextTimeout = -1;
2136 final int numProfiles = mProfilePowerState.size();
2137 for (int i = 0; i < numProfiles; i++) {
2138 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2139 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2140 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2141 nextTimeout = timeout;
2142 }
2143 }
2144 return nextTimeout;
2145 }
2146
Jeff Brown96307042012-07-27 15:51:34 -07002147 /**
2148 * Called when a user activity timeout has occurred.
2149 * Simply indicates that something about user activity has changed so that the new
2150 * state can be recomputed when the power state is updated.
2151 *
2152 * This function must have no other side-effects besides setting the dirty
2153 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2154 */
2155 private void handleUserActivityTimeout() { // runs on handler thread
2156 synchronized (mLock) {
2157 if (DEBUG_SPEW) {
2158 Slog.d(TAG, "handleUserActivityTimeout");
2159 }
2160
2161 mDirty |= DIRTY_USER_ACTIVITY;
2162 updatePowerStateLocked();
2163 }
2164 }
2165
Pavel Grafov28939982017-10-03 15:11:52 +01002166 private long getSleepTimeoutLocked() {
2167 final long timeout = mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002168 if (timeout <= 0) {
2169 return -1;
2170 }
2171 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2172 }
2173
Pavel Grafov28939982017-10-03 15:11:52 +01002174 private long getScreenOffTimeoutLocked(long sleepTimeout) {
2175 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002176 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2177 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2178 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002179 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002180 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002181 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002182 if (sleepTimeout >= 0) {
2183 timeout = Math.min(timeout, sleepTimeout);
2184 }
Jeff Brown27736f52014-05-20 17:17:10 -07002185 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002186 }
2187
Pavel Grafov28939982017-10-03 15:11:52 +01002188 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002189 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002190 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002191 }
2192
2193 /**
2194 * Updates the wakefulness of the device.
2195 *
Jeff Brown26875502014-01-30 21:47:47 -08002196 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002197 * based on the current wake locks and user activity state. It may modify mDirty
2198 * if the wakefulness changes.
2199 *
2200 * Returns true if the wakefulness changed and we need to restart power state calculation.
2201 */
2202 private boolean updateWakefulnessLocked(int dirty) {
2203 boolean changed = false;
2204 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002205 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
2206 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002207 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2208 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002209 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002210 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002211 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07002212 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002213 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002214 } else {
2215 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002216 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002217 }
Jeff Brown96307042012-07-27 15:51:34 -07002218 }
2219 }
2220 return changed;
2221 }
2222
Jeff Brown645832d2012-10-03 14:57:03 -07002223 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002224 * Returns true if the device should automatically nap and start dreaming when the user
2225 * activity timeout has expired and it's bedtime.
2226 */
2227 private boolean shouldNapAtBedTimeLocked() {
2228 return mDreamsActivateOnSleepSetting
2229 || (mDreamsActivateOnDockSetting
2230 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2231 }
2232
2233 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002234 * Returns true if the device should go to sleep now.
2235 * Also used when exiting a dream to determine whether we should go back
2236 * to being fully awake or else go to sleep for good.
2237 */
Jeff Brown96307042012-07-27 15:51:34 -07002238 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07002239 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07002240 }
2241
2242 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002243 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002244 * or the stay on while powered setting. We also keep the phone awake when
2245 * the proximity sensor returns a positive result so that the device does not
2246 * lock while in a phone call. This function only controls whether the device
2247 * will go to sleep or dream which is independent of whether it will be allowed
2248 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002249 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002250 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002251 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002252 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002253 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002254 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002255 | USER_ACTIVITY_SCREEN_DIM)) != 0
2256 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002257 }
2258
2259 /**
2260 * Determines whether to post a message to the sandman to update the dream state.
2261 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002262 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002263 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002264 | DIRTY_USER_ACTIVITY
2265 | DIRTY_WAKE_LOCKS
2266 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002267 | DIRTY_SETTINGS
2268 | DIRTY_IS_POWERED
2269 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002270 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002271 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2272 if (mDisplayReady) {
2273 scheduleSandmanLocked();
2274 }
Jeff Brown96307042012-07-27 15:51:34 -07002275 }
2276 }
2277
2278 private void scheduleSandmanLocked() {
2279 if (!mSandmanScheduled) {
2280 mSandmanScheduled = true;
2281 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2282 msg.setAsynchronous(true);
2283 mHandler.sendMessage(msg);
2284 }
2285 }
2286
2287 /**
Jeff Brown26875502014-01-30 21:47:47 -08002288 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002289 *
2290 * We do this asynchronously because we must call out of the power manager to start
2291 * the dream and we don't want to hold our lock while doing so. There is a risk that
2292 * the device will wake or go to sleep in the meantime so we have to handle that case.
2293 */
2294 private void handleSandman() { // runs on handler thread
2295 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002296 final boolean startDreaming;
2297 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002298 synchronized (mLock) {
2299 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002300 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002301 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002302 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002303 mSandmanSummoned = false;
2304 } else {
2305 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002306 }
2307 }
2308
Jeff Brown96307042012-07-27 15:51:34 -07002309 // Start dreaming if needed.
2310 // We only control the dream on the handler thread, so we don't need to worry about
2311 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002312 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002313 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002314 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002315 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002316 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002317 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002318 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002319 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002320 } else {
2321 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002322 }
2323
Santos Cordon03044382019-09-19 16:59:01 +01002324 // At this point, we either attempted to start the dream or no attempt will be made,
2325 // so stop holding the display suspend blocker for Doze.
2326 mDozeStartInProgress = false;
2327
Jeff Brown96307042012-07-27 15:51:34 -07002328 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002329 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002330 // Remember the initial battery level when the dream started.
2331 if (startDreaming && isDreaming) {
2332 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2333 if (wakefulness == WAKEFULNESS_DOZING) {
2334 Slog.i(TAG, "Dozing...");
2335 } else {
2336 Slog.i(TAG, "Dreaming...");
2337 }
2338 }
2339
2340 // If preconditions changed, wait for the next iteration to determine
2341 // whether the dream should continue (or be restarted).
2342 if (mSandmanSummoned || mWakefulness != wakefulness) {
2343 return; // wait for next cycle
2344 }
2345
2346 // Determine whether the dream should continue.
2347 if (wakefulness == WAKEFULNESS_DREAMING) {
2348 if (isDreaming && canDreamLocked()) {
2349 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002350 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002351 - mDreamsBatteryLevelDrainCutoffConfig
2352 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002353 // If the user activity timeout expired and the battery appears
2354 // to be draining faster than it is charging then stop dreaming
2355 // and go to sleep.
2356 Slog.i(TAG, "Stopping dream because the battery appears to "
2357 + "be draining faster than it is charging. "
2358 + "Battery level when dream started: "
2359 + mBatteryLevelWhenDreamStarted + "%. "
2360 + "Battery level now: " + mBatteryLevel + "%.");
2361 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002362 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002363 }
Jeff Brown96307042012-07-27 15:51:34 -07002364 }
Jeff Brown26875502014-01-30 21:47:47 -08002365
2366 // Dream has ended or will be stopped. Update the power state.
2367 if (isItBedTimeYetLocked()) {
2368 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07002369 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002370 updatePowerStateLocked();
2371 } else {
Michael Wrighte3001042019-02-05 00:13:14 +00002372 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(),
2373 PowerManager.WAKE_REASON_UNKNOWN,
2374 "android.server.power:DREAM_FINISHED", Process.SYSTEM_UID,
2375 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002376 updatePowerStateLocked();
2377 }
2378 } else if (wakefulness == WAKEFULNESS_DOZING) {
2379 if (isDreaming) {
2380 return; // continue dozing
2381 }
2382
2383 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07002384 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002385 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002386 }
Jeff Brown96307042012-07-27 15:51:34 -07002387 }
2388
Jeff Brown26875502014-01-30 21:47:47 -08002389 // Stop dream.
2390 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002391 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002392 }
2393 }
2394
2395 /**
Jeff Brown26875502014-01-30 21:47:47 -08002396 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002397 */
2398 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002399 if (mWakefulness != WAKEFULNESS_DREAMING
2400 || !mDreamsSupportedConfig
2401 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002402 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002403 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002404 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2405 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002406 || !mBootCompleted) {
2407 return false;
2408 }
2409 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002410 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002411 return false;
2412 }
2413 if (!mIsPowered
2414 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2415 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2416 return false;
2417 }
2418 if (mIsPowered
2419 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2420 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2421 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002422 }
2423 }
Jeff Brown26875502014-01-30 21:47:47 -08002424 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002425 }
2426
Jeff Brown96307042012-07-27 15:51:34 -07002427 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002428 * Returns true if the device is allowed to doze in its current state.
2429 */
2430 private boolean canDozeLocked() {
2431 return mWakefulness == WAKEFULNESS_DOZING;
2432 }
2433
2434 /**
Jeff Brown96307042012-07-27 15:51:34 -07002435 * Updates the display power state asynchronously.
2436 * When the update is finished, mDisplayReady will be set to true. The display
2437 * controller posts a message to tell us when the actual display power state
2438 * has been updated so we come back here to double-check and finish up.
2439 *
2440 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002441 *
2442 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002443 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002444 private boolean updateDisplayPowerStateLocked(int dirty) {
2445 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002446 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2447 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002448 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2449 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002450 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002451
Jeff Browne333e672014-10-28 13:48:55 -07002452 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002453 final boolean autoBrightness;
2454 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002455 if (!mBootCompleted) {
2456 // Keep the brightness steady during boot. This requires the
2457 // bootloader brightness and the default brightness to be identical.
2458 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002459 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002460 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002461 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002462 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2463 } else {
2464 autoBrightness = (mScreenBrightnessModeSetting ==
2465 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2466 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002467 }
Jeff Browne333e672014-10-28 13:48:55 -07002468
2469 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002470 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002471 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002472 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002473 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002474
jackqdyulei92681e82017-02-28 11:26:28 -08002475 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2476
Jeff Brown970d4132014-07-19 11:33:47 -07002477 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2478 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002479 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2480 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002481 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2482 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2483 }
2484 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2485 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2486 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002487 }
Jeff Brown970d4132014-07-19 11:33:47 -07002488 mDisplayPowerRequest.dozeScreenBrightness =
2489 mDozeScreenBrightnessOverrideFromDreamManager;
2490 } else {
2491 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2492 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2493 }
2494
Jeff Brown131206b2014-04-08 17:27:14 -07002495 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002496 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002497 mRequestWaitForNegativeProximity = false;
2498
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002499 if ((dirty & DIRTY_QUIESCENT) != 0) {
2500 sQuiescent = false;
2501 }
Jeff Brown96307042012-07-27 15:51:34 -07002502 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002503 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002504 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002505 + ", mWakefulness=" + mWakefulness
2506 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2507 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002508 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002509 + ", screenBrightnessOverride=" + screenBrightnessOverride
2510 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002511 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002512 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002513 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002514 }
2515 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002516 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002517 }
2518
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002519 private void updateScreenBrightnessBoostLocked(int dirty) {
2520 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2521 if (mScreenBrightnessBoostInProgress) {
2522 final long now = SystemClock.uptimeMillis();
2523 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2524 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2525 final long boostTimeout = mLastScreenBrightnessBoostTime +
2526 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2527 if (boostTimeout > now) {
2528 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2529 msg.setAsynchronous(true);
2530 mHandler.sendMessageAtTime(msg, boostTimeout);
2531 return;
2532 }
Jeff Browne333e672014-10-28 13:48:55 -07002533 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002534 mScreenBrightnessBoostInProgress = false;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002535 mNotifier.onScreenBrightnessBoostChanged();
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002536 userActivityNoUpdateLocked(now,
2537 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002538 }
Jeff Browne333e672014-10-28 13:48:55 -07002539 }
2540 }
2541
Santos Cordon3107d292016-09-20 15:50:35 -07002542 private boolean shouldBoostScreenBrightness() {
2543 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2544 }
2545
Jeff Brown96307042012-07-27 15:51:34 -07002546 private static boolean isValidBrightness(int value) {
2547 return value >= 0 && value <= 255;
2548 }
2549
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002550 @VisibleForTesting
2551 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002552 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002553 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002554 }
2555
Jeff Brown2175e9c2014-09-12 16:11:07 -07002556 if (mWakefulness == WAKEFULNESS_DOZING) {
2557 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2558 return DisplayPowerRequest.POLICY_DOZE;
2559 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002560 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002561 return DisplayPowerRequest.POLICY_OFF;
2562 }
2563 // Fall through and preserve the current screen policy if not configured to
2564 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002565 }
2566
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002567 // It is important that POLICY_VR check happens after the wakefulness checks above so
2568 // that VR-mode does not prevent displays from transitioning to the correct state when
2569 // dozing or sleeping.
2570 if (mIsVrModeEnabled) {
2571 return DisplayPowerRequest.POLICY_VR;
2572 }
2573
Jeff Brown96307042012-07-27 15:51:34 -07002574 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2575 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002576 || !mBootCompleted
2577 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002578 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002579 }
2580
Jeff Brown970d4132014-07-19 11:33:47 -07002581 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002582 }
2583
Jeff Brown131206b2014-04-08 17:27:14 -07002584 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2585 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002586 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002587
Jeff Brown96307042012-07-27 15:51:34 -07002588 @Override
2589 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002590 synchronized (mLock) {
2591 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2592 updatePowerStateLocked();
2593 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002594 }
2595
2596 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002597 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002598 synchronized (mLock) {
2599 mProximityPositive = true;
2600 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2601 updatePowerStateLocked();
2602 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002603 }
2604
2605 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002606 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002607 synchronized (mLock) {
2608 mProximityPositive = false;
2609 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2610 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2611 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2612 updatePowerStateLocked();
2613 }
Jeff Brown96307042012-07-27 15:51:34 -07002614 }
Jeff Brown131206b2014-04-08 17:27:14 -07002615
2616 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002617 public void onDisplayStateChange(int state) {
2618 // This method is only needed to support legacy display blanking behavior
2619 // where the display's power state is coupled to suspend or to the power HAL.
2620 // The order of operations matters here.
2621 synchronized (mLock) {
2622 if (mDisplayState != state) {
2623 mDisplayState = state;
2624 if (state == Display.STATE_OFF) {
2625 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2626 setHalInteractiveModeLocked(false);
2627 }
2628 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2629 setHalAutoSuspendModeLocked(true);
2630 }
2631 } else {
2632 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2633 setHalAutoSuspendModeLocked(false);
2634 }
2635 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2636 setHalInteractiveModeLocked(true);
2637 }
2638 }
2639 }
2640 }
2641 }
2642
2643 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002644 public void acquireSuspendBlocker() {
2645 mDisplaySuspendBlocker.acquire();
2646 }
2647
2648 @Override
2649 public void releaseSuspendBlocker() {
2650 mDisplaySuspendBlocker.release();
2651 }
2652
2653 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002654 public String toString() {
2655 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002656 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002657 }
2658 }
Jeff Brown96307042012-07-27 15:51:34 -07002659 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002660
Jeff Brown96307042012-07-27 15:51:34 -07002661 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002662 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002663 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002664
Jeff Brown96307042012-07-27 15:51:34 -07002665 /**
2666 * Updates the suspend blocker that keeps the CPU alive.
2667 *
2668 * This function must have no other side-effects.
2669 */
2670 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002671 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002672 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2673 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002674 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002675
2676 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002677 // FIXME We should consider just leaving auto-suspend enabled forever since
2678 // we already hold the necessary wakelocks.
2679 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2680 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002681 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002682
2683 // First acquire suspend blockers if needed.
2684 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2685 mWakeLockSuspendBlocker.acquire();
2686 mHoldingWakeLockSuspendBlocker = true;
2687 }
2688 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2689 mDisplaySuspendBlocker.acquire();
2690 mHoldingDisplaySuspendBlocker = true;
2691 }
2692
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002693 // Inform the power HAL about interactive mode.
2694 // Although we could set interactive strictly based on the wakefulness
2695 // as reported by isInteractive(), it is actually more desirable to track
2696 // the display policy state instead so that the interactive state observed
2697 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2698 // Refer to getDesiredScreenPolicyLocked() for details.
2699 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2700 // When becoming non-interactive, we want to defer sending this signal
2701 // until the display is actually ready so that all transitions have
2702 // completed. This is probably a good sign that things have gotten
2703 // too tangled over here...
2704 if (interactive || mDisplayReady) {
2705 setHalInteractiveModeLocked(interactive);
2706 }
2707 }
2708
Jeff Brown27f7a862012-12-12 15:43:31 -08002709 // Then release suspend blockers if needed.
2710 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2711 mWakeLockSuspendBlocker.release();
2712 mHoldingWakeLockSuspendBlocker = false;
2713 }
2714 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2715 mDisplaySuspendBlocker.release();
2716 mHoldingDisplaySuspendBlocker = false;
2717 }
Jeff Brown26875502014-01-30 21:47:47 -08002718
2719 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002720 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2721 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002722 }
Jeff Brown96307042012-07-27 15:51:34 -07002723 }
2724
Jeff Brownec083212013-09-11 20:45:25 -07002725 /**
2726 * Return true if we must keep a suspend blocker active on behalf of the display.
2727 * We do so if the screen is on or is in transition between states.
2728 */
Jeff Brown26875502014-01-30 21:47:47 -08002729 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002730 if (!mDisplayReady) {
2731 return true;
2732 }
Jeff Brown970d4132014-07-19 11:33:47 -07002733 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002734 // If we asked for the screen to be on but it is off due to the proximity
2735 // sensor then we may suspend but only if the configuration allows it.
2736 // On some hardware it may not be safe to suspend because the proximity
2737 // sensor may not be correctly configured as a wake-up source.
2738 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2739 || !mSuspendWhenScreenOffDueToProximityConfig) {
2740 return true;
2741 }
2742 }
Santos Cordond9701ab2019-08-01 18:33:20 +01002743
2744 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE
2745 && mDisplayPowerRequest.dozeScreenState == Display.STATE_ON) {
2746 // Although we are in DOZE and would normally allow the device to suspend,
2747 // the doze service has explicitly requested the display to remain in the ON
2748 // state which means we should hold the display suspend blocker.
2749 return true;
2750 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002751 if (mScreenBrightnessBoostInProgress) {
2752 return true;
2753 }
Santos Cordon03044382019-09-19 16:59:01 +01002754
2755 // When we transition to DOZING, we have to keep the display suspend blocker
2756 // up until the Doze service has a change to acquire the DOZE wakelock.
2757 // Here we wait for mWakefulnessChanging to become false since the wakefulness
2758 // transition to DOZING isn't considered "changed" until the doze wake lock is
2759 // acquired.
2760 if (mWakefulness == WAKEFULNESS_DOZING && mDozeStartInProgress) {
2761 return true;
2762 }
2763
Jeff Brown26875502014-01-30 21:47:47 -08002764 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002765 return false;
2766 }
2767
Jeff Brown037c33e2014-04-09 00:31:55 -07002768 private void setHalAutoSuspendModeLocked(boolean enable) {
2769 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002770 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002771 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002772 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002773 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002774 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2775 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002776 mNativeWrapper.nativeSetAutoSuspend(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002777 } finally {
2778 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2779 }
Jeff Brown26875502014-01-30 21:47:47 -08002780 }
2781 }
2782
Jeff Brown037c33e2014-04-09 00:31:55 -07002783 private void setHalInteractiveModeLocked(boolean enable) {
2784 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002785 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002786 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002787 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002788 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002789 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2790 try {
Santos Cordon64a6e612018-08-22 19:27:04 +01002791 mNativeWrapper.nativeSetInteractive(enable);
Jeff Brown3edf5272014-08-14 19:25:14 -07002792 } finally {
2793 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2794 }
Jeff Brown26875502014-01-30 21:47:47 -08002795 }
2796 }
2797
Jeff Brown037c33e2014-04-09 00:31:55 -07002798 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002799 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002800 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002801 }
2802 }
2803
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002804 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002805 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002806 if (DEBUG) {
2807 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2808 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002809 if (mIsPowered) {
2810 return false;
2811 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002812
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002813 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002814
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002815 return true;
2816 }
2817 }
2818
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002819 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002820 synchronized (mLock) {
2821 return mDeviceIdleMode;
2822 }
2823 }
2824
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002825 boolean isLightDeviceIdleModeInternal() {
2826 synchronized (mLock) {
2827 return mLightDeviceIdleMode;
2828 }
2829 }
2830
Jeff Brown96307042012-07-27 15:51:34 -07002831 private void handleBatteryStateChangedLocked() {
2832 mDirty |= DIRTY_BATTERY_STATE;
2833 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002834 }
2835
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002836 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002837 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002838 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07002839 if (RescueParty.isAttemptingFactoryReset()) {
2840 // If we're stuck in a really low-level reboot loop, and a
2841 // rescue party is trying to prompt the user for a factory data
2842 // reset, we must GET TO DA CHOPPA!
2843 PowerManagerService.lowLevelReboot(reason);
2844 } else {
2845 throw new IllegalStateException("Too early to call shutdown() or reboot()");
2846 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002847 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002848
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002849 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002850 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002851 public void run() {
2852 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002853 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002854 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002855 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002856 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002857 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002858 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002859 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002860 }
San Mehat1e512792010-01-07 10:40:29 -08002861 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002862 };
Jeff Brown96307042012-07-27 15:51:34 -07002863
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002864 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00002865 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07002866 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00002867 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002868
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002869 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002870 if (wait) {
2871 synchronized (runnable) {
2872 while (true) {
2873 try {
2874 runnable.wait();
2875 } catch (InterruptedException e) {
2876 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002877 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002878 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002879 }
2880 }
2881
Jeff Brown96307042012-07-27 15:51:34 -07002882 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002883 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002884 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002885 public void run() {
2886 throw new RuntimeException(message);
2887 }
Dan Egnor60d87622009-12-16 16:32:58 -08002888 };
2889 try {
2890 t.start();
2891 t.join();
2892 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002893 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002894 }
2895 }
2896
jackqdyulei92681e82017-02-28 11:26:28 -08002897 @VisibleForTesting
2898 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
2899 PowerSaveState state = mBatterySaverPolicy.
Kweku Adams9f488e22019-01-14 16:25:08 -08002900 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS);
jackqdyulei92681e82017-02-28 11:26:28 -08002901 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
2902 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
2903 }
2904
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002905 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002906 Settings.Global.putInt(mContext.getContentResolver(),
2907 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 }
2909
Pavel Grafov28939982017-10-03 15:11:52 +01002910 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
2911 if (userId < 0) {
2912 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
2913 return;
2914 }
Jeff Brown96307042012-07-27 15:51:34 -07002915 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002916 // System-wide timeout
2917 if (userId == UserHandle.USER_SYSTEM) {
2918 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2919 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
2920 mProfilePowerState.delete(userId);
2921 } else {
2922 final ProfilePowerState profile = mProfilePowerState.get(userId);
2923 if (profile != null) {
2924 profile.mScreenOffTimeout = timeMs;
2925 } else {
2926 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
2927 // We need to recalculate wake locks for the new profile state.
2928 mDirty |= DIRTY_WAKE_LOCKS;
2929 }
2930 }
Jeff Brown96307042012-07-27 15:51:34 -07002931 mDirty |= DIRTY_SETTINGS;
2932 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002933 }
2934 }
2935
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002936 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002937 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002938 if (mDeviceIdleMode == enabled) {
2939 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002940 }
Felipe Lemeea014392016-09-06 13:59:54 -07002941 mDeviceIdleMode = enabled;
2942 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002943 }
Felipe Lemeea014392016-09-06 13:59:54 -07002944 if (enabled) {
2945 EventLogTags.writeDeviceIdleOnPhase("power");
2946 } else {
2947 EventLogTags.writeDeviceIdleOffPhase("power");
2948 }
2949 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002950 }
2951
2952 boolean setLightDeviceIdleModeInternal(boolean enabled) {
2953 synchronized (mLock) {
2954 if (mLightDeviceIdleMode != enabled) {
2955 mLightDeviceIdleMode = enabled;
2956 return true;
2957 }
2958 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002959 }
2960 }
2961
2962 void setDeviceIdleWhitelistInternal(int[] appids) {
2963 synchronized (mLock) {
2964 mDeviceIdleWhitelist = appids;
2965 if (mDeviceIdleMode) {
2966 updateWakeLockDisabledStatesLocked();
2967 }
2968 }
2969 }
2970
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002971 void setDeviceIdleTempWhitelistInternal(int[] appids) {
2972 synchronized (mLock) {
2973 mDeviceIdleTempWhitelist = appids;
2974 if (mDeviceIdleMode) {
2975 updateWakeLockDisabledStatesLocked();
2976 }
2977 }
2978 }
2979
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002980 void startUidChangesInternal() {
2981 synchronized (mLock) {
2982 mUidsChanging = true;
2983 }
2984 }
2985
2986 void finishUidChangesInternal() {
2987 synchronized (mLock) {
2988 mUidsChanging = false;
2989 if (mUidsChanged) {
2990 updateWakeLockDisabledStatesLocked();
2991 mUidsChanged = false;
2992 }
2993 }
2994 }
2995
2996 private void handleUidStateChangeLocked() {
2997 if (mUidsChanging) {
2998 mUidsChanged = true;
2999 } else {
3000 updateWakeLockDisabledStatesLocked();
3001 }
3002 }
3003
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003004 void updateUidProcStateInternal(int uid, int procState) {
3005 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003006 UidState state = mUidState.get(uid);
3007 if (state == null) {
3008 state = new UidState(uid);
3009 mUidState.put(uid, state);
3010 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07003011 final boolean oldShouldAllow = state.mProcState
3012 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003013 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07003014 if (state.mNumWakeLocks > 0) {
3015 if (mDeviceIdleMode) {
3016 handleUidStateChangeLocked();
3017 } else if (!state.mActive && oldShouldAllow !=
3018 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
3019 // If this uid is not active, but the process state has changed such
3020 // that we may still want to allow it to hold a wake lock, then take care of it.
3021 handleUidStateChangeLocked();
3022 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003023 }
3024 }
3025 }
3026
3027 void uidGoneInternal(int uid) {
3028 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003029 final int index = mUidState.indexOfKey(uid);
3030 if (index >= 0) {
3031 UidState state = mUidState.valueAt(index);
3032 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
3033 state.mActive = false;
3034 mUidState.removeAt(index);
3035 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
3036 handleUidStateChangeLocked();
3037 }
3038 }
3039 }
3040 }
3041
3042 void uidActiveInternal(int uid) {
3043 synchronized (mLock) {
3044 UidState state = mUidState.get(uid);
3045 if (state == null) {
3046 state = new UidState(uid);
3047 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
3048 mUidState.put(uid, state);
3049 }
3050 state.mActive = true;
3051 if (state.mNumWakeLocks > 0) {
3052 handleUidStateChangeLocked();
3053 }
3054 }
3055 }
3056
3057 void uidIdleInternal(int uid) {
3058 synchronized (mLock) {
3059 UidState state = mUidState.get(uid);
3060 if (state != null) {
3061 state.mActive = false;
3062 if (state.mNumWakeLocks > 0) {
3063 handleUidStateChangeLocked();
3064 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003065 }
3066 }
3067 }
3068
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003069 private void updateWakeLockDisabledStatesLocked() {
3070 boolean changed = false;
3071 final int numWakeLocks = mWakeLocks.size();
3072 for (int i = 0; i < numWakeLocks; i++) {
3073 final WakeLock wakeLock = mWakeLocks.get(i);
3074 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003075 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003076 if (setWakeLockDisabledStateLocked(wakeLock)) {
3077 changed = true;
3078 if (wakeLock.mDisabled) {
3079 // This wake lock is no longer being respected.
3080 notifyWakeLockReleasedLocked(wakeLock);
3081 } else {
3082 notifyWakeLockAcquiredLocked(wakeLock);
3083 }
3084 }
3085 }
3086 }
3087 if (changed) {
3088 mDirty |= DIRTY_WAKE_LOCKS;
3089 updatePowerStateLocked();
3090 }
3091 }
3092
3093 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
3094 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
3095 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003096 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003097 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
3098 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003099 // Cached inactive processes are never allowed to hold wake locks.
3100 if (mConstants.NO_CACHED_WAKE_LOCKS) {
Santos Cordon12f92eb2019-02-01 21:28:47 +00003101 disabled = mForceSuspendActive
3102 || (!wakeLock.mUidState.mActive && wakeLock.mUidState.mProcState
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003103 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Santos Cordon12f92eb2019-02-01 21:28:47 +00003104 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER);
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003105 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003106 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003107 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003108 // for application uids that are not whitelisted.
3109 final UidState state = wakeLock.mUidState;
3110 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
3111 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
3112 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08003113 state.mProcState >
3114 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003115 disabled = true;
3116 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003117 }
3118 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003119 if (wakeLock.mDisabled != disabled) {
3120 wakeLock.mDisabled = disabled;
3121 return true;
3122 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003123 }
3124 return false;
3125 }
3126
Jeff Brown96307042012-07-27 15:51:34 -07003127 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3128 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003129 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003131
Jeff Brown96307042012-07-27 15:51:34 -07003132 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003133 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003134 synchronized (mLock) {
3135 if (!mSystemReady) {
3136 return;
3137 }
3138 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003139 }
Jeff Brown96307042012-07-27 15:51:34 -07003140
3141 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003142 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003143 }
3144
Lucas Dupin16cfe452018-02-08 13:14:50 -08003145 private void setDozeAfterScreenOffInternal(boolean on) {
3146 synchronized (mLock) {
3147 mDozeAfterScreenOff = on;
3148 }
3149 }
3150
Jeff Browne333e672014-10-28 13:48:55 -07003151 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3152 synchronized (mLock) {
3153 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3154 || eventTime < mLastScreenBrightnessBoostTime) {
3155 return;
3156 }
3157
3158 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3159 mLastScreenBrightnessBoostTime = eventTime;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003160 if (!mScreenBrightnessBoostInProgress) {
3161 mScreenBrightnessBoostInProgress = true;
3162 mNotifier.onScreenBrightnessBoostChanged();
3163 }
Jeff Browne333e672014-10-28 13:48:55 -07003164 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3165
3166 userActivityNoUpdateLocked(eventTime,
3167 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3168 updatePowerStateLocked();
3169 }
3170 }
3171
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003172 private boolean isScreenBrightnessBoostedInternal() {
3173 synchronized (mLock) {
3174 return mScreenBrightnessBoostInProgress;
3175 }
3176 }
3177
Jeff Browne333e672014-10-28 13:48:55 -07003178 /**
3179 * Called when a screen brightness boost timeout has occurred.
3180 *
3181 * This function must have no other side-effects besides setting the dirty
3182 * bit and calling update power state.
3183 */
3184 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3185 synchronized (mLock) {
3186 if (DEBUG_SPEW) {
3187 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3188 }
3189
3190 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3191 updatePowerStateLocked();
3192 }
3193 }
3194
Jeff Brown96307042012-07-27 15:51:34 -07003195 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3196 synchronized (mLock) {
3197 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3198 mScreenBrightnessOverrideFromWindowManager = brightness;
3199 mDirty |= DIRTY_SETTINGS;
3200 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003201 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003202 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003203 }
3204
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003205 private void setUserInactiveOverrideFromWindowManagerInternal() {
3206 synchronized (mLock) {
3207 mUserInactiveOverrideFromWindowManager = true;
3208 mDirty |= DIRTY_USER_ACTIVITY;
3209 updatePowerStateLocked();
3210 }
3211 }
3212
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003213 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3214 synchronized (mLock) {
3215 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3216 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003217 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003218 mDirty |= DIRTY_SETTINGS;
3219 updatePowerStateLocked();
3220 }
3221 }
3222 }
3223
Jeff Brown970d4132014-07-19 11:33:47 -07003224 private void setDozeOverrideFromDreamManagerInternal(
3225 int screenState, int screenBrightness) {
3226 synchronized (mLock) {
3227 if (mDozeScreenStateOverrideFromDreamManager != screenState
3228 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3229 mDozeScreenStateOverrideFromDreamManager = screenState;
3230 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3231 mDirty |= DIRTY_SETTINGS;
3232 updatePowerStateLocked();
3233 }
3234 }
3235 }
3236
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003237 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3238 synchronized (mLock) {
3239 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3240 mDrawWakeLockOverrideFromSidekick = keepState;
3241 mDirty |= DIRTY_SETTINGS;
3242 updatePowerStateLocked();
3243 }
3244 }
3245 }
3246
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003247 @VisibleForTesting
3248 void setVrModeEnabled(boolean enabled) {
3249 mIsVrModeEnabled = enabled;
3250 }
3251
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003252 private void powerHintInternal(int hintId, int data) {
3253 // Maybe filter the event.
3254 switch (hintId) {
3255 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3256 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3257 return;
3258 }
3259 break;
3260 }
3261
Santos Cordon64a6e612018-08-22 19:27:04 +01003262 mNativeWrapper.nativeSendPowerHint(hintId, data);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003263 }
3264
Alex Kershaw2418ea92018-10-19 17:17:49 +01003265 @VisibleForTesting
3266 boolean wasDeviceIdleForInternal(long ms) {
3267 synchronized (mLock) {
3268 return mLastUserActivityTime + ms < SystemClock.uptimeMillis();
3269 }
3270 }
3271
3272 @VisibleForTesting
3273 void onUserActivity() {
3274 synchronized (mLock) {
3275 mLastUserActivityTime = SystemClock.uptimeMillis();
3276 }
3277 }
3278
Santos Cordon12f92eb2019-02-01 21:28:47 +00003279 private boolean forceSuspendInternal(int uid) {
3280 try {
3281 synchronized (mLock) {
3282 mForceSuspendActive = true;
3283 // Place the system in an non-interactive state
3284 goToSleepInternal(SystemClock.uptimeMillis(),
3285 PowerManager.GO_TO_SLEEP_REASON_FORCE_SUSPEND,
3286 PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE, uid);
3287
3288 // Disable all the partial wake locks as well
3289 updateWakeLockDisabledStatesLocked();
3290 }
3291
3292 Slog.i(TAG, "Force-Suspending (uid " + uid + ")...");
3293 boolean success = mNativeWrapper.nativeForceSuspend();
3294 if (!success) {
3295 Slog.i(TAG, "Force-Suspending failed in native.");
3296 }
3297 return success;
3298 } finally {
3299 synchronized (mLock) {
3300 mForceSuspendActive = false;
3301 // Re-enable wake locks once again.
3302 updateWakeLockDisabledStatesLocked();
3303 }
3304 }
3305 }
3306
Jeff Brown96307042012-07-27 15:51:34 -07003307 /**
3308 * Low-level function turn the device off immediately, without trying
3309 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003310 *
3311 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003312 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003313 public static void lowLevelShutdown(String reason) {
3314 if (reason == null) {
3315 reason = "";
3316 }
3317 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003318 }
3319
3320 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003321 * Low-level function to reboot the device. On success, this
3322 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003323 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003324 *
3325 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003326 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003327 public static void lowLevelReboot(String reason) {
3328 if (reason == null) {
3329 reason = "";
3330 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003331
3332 // If the reason is "quiescent", it means that the boot process should proceed
3333 // without turning on the screen/lights.
3334 // The "quiescent" property is sticky, meaning that any number
3335 // of subsequent reboots should honor the property until it is reset.
3336 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3337 sQuiescent = true;
3338 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003339 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3340 sQuiescent = true;
3341 reason = reason.substring(0,
3342 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3343 }
3344
3345 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3346 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3347 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003348 }
3349
3350 if (sQuiescent) {
3351 // Pass the optional "quiescent" argument to the bootloader to let it know
3352 // that it should not turn the screen/lights on.
3353 reason = reason + ",quiescent";
3354 }
3355
3356 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003357 try {
Tao Bao90237f72015-05-21 16:25:19 -07003358 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003359 } catch (InterruptedException e) {
3360 Thread.currentThread().interrupt();
3361 }
Tao Bao90237f72015-05-21 16:25:19 -07003362 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003363 }
3364
3365 @Override // Watchdog.Monitor implementation
3366 public void monitor() {
3367 // Grab and release lock for watchdog monitor to detect deadlocks.
3368 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003369 }
Jeff Brown96307042012-07-27 15:51:34 -07003370 }
3371
Jeff Brown6f357d32014-01-15 20:40:55 -08003372 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003373 pw.println("POWER MANAGER (dumpsys power)\n");
3374
Jeff Brown3b971592013-01-09 18:46:37 -08003375 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003376 synchronized (mLock) {
3377 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003378 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003379 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003380 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3381 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003382 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003383 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003384 pw.println(" mBatteryLevel=" + mBatteryLevel);
3385 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003386 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003387 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003388 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003389 pw.println(" mBootCompleted=" + mBootCompleted);
3390 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003391 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3392 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003393 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003394 pw.print(" mNotifyLongScheduled=");
3395 if (mNotifyLongScheduled == 0) {
3396 pw.print("(none)");
3397 } else {
3398 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3399 }
3400 pw.println();
3401 pw.print(" mNotifyLongDispatched=");
3402 if (mNotifyLongDispatched == 0) {
3403 pw.print("(none)");
3404 } else {
3405 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3406 }
3407 pw.println();
3408 pw.print(" mNotifyLongNextCheck=");
3409 if (mNotifyLongNextCheck == 0) {
3410 pw.print("(none)");
3411 } else {
3412 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3413 }
3414 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003415 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3416 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3417 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003418 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003419 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003420 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003421 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3422 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003423 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003424 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3425 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Calin Tatarua3805722018-08-09 16:41:28 +02003426 pw.println(" mLastSleepReason=" + PowerManager.sleepReasonToString(mLastSleepReason));
Jeff Brown96307042012-07-27 15:51:34 -07003427 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3428 pw.println(" mLastUserActivityTimeNoChangeLights="
3429 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003430 pw.println(" mLastInteractivePowerHintTime="
3431 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003432 pw.println(" mLastScreenBrightnessBoostTime="
3433 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3434 pw.println(" mScreenBrightnessBoostInProgress="
3435 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003436 pw.println(" mDisplayReady=" + mDisplayReady);
3437 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003438 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003439
3440 pw.println();
3441 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003442 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3443 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3444 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3445 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003446 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3447 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003448 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3449 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3450 pw.println(" mTheaterModeEnabled="
3451 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003452 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3453 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003454 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003455 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3456 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3457 + mDreamsActivatedOnSleepByDefaultConfig);
3458 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3459 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003460 pw.println(" mDreamsEnabledOnBatteryConfig="
3461 + mDreamsEnabledOnBatteryConfig);
3462 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3463 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3464 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3465 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3466 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3467 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003468 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003469 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003470 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003471 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003472 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3473 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3474 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003475 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003476 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003477 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3478 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3479 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3480 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3481 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3482 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3483 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3484 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003485 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3486 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003487 pw.println(" mUserInactiveOverrideFromWindowManager="
3488 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003489 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3490 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003491 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003492 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3493 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003494 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3495 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3496 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003497 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003498 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003499 pw.println(" mForegroundProfile=" + mForegroundProfile);
Jeff Brown96307042012-07-27 15:51:34 -07003500
Pavel Grafov28939982017-10-03 15:11:52 +01003501 final long sleepTimeout = getSleepTimeoutLocked();
3502 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3503 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003504 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07003505 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003506 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3507 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3508
Jeff Brown96307042012-07-27 15:51:34 -07003509 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003510 pw.print("UID states (changing=");
3511 pw.print(mUidsChanging);
3512 pw.print(" changed=");
3513 pw.print(mUidsChanged);
3514 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003515 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003516 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003517 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003518 pw.print(": ");
3519 if (state.mActive) pw.print(" ACTIVE ");
3520 else pw.print("INACTIVE ");
3521 pw.print(" count=");
3522 pw.print(state.mNumWakeLocks);
3523 pw.print(" state=");
3524 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003525 }
3526
3527 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003528 pw.println("Looper state:");
3529 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3530
3531 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003532 pw.println("Wake Locks: size=" + mWakeLocks.size());
3533 for (WakeLock wl : mWakeLocks) {
3534 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003535 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003536
Jeff Brown96307042012-07-27 15:51:34 -07003537 pw.println();
3538 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3539 for (SuspendBlocker sb : mSuspendBlockers) {
3540 pw.println(" " + sb);
3541 }
3542
Jeff Brownc38c9be2012-10-04 13:16:19 -07003543 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003544 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003545
jackqdyulei455e90a2017-02-09 15:29:16 -08003546 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003547 mBatterySaverStateMachine.dump(pw);
Lucas Dupin0a5d7972019-01-16 18:52:30 -08003548 mAttentionDetector.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003549
Pavel Grafov28939982017-10-03 15:11:52 +01003550 pw.println();
3551 final int numProfiles = mProfilePowerState.size();
3552 pw.println("Profile power states: size=" + numProfiles);
3553 for (int i = 0; i < numProfiles; i++) {
3554 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3555 pw.print(" mUserId=");
3556 pw.print(profile.mUserId);
3557 pw.print(" mScreenOffTimeout=");
3558 pw.print(profile.mScreenOffTimeout);
3559 pw.print(" mWakeLockSummary=");
3560 pw.print(profile.mWakeLockSummary);
3561 pw.print(" mLastUserActivityTime=");
3562 pw.print(profile.mLastUserActivityTime);
3563 pw.print(" mLockingNotified=");
3564 pw.println(profile.mLockingNotified);
3565 }
3566
Jeff Brown3b971592013-01-09 18:46:37 -08003567 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003568 }
3569
Jeff Brown3b971592013-01-09 18:46:37 -08003570 if (wcd != null) {
3571 wcd.dump(pw);
3572 }
Jeff Brown96307042012-07-27 15:51:34 -07003573 }
3574
Netta P958d0a52017-02-07 11:20:55 -08003575 private void dumpProto(FileDescriptor fd) {
3576 final WirelessChargerDetector wcd;
3577 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3578
3579 synchronized (mLock) {
3580 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003581 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3582 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3583 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3584 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3585 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3586 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003587 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003588 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003589 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003590 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3591 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3592 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3593 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3594 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003595 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003596 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003597 mHalAutoSuspendModeEnabled);
3598 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003599 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003600 mHalInteractiveModeEnabled);
3601
Kweku Adamse6b00c22017-10-23 16:46:45 -07003602 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003603 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003604 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003605 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3606 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003607 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003608 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3609 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003610 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003611 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3612 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003613 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003614 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3615 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003616 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003617 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3618 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003619 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003620 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3621 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003622 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003623 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3624 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003625 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003626 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3627 proto.end(activeWakeLocksToken);
3628
Kweku Adamse6b00c22017-10-23 16:46:45 -07003629 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3630 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3631 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003632
Kweku Adamse6b00c22017-10-23 16:46:45 -07003633 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003634 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003635 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003636 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3637 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003638 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003639 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3640 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003641 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003642 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3643 proto.end(userActivityToken);
3644
3645 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003646 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003647 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003648 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3649 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003650 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3651 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3652 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003653
3654 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003655 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003656 }
3657 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003658 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003659 }
3660
Kweku Adamse6b00c22017-10-23 16:46:45 -07003661 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3662 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3663 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003664 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003665 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003666 mLastUserActivityTimeNoChangeLights);
3667 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003668 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003669 mLastInteractivePowerHintTime);
3670 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003671 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003672 mLastScreenBrightnessBoostTime);
3673 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003674 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003675 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003676 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003677 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003678 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003679 mHoldingWakeLockSuspendBlocker);
3680 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003681 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003682 mHoldingDisplaySuspendBlocker);
3683
3684 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003685 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003686 proto.write(
3687 PowerServiceSettingsAndConfigurationDumpProto
3688 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3689 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3690 proto.write(
3691 PowerServiceSettingsAndConfigurationDumpProto
3692 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3693 mDecoupleHalInteractiveModeFromDisplayConfig);
3694 proto.write(
3695 PowerServiceSettingsAndConfigurationDumpProto
3696 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3697 mWakeUpWhenPluggedOrUnpluggedConfig);
3698 proto.write(
3699 PowerServiceSettingsAndConfigurationDumpProto
3700 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3701 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3702 proto.write(
3703 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3704 mTheaterModeEnabled);
3705 proto.write(
3706 PowerServiceSettingsAndConfigurationDumpProto
3707 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3708 mSuspendWhenScreenOffDueToProximityConfig);
3709 proto.write(
3710 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3711 mDreamsSupportedConfig);
3712 proto.write(
3713 PowerServiceSettingsAndConfigurationDumpProto
3714 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3715 mDreamsEnabledByDefaultConfig);
3716 proto.write(
3717 PowerServiceSettingsAndConfigurationDumpProto
3718 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3719 mDreamsActivatedOnSleepByDefaultConfig);
3720 proto.write(
3721 PowerServiceSettingsAndConfigurationDumpProto
3722 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3723 mDreamsActivatedOnDockByDefaultConfig);
3724 proto.write(
3725 PowerServiceSettingsAndConfigurationDumpProto
3726 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3727 mDreamsEnabledOnBatteryConfig);
3728 proto.write(
3729 PowerServiceSettingsAndConfigurationDumpProto
3730 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3731 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3732 proto.write(
3733 PowerServiceSettingsAndConfigurationDumpProto
3734 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3735 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3736 proto.write(
3737 PowerServiceSettingsAndConfigurationDumpProto
3738 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3739 mDreamsBatteryLevelDrainCutoffConfig);
3740 proto.write(
3741 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3742 mDreamsEnabledSetting);
3743 proto.write(
3744 PowerServiceSettingsAndConfigurationDumpProto
3745 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3746 mDreamsActivateOnSleepSetting);
3747 proto.write(
3748 PowerServiceSettingsAndConfigurationDumpProto
3749 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3750 mDreamsActivateOnDockSetting);
3751 proto.write(
3752 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08003753 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08003754 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003755 PowerServiceSettingsAndConfigurationDumpProto
3756 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3757 mMinimumScreenOffTimeoutConfig);
3758 proto.write(
3759 PowerServiceSettingsAndConfigurationDumpProto
3760 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3761 mMaximumScreenDimDurationConfig);
3762 proto.write(
3763 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3764 mMaximumScreenDimRatioConfig);
3765 proto.write(
3766 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3767 mScreenOffTimeoutSetting);
3768 proto.write(
3769 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3770 mSleepTimeoutSetting);
3771 proto.write(
3772 PowerServiceSettingsAndConfigurationDumpProto
3773 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003774 // Clamp to int32
3775 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003776 proto.write(
3777 PowerServiceSettingsAndConfigurationDumpProto
3778 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3779 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3780
3781 final long stayOnWhilePluggedInToken =
3782 proto.start(
3783 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3784 proto.write(
3785 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3786 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3787 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3788 proto.write(
3789 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3790 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3791 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3792 proto.write(
3793 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3794 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3795 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3796 != 0));
3797 proto.end(stayOnWhilePluggedInToken);
3798
3799 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003800 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3801 mScreenBrightnessModeSetting);
3802 proto.write(
3803 PowerServiceSettingsAndConfigurationDumpProto
3804 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3805 mScreenBrightnessOverrideFromWindowManager);
3806 proto.write(
3807 PowerServiceSettingsAndConfigurationDumpProto
3808 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3809 mUserActivityTimeoutOverrideFromWindowManager);
3810 proto.write(
3811 PowerServiceSettingsAndConfigurationDumpProto
3812 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
3813 mUserInactiveOverrideFromWindowManager);
3814 proto.write(
3815 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003816 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
3817 mDozeScreenStateOverrideFromDreamManager);
3818 proto.write(
3819 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003820 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
3821 mDrawWakeLockOverrideFromSidekick);
3822 proto.write(
3823 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003824 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
3825 mDozeScreenBrightnessOverrideFromDreamManager);
3826
3827 final long screenBrightnessSettingLimitsToken =
3828 proto.start(
3829 PowerServiceSettingsAndConfigurationDumpProto
3830 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
3831 proto.write(
3832 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3833 .SETTING_MINIMUM,
3834 mScreenBrightnessSettingMinimum);
3835 proto.write(
3836 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3837 .SETTING_MAXIMUM,
3838 mScreenBrightnessSettingMaximum);
3839 proto.write(
3840 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3841 .SETTING_DEFAULT,
3842 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08003843 proto.end(screenBrightnessSettingLimitsToken);
3844
3845 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003846 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
3847 mDoubleTapWakeEnabled);
3848 proto.write(
3849 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
3850 mIsVrModeEnabled);
3851 proto.end(settingsAndConfigurationToken);
3852
Pavel Grafov28939982017-10-03 15:11:52 +01003853 final long sleepTimeout = getSleepTimeoutLocked();
3854 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3855 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003856 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
3857 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
3858 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
3859 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
3860 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08003861
3862 for (int i = 0; i < mUidState.size(); i++) {
3863 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003864 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08003865 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003866 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
3867 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
3868 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
3869 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08003870 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
3871 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08003872 proto.end(uIDToken);
3873 }
3874
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003875 mBatterySaverStateMachine.dumpProto(proto,
3876 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
3877
Kweku Adamse6b00c22017-10-23 16:46:45 -07003878 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08003879
3880 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003881 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003882 }
3883
3884 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003885 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08003886 }
3887 wcd = mWirelessChargerDetector;
3888 }
3889
3890 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003891 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08003892 }
3893 proto.flush();
3894 }
3895
Daichi Hirono82ab9802016-03-02 13:23:29 +09003896 private void incrementBootCount() {
3897 synchronized (mLock) {
3898 int count;
3899 try {
3900 count = Settings.Global.getInt(
3901 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3902 } catch (SettingNotFoundException e) {
3903 count = 0;
3904 }
3905 Settings.Global.putInt(
3906 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3907 }
3908 }
3909
Jeff Brown96307042012-07-27 15:51:34 -07003910 private static WorkSource copyWorkSource(WorkSource workSource) {
3911 return workSource != null ? new WorkSource(workSource) : null;
3912 }
3913
Santos Cordon9b510a22018-08-24 16:42:54 +01003914 @VisibleForTesting
3915 final class BatteryReceiver extends BroadcastReceiver {
Jeff Brown96307042012-07-27 15:51:34 -07003916 @Override
3917 public void onReceive(Context context, Intent intent) {
3918 synchronized (mLock) {
3919 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003920 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003921 }
3922 }
3923
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003924 private final class DreamReceiver extends BroadcastReceiver {
3925 @Override
3926 public void onReceive(Context context, Intent intent) {
3927 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07003928 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003929 }
3930 }
3931 }
3932
Santos Cordon9b510a22018-08-24 16:42:54 +01003933 @VisibleForTesting
3934 final class UserSwitchedReceiver extends BroadcastReceiver {
Jeff Brownd4935962012-09-25 13:27:20 -07003935 @Override
3936 public void onReceive(Context context, Intent intent) {
3937 synchronized (mLock) {
3938 handleSettingsChangedLocked();
3939 }
3940 }
3941 }
3942
Jeff Brownec6aa592012-10-17 20:30:25 -07003943 private final class DockReceiver extends BroadcastReceiver {
3944 @Override
3945 public void onReceive(Context context, Intent intent) {
3946 synchronized (mLock) {
3947 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3948 Intent.EXTRA_DOCK_STATE_UNDOCKED);
3949 if (mDockState != dockState) {
3950 mDockState = dockState;
3951 mDirty |= DIRTY_DOCK_STATE;
3952 updatePowerStateLocked();
3953 }
3954 }
3955 }
3956 }
3957
Jeff Brown96307042012-07-27 15:51:34 -07003958 private final class SettingsObserver extends ContentObserver {
3959 public SettingsObserver(Handler handler) {
3960 super(handler);
3961 }
3962
3963 @Override
3964 public void onChange(boolean selfChange, Uri uri) {
3965 synchronized (mLock) {
3966 handleSettingsChangedLocked();
3967 }
3968 }
3969 }
3970
Ruben Brunkc7be3be2016-04-01 17:07:51 -07003971 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003972 @Override
3973 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07003974 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07003975
3976 synchronized (mLock) {
3977 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003978 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003979 mDirty |= DIRTY_VR_MODE_CHANGED;
3980 updatePowerStateLocked();
3981 }
3982 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003983 }
3984 };
3985
Jeff Brown96307042012-07-27 15:51:34 -07003986 /**
3987 * Handler for asynchronous operations performed by the power manager.
3988 */
3989 private final class PowerManagerHandler extends Handler {
3990 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07003991 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07003992 }
3993
3994 @Override
3995 public void handleMessage(Message msg) {
3996 switch (msg.what) {
3997 case MSG_USER_ACTIVITY_TIMEOUT:
3998 handleUserActivityTimeout();
3999 break;
4000 case MSG_SANDMAN:
4001 handleSandman();
4002 break;
Jeff Browne333e672014-10-28 13:48:55 -07004003 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
4004 handleScreenBrightnessBoostTimeout();
4005 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004006 case MSG_CHECK_FOR_LONG_WAKELOCKS:
4007 checkForLongWakeLocks();
4008 break;
Jeff Brown96307042012-07-27 15:51:34 -07004009 }
4010 }
4011 }
4012
4013 /**
4014 * Represents a wake lock that has been acquired by an application.
4015 */
4016 private final class WakeLock implements IBinder.DeathRecipient {
4017 public final IBinder mLock;
4018 public int mFlags;
4019 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004020 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07004021 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004022 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004023 public final int mOwnerUid;
4024 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004025 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004026 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07004027 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004028 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004029 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07004030
Dianne Hackborn713df152013-05-17 11:27:57 -07004031 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004032 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
4033 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07004034 mLock = lock;
4035 mFlags = flags;
4036 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07004037 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07004038 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004039 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004040 mOwnerUid = ownerUid;
4041 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004042 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07004043 }
4044
4045 @Override
4046 public void binderDied() {
4047 PowerManagerService.this.handleWakeLockDeath(this);
4048 }
4049
4050 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
4051 int ownerUid, int ownerPid) {
4052 return mFlags == flags
4053 && mTag.equals(tag)
4054 && hasSameWorkSource(workSource)
4055 && mOwnerUid == ownerUid
4056 && mOwnerPid == ownerPid;
4057 }
4058
Dianne Hackborn713df152013-05-17 11:27:57 -07004059 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004060 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07004061 if (!mPackageName.equals(packageName)) {
4062 throw new IllegalStateException("Existing wake lock package name changed: "
4063 + mPackageName + " to " + packageName);
4064 }
4065 if (mOwnerUid != ownerUid) {
4066 throw new IllegalStateException("Existing wake lock uid changed: "
4067 + mOwnerUid + " to " + ownerUid);
4068 }
4069 if (mOwnerPid != ownerPid) {
4070 throw new IllegalStateException("Existing wake lock pid changed: "
4071 + mOwnerPid + " to " + ownerPid);
4072 }
Jeff Brown96307042012-07-27 15:51:34 -07004073 mFlags = flags;
4074 mTag = tag;
4075 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004076 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07004077 }
4078
4079 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00004080 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07004081 }
4082
4083 public void updateWorkSource(WorkSource workSource) {
4084 mWorkSource = copyWorkSource(workSource);
4085 }
4086
4087 @Override
4088 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07004089 StringBuilder sb = new StringBuilder();
4090 sb.append(getLockLevelString());
4091 sb.append(" '");
4092 sb.append(mTag);
4093 sb.append("'");
4094 sb.append(getLockFlagsString());
4095 if (mDisabled) {
4096 sb.append(" DISABLED");
4097 }
4098 if (mNotifiedAcquired) {
4099 sb.append(" ACQ=");
4100 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
4101 }
4102 if (mNotifiedLong) {
4103 sb.append(" LONG");
4104 }
4105 sb.append(" (uid=");
4106 sb.append(mOwnerUid);
4107 if (mOwnerPid != 0) {
4108 sb.append(" pid=");
4109 sb.append(mOwnerPid);
4110 }
4111 if (mWorkSource != null) {
4112 sb.append(" ws=");
4113 sb.append(mWorkSource);
4114 }
4115 sb.append(")");
4116 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07004117 }
4118
Netta P958d0a52017-02-07 11:20:55 -08004119 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4120 final long wakeLockToken = proto.start(fieldId);
4121 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
4122 proto.write(WakeLockProto.TAG, mTag);
4123
4124 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
4125 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
4126 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
4127 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
4128 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
4129 proto.end(wakeLockFlagsToken);
4130
4131 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
4132 if (mNotifiedAcquired) {
4133 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
4134 }
4135 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
4136 proto.write(WakeLockProto.UID, mOwnerUid);
4137 proto.write(WakeLockProto.PID, mOwnerPid);
4138
4139 if (mWorkSource != null) {
4140 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
4141 }
4142 proto.end(wakeLockToken);
4143 }
4144
Jeff Brown26875502014-01-30 21:47:47 -08004145 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07004146 private String getLockLevelString() {
4147 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
4148 case PowerManager.FULL_WAKE_LOCK:
4149 return "FULL_WAKE_LOCK ";
4150 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
4151 return "SCREEN_BRIGHT_WAKE_LOCK ";
4152 case PowerManager.SCREEN_DIM_WAKE_LOCK:
4153 return "SCREEN_DIM_WAKE_LOCK ";
4154 case PowerManager.PARTIAL_WAKE_LOCK:
4155 return "PARTIAL_WAKE_LOCK ";
4156 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4157 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004158 case PowerManager.DOZE_WAKE_LOCK:
4159 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004160 case PowerManager.DRAW_WAKE_LOCK:
4161 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004162 default:
4163 return "??? ";
4164 }
4165 }
4166
4167 private String getLockFlagsString() {
4168 String result = "";
4169 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4170 result += " ACQUIRE_CAUSES_WAKEUP";
4171 }
4172 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4173 result += " ON_AFTER_RELEASE";
4174 }
4175 return result;
4176 }
4177 }
4178
4179 private final class SuspendBlockerImpl implements SuspendBlocker {
4180 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004181 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004182 private int mReferenceCount;
4183
4184 public SuspendBlockerImpl(String name) {
4185 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004186 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004187 }
4188
4189 @Override
4190 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004191 try {
Jeff Brown96307042012-07-27 15:51:34 -07004192 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004193 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004194 + "\" was finalized without being released!");
4195 mReferenceCount = 0;
Santos Cordon64a6e612018-08-22 19:27:04 +01004196 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004197 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004198 }
4199 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004200 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004201 }
4202 }
4203
Craig Mautner75fc9de2012-06-18 16:53:27 -07004204 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004205 public void acquire() {
4206 synchronized (this) {
4207 mReferenceCount += 1;
4208 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004209 if (DEBUG_SPEW) {
4210 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4211 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004212 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Santos Cordon64a6e612018-08-22 19:27:04 +01004213 mNativeWrapper.nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004214 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004215 }
4216 }
4217
Craig Mautner75fc9de2012-06-18 16:53:27 -07004218 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004219 public void release() {
4220 synchronized (this) {
4221 mReferenceCount -= 1;
4222 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004223 if (DEBUG_SPEW) {
4224 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4225 }
Santos Cordon64a6e612018-08-22 19:27:04 +01004226 mNativeWrapper.nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004227 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004228 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004229 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004230 + "\" was released without being acquired!", new Throwable());
4231 mReferenceCount = 0;
4232 }
4233 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004234 }
Jeff Brown96307042012-07-27 15:51:34 -07004235
4236 @Override
4237 public String toString() {
4238 synchronized (this) {
4239 return mName + ": ref count=" + mReferenceCount;
4240 }
4241 }
Netta P958d0a52017-02-07 11:20:55 -08004242
4243 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4244 final long sbToken = proto.start(fieldId);
4245 synchronized (this) {
4246 proto.write(SuspendBlockerProto.NAME, mName);
4247 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4248 }
4249 proto.end(sbToken);
4250 }
Jeff Brown96307042012-07-27 15:51:34 -07004251 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004252
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004253 static final class UidState {
4254 final int mUid;
4255 int mNumWakeLocks;
4256 int mProcState;
4257 boolean mActive;
4258
4259 UidState(int uid) {
4260 mUid = uid;
4261 }
4262 }
4263
Santos Cordon64a6e612018-08-22 19:27:04 +01004264 @VisibleForTesting
4265 final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004266 @Override
4267 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4268 FileDescriptor err, String[] args, ShellCallback callback,
4269 ResultReceiver resultReceiver) {
4270 (new PowerManagerShellCommand(this)).exec(
4271 this, in, out, err, args, callback, resultReceiver);
4272 }
4273
Jeff Brown6f357d32014-01-15 20:40:55 -08004274 @Override // Binder call
4275 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4276 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004277 if (uid < 0) {
4278 uid = Binder.getCallingUid();
4279 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004280 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004281 }
4282
4283 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004284 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004285 if (!mSystemReady) {
4286 // Service not ready yet, so who the heck cares about power hints, bah.
4287 return;
4288 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004289 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004290 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004291 }
4292
4293 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004294 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004295 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004296 if (lock == null) {
4297 throw new IllegalArgumentException("lock must not be null");
4298 }
4299 if (packageName == null) {
4300 throw new IllegalArgumentException("packageName must not be null");
4301 }
4302 PowerManager.validateWakeLockParameters(flags, tag);
4303
4304 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004305 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4306 mContext.enforceCallingOrSelfPermission(
4307 android.Manifest.permission.DEVICE_POWER, null);
4308 }
Narayan Kamath81822022017-12-08 11:56:01 +00004309 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004310 mContext.enforceCallingOrSelfPermission(
4311 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4312 } else {
4313 ws = null;
4314 }
4315
4316 final int uid = Binder.getCallingUid();
4317 final int pid = Binder.getCallingPid();
4318 final long ident = Binder.clearCallingIdentity();
4319 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004320 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004321 } finally {
4322 Binder.restoreCallingIdentity(ident);
4323 }
4324 }
4325
4326 @Override // Binder call
4327 public void releaseWakeLock(IBinder lock, int flags) {
4328 if (lock == null) {
4329 throw new IllegalArgumentException("lock must not be null");
4330 }
4331
4332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4333
4334 final long ident = Binder.clearCallingIdentity();
4335 try {
4336 releaseWakeLockInternal(lock, flags);
4337 } finally {
4338 Binder.restoreCallingIdentity(ident);
4339 }
4340 }
4341
4342 @Override // Binder call
4343 public void updateWakeLockUids(IBinder lock, int[] uids) {
4344 WorkSource ws = null;
4345
4346 if (uids != null) {
4347 ws = new WorkSource();
4348 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4349 // one at a time?
4350 for (int i = 0; i < uids.length; i++) {
4351 ws.add(uids[i]);
4352 }
4353 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004354 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004355 }
4356
4357 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004358 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004359 if (lock == null) {
4360 throw new IllegalArgumentException("lock must not be null");
4361 }
4362
4363 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004364 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004365 mContext.enforceCallingOrSelfPermission(
4366 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4367 } else {
4368 ws = null;
4369 }
4370
Dianne Hackbornd953c532014-08-16 18:17:38 -07004371 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004372 final long ident = Binder.clearCallingIdentity();
4373 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004374 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004375 } finally {
4376 Binder.restoreCallingIdentity(ident);
4377 }
4378 }
4379
4380 @Override // Binder call
4381 public boolean isWakeLockLevelSupported(int level) {
4382 final long ident = Binder.clearCallingIdentity();
4383 try {
4384 return isWakeLockLevelSupportedInternal(level);
4385 } finally {
4386 Binder.restoreCallingIdentity(ident);
4387 }
4388 }
4389
4390 @Override // Binder call
4391 public void userActivity(long eventTime, int event, int flags) {
4392 final long now = SystemClock.uptimeMillis();
4393 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004394 != PackageManager.PERMISSION_GRANTED
4395 && mContext.checkCallingOrSelfPermission(
4396 android.Manifest.permission.USER_ACTIVITY)
4397 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004398 // Once upon a time applications could call userActivity().
4399 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4400 // request instead of throwing a SecurityException so we don't break old apps.
4401 synchronized (mLock) {
4402 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4403 mLastWarningAboutUserActivityPermission = now;
4404 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004405 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4406 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004407 + " pid=" + Binder.getCallingPid()
4408 + " uid=" + Binder.getCallingUid());
4409 }
4410 }
4411 return;
4412 }
4413
Jim Millerdca15d22015-06-16 20:55:13 -07004414 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004415 throw new IllegalArgumentException("event time must not be in the future");
4416 }
4417
4418 final int uid = Binder.getCallingUid();
4419 final long ident = Binder.clearCallingIdentity();
4420 try {
4421 userActivityInternal(eventTime, event, flags, uid);
4422 } finally {
4423 Binder.restoreCallingIdentity(ident);
4424 }
4425 }
4426
4427 @Override // Binder call
Michael Wrighte3001042019-02-05 00:13:14 +00004428 public void wakeUp(long eventTime, @WakeReason int reason, String details,
4429 String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004430 if (eventTime > SystemClock.uptimeMillis()) {
4431 throw new IllegalArgumentException("event time must not be in the future");
4432 }
4433
4434 mContext.enforceCallingOrSelfPermission(
4435 android.Manifest.permission.DEVICE_POWER, null);
4436
Jeff Brownc12035c2014-08-13 18:52:25 -07004437 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004438 final long ident = Binder.clearCallingIdentity();
4439 try {
Michael Wrighte3001042019-02-05 00:13:14 +00004440 wakeUpInternal(eventTime, reason, details, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004441 } finally {
4442 Binder.restoreCallingIdentity(ident);
4443 }
4444 }
4445
4446 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004447 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004448 if (eventTime > SystemClock.uptimeMillis()) {
4449 throw new IllegalArgumentException("event time must not be in the future");
4450 }
4451
4452 mContext.enforceCallingOrSelfPermission(
4453 android.Manifest.permission.DEVICE_POWER, null);
4454
Jeff Brownc12035c2014-08-13 18:52:25 -07004455 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004456 final long ident = Binder.clearCallingIdentity();
4457 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004458 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004459 } finally {
4460 Binder.restoreCallingIdentity(ident);
4461 }
4462 }
4463
4464 @Override // Binder call
4465 public void nap(long eventTime) {
4466 if (eventTime > SystemClock.uptimeMillis()) {
4467 throw new IllegalArgumentException("event time must not be in the future");
4468 }
4469
4470 mContext.enforceCallingOrSelfPermission(
4471 android.Manifest.permission.DEVICE_POWER, null);
4472
Jeff Brownc12035c2014-08-13 18:52:25 -07004473 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004474 final long ident = Binder.clearCallingIdentity();
4475 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004476 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004477 } finally {
4478 Binder.restoreCallingIdentity(ident);
4479 }
4480 }
4481
4482 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004483 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004484 final long ident = Binder.clearCallingIdentity();
4485 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004486 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004487 } finally {
4488 Binder.restoreCallingIdentity(ident);
4489 }
4490 }
4491
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004492 @Override // Binder call
4493 public boolean isPowerSaveMode() {
4494 final long ident = Binder.clearCallingIdentity();
4495 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004496 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004497 } finally {
4498 Binder.restoreCallingIdentity(ident);
4499 }
4500 }
4501
jackqdyulei455e90a2017-02-09 15:29:16 -08004502 // Binder call
4503 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4504 final long ident = Binder.clearCallingIdentity();
4505 try {
Kweku Adams9f488e22019-01-14 16:25:08 -08004506 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
jackqdyulei455e90a2017-02-09 15:29:16 -08004507 } finally {
4508 Binder.restoreCallingIdentity(ident);
4509 }
4510 }
4511
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004512 @Override // Binder call
Salvador Martinezc8c4c5d2019-03-11 11:11:37 -07004513 public boolean setPowerSaveModeEnabled(boolean enabled) {
Salvador Martineza80bbab2018-09-24 10:36:11 -07004514 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4515 != PackageManager.PERMISSION_GRANTED) {
4516 mContext.enforceCallingOrSelfPermission(
4517 android.Manifest.permission.DEVICE_POWER, null);
4518 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004519 final long ident = Binder.clearCallingIdentity();
4520 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004521 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004522 } finally {
4523 Binder.restoreCallingIdentity(ident);
4524 }
4525 }
4526
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004527 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004528 public boolean setDynamicPowerSaveHint(boolean powerSaveHint, int disableThreshold) {
Salvador Martinez812ea752018-10-19 13:03:20 -07004529 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER,
4530 "updateDynamicPowerSavings");
4531 final long ident = Binder.clearCallingIdentity();
4532 try {
4533 final ContentResolver resolver = mContext.getContentResolver();
4534 boolean success = Settings.Global.putInt(resolver,
4535 Settings.Global.DYNAMIC_POWER_SAVINGS_DISABLE_THRESHOLD,
4536 disableThreshold);
4537 if (success) {
4538 // abort updating if we weren't able to succeed on the threshold
4539 success &= Settings.Global.putInt(resolver,
4540 Settings.Global.DYNAMIC_POWER_SAVINGS_ENABLED,
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004541 powerSaveHint ? 1 : 0);
Salvador Martinez812ea752018-10-19 13:03:20 -07004542 }
4543 return success;
4544 } finally {
4545 Binder.restoreCallingIdentity(ident);
4546 }
4547 }
4548
4549 @Override // Binder call
Kweku Adams9f488e22019-01-14 16:25:08 -08004550 public boolean setAdaptivePowerSavePolicy(@NonNull BatterySaverPolicyConfig config) {
4551 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4552 != PackageManager.PERMISSION_GRANTED) {
4553 mContext.enforceCallingOrSelfPermission(
4554 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSavePolicy");
4555 }
4556 final long ident = Binder.clearCallingIdentity();
4557 try {
4558 return mBatterySaverStateMachine.setAdaptiveBatterySaverPolicy(config);
4559 } finally {
4560 Binder.restoreCallingIdentity(ident);
4561 }
4562 }
4563
4564 @Override // Binder call
4565 public boolean setAdaptivePowerSaveEnabled(boolean enabled) {
4566 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER)
4567 != PackageManager.PERMISSION_GRANTED) {
4568 mContext.enforceCallingOrSelfPermission(
4569 android.Manifest.permission.DEVICE_POWER, "setAdaptivePowerSaveEnabled");
4570 }
4571 final long ident = Binder.clearCallingIdentity();
4572 try {
4573 return mBatterySaverStateMachine.setAdaptiveBatterySaverEnabled(enabled);
4574 } finally {
4575 Binder.restoreCallingIdentity(ident);
4576 }
4577 }
4578
4579 @Override // Binder call
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004580 public int getPowerSaveModeTrigger() {
Salvador Martinez812ea752018-10-19 13:03:20 -07004581 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.POWER_SAVER, null);
4582 final long ident = Binder.clearCallingIdentity();
4583 try {
4584 return Settings.Global.getInt(mContext.getContentResolver(),
Salvador Martinezb85a9f82019-03-20 16:21:27 -07004585 Settings.Global.AUTOMATIC_POWER_SAVE_MODE,
4586 PowerManager.POWER_SAVE_MODE_TRIGGER_PERCENTAGE);
Salvador Martinez812ea752018-10-19 13:03:20 -07004587 } finally {
4588 Binder.restoreCallingIdentity(ident);
4589 }
4590 }
4591
4592 @Override // Binder call
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004593 public boolean isDeviceIdleMode() {
4594 final long ident = Binder.clearCallingIdentity();
4595 try {
4596 return isDeviceIdleModeInternal();
4597 } finally {
4598 Binder.restoreCallingIdentity(ident);
4599 }
4600 }
4601
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004602 @Override // Binder call
4603 public boolean isLightDeviceIdleMode() {
4604 final long ident = Binder.clearCallingIdentity();
4605 try {
4606 return isLightDeviceIdleModeInternal();
4607 } finally {
4608 Binder.restoreCallingIdentity(ident);
4609 }
4610 }
4611
Jeff Brown6f357d32014-01-15 20:40:55 -08004612 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004613 * Gets the reason for the last time the phone had to reboot.
4614 *
4615 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004616 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004617 */
4618 @Override // Binder call
4619 public int getLastShutdownReason() {
4620 mContext.enforceCallingOrSelfPermission(
4621 android.Manifest.permission.DEVICE_POWER, null);
4622
4623 final long ident = Binder.clearCallingIdentity();
4624 try {
Mark Salyzyn74ce8b32018-06-05 09:06:54 -07004625 return getLastShutdownReasonInternal(REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004626 } finally {
4627 Binder.restoreCallingIdentity(ident);
4628 }
4629 }
4630
Calin Tatarua3805722018-08-09 16:41:28 +02004631 @Override // Binder call
4632 public int getLastSleepReason() {
4633 mContext.enforceCallingOrSelfPermission(
4634 android.Manifest.permission.DEVICE_POWER, null);
4635
4636 final long ident = Binder.clearCallingIdentity();
4637 try {
4638 return getLastSleepReasonInternal();
4639 } finally {
4640 Binder.restoreCallingIdentity(ident);
4641 }
4642 }
4643
Salvador Martineza6f7b252017-04-10 10:46:15 -07004644 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004645 * Reboots the device.
4646 *
4647 * @param confirm If true, shows a reboot confirmation dialog.
4648 * @param reason The reason for the reboot, or null if none.
4649 * @param wait If true, this call waits for the reboot to complete and does not return.
4650 */
4651 @Override // Binder call
4652 public void reboot(boolean confirm, String reason, boolean wait) {
4653 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004654 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4655 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004656 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4657 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004658
4659 final long ident = Binder.clearCallingIdentity();
4660 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004661 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4662 } finally {
4663 Binder.restoreCallingIdentity(ident);
4664 }
4665 }
4666
4667 /**
4668 * Reboots the device into safe mode
4669 *
4670 * @param confirm If true, shows a reboot confirmation dialog.
4671 * @param wait If true, this call waits for the reboot to complete and does not return.
4672 */
4673 @Override // Binder call
4674 public void rebootSafeMode(boolean confirm, boolean wait) {
4675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4676
4677 final long ident = Binder.clearCallingIdentity();
4678 try {
4679 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4680 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004681 } finally {
4682 Binder.restoreCallingIdentity(ident);
4683 }
4684 }
4685
4686 /**
4687 * Shuts down the device.
4688 *
4689 * @param confirm If true, shows a shutdown confirmation dialog.
4690 * @param wait If true, this call waits for the shutdown to complete and does not return.
4691 */
4692 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004693 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004694 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4695
4696 final long ident = Binder.clearCallingIdentity();
4697 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004698 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004699 } finally {
4700 Binder.restoreCallingIdentity(ident);
4701 }
4702 }
4703
4704 /**
4705 * Crash the runtime (causing a complete restart of the Android framework).
4706 * Requires REBOOT permission. Mostly for testing. Should not return.
4707 */
4708 @Override // Binder call
4709 public void crash(String message) {
4710 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4711
4712 final long ident = Binder.clearCallingIdentity();
4713 try {
4714 crashInternal(message);
4715 } finally {
4716 Binder.restoreCallingIdentity(ident);
4717 }
4718 }
4719
4720 /**
4721 * Set the setting that determines whether the device stays on when plugged in.
4722 * The argument is a bit string, with each bit specifying a power source that,
4723 * when the device is connected to that source, causes the device to stay on.
4724 * See {@link android.os.BatteryManager} for the list of power sources that
4725 * can be specified. Current values include
4726 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4727 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4728 *
4729 * Used by "adb shell svc power stayon ..."
4730 *
4731 * @param val an {@code int} containing the bits that specify which power sources
4732 * should cause the device to stay on.
4733 */
4734 @Override // Binder call
4735 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004736 int uid = Binder.getCallingUid();
4737 // if uid is of root's, we permit this operation straight away
4738 if (uid != Process.ROOT_UID) {
4739 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4740 Settings.getPackageNameForUid(mContext, uid), true)) {
4741 return;
4742 }
4743 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004744
4745 final long ident = Binder.clearCallingIdentity();
4746 try {
4747 setStayOnSettingInternal(val);
4748 } finally {
4749 Binder.restoreCallingIdentity(ident);
4750 }
4751 }
4752
4753 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004754 * Used by the phone application to make the attention LED flash when ringing.
4755 */
4756 @Override // Binder call
4757 public void setAttentionLight(boolean on, int color) {
4758 mContext.enforceCallingOrSelfPermission(
4759 android.Manifest.permission.DEVICE_POWER, null);
4760
4761 final long ident = Binder.clearCallingIdentity();
4762 try {
4763 setAttentionLightInternal(on, color);
4764 } finally {
4765 Binder.restoreCallingIdentity(ident);
4766 }
4767 }
4768
4769 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08004770 public void setDozeAfterScreenOff(boolean on) {
4771 mContext.enforceCallingOrSelfPermission(
4772 android.Manifest.permission.DEVICE_POWER, null);
4773
4774 final long ident = Binder.clearCallingIdentity();
4775 try {
4776 setDozeAfterScreenOffInternal(on);
4777 } finally {
4778 Binder.restoreCallingIdentity(ident);
4779 }
4780 }
4781
4782 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004783 public void boostScreenBrightness(long eventTime) {
4784 if (eventTime > SystemClock.uptimeMillis()) {
4785 throw new IllegalArgumentException("event time must not be in the future");
4786 }
4787
4788 mContext.enforceCallingOrSelfPermission(
4789 android.Manifest.permission.DEVICE_POWER, null);
4790
4791 final int uid = Binder.getCallingUid();
4792 final long ident = Binder.clearCallingIdentity();
4793 try {
4794 boostScreenBrightnessInternal(eventTime, uid);
4795 } finally {
4796 Binder.restoreCallingIdentity(ident);
4797 }
4798 }
4799
4800 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004801 public boolean isScreenBrightnessBoosted() {
4802 final long ident = Binder.clearCallingIdentity();
4803 try {
4804 return isScreenBrightnessBoostedInternal();
4805 } finally {
4806 Binder.restoreCallingIdentity(ident);
4807 }
4808 }
4809
Santos Cordon12f92eb2019-02-01 21:28:47 +00004810 @Override // binder call
4811 public boolean forceSuspend() {
4812 mContext.enforceCallingOrSelfPermission(
4813 android.Manifest.permission.DEVICE_POWER, null);
4814
4815 final int uid = Binder.getCallingUid();
4816 final long ident = Binder.clearCallingIdentity();
4817 try {
4818 return forceSuspendInternal(uid);
4819 } finally {
4820 Binder.restoreCallingIdentity(ident);
4821 }
4822 }
4823
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004824 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004825 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004826 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08004827
4828 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08004829
4830 boolean isDumpProto = false;
4831 for (String arg : args) {
4832 if (arg.equals("--proto")) {
4833 isDumpProto = true;
4834 }
4835 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004836 try {
Netta P958d0a52017-02-07 11:20:55 -08004837 if (isDumpProto) {
4838 dumpProto(fd);
4839 } else {
4840 dumpInternal(pw);
4841 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004842 } finally {
4843 Binder.restoreCallingIdentity(ident);
4844 }
4845 }
4846 }
4847
Salvador Martineza6f7b252017-04-10 10:46:15 -07004848 @VisibleForTesting
Santos Cordon64a6e612018-08-22 19:27:04 +01004849 BinderService getBinderServiceInstance() {
4850 return mBinderService;
4851 }
4852
4853 @VisibleForTesting
4854 LocalService getLocalServiceInstance() {
4855 return mLocalService;
4856 }
4857
4858 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004859 // lastRebootReasonProperty argument to permit testing
4860 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
4861 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01004862 if (line == null) {
4863 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4864 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07004865 switch (line) {
4866 case REASON_SHUTDOWN:
4867 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
4868 case REASON_REBOOT:
4869 return PowerManager.SHUTDOWN_REASON_REBOOT;
4870 case REASON_USERREQUESTED:
4871 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
4872 case REASON_THERMAL_SHUTDOWN:
4873 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07004874 case REASON_LOW_BATTERY:
4875 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
4876 case REASON_BATTERY_THERMAL_STATE:
4877 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07004878 default:
4879 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4880 }
4881 }
4882
Calin Tatarua3805722018-08-09 16:41:28 +02004883 private int getLastSleepReasonInternal() {
4884 synchronized (mLock) {
4885 return mLastSleepReason;
4886 }
4887 }
4888
Santos Cordon623526b2019-04-09 17:02:38 +01004889 private PowerManager.WakeData getLastWakeupInternal() {
4890 synchronized (mLock) {
4891 return new WakeData(mLastWakeTime, mLastWakeReason);
4892 }
4893 }
4894
Santos Cordond9701ab2019-08-01 18:33:20 +01004895 @VisibleForTesting
4896 final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08004897 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004898 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
4899 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4900 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4901 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08004902 }
Jeff Brown970d4132014-07-19 11:33:47 -07004903 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08004904 }
4905
Jeff Brown6f357d32014-01-15 20:40:55 -08004906 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004907 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
4908 switch (screenState) {
4909 case Display.STATE_UNKNOWN:
4910 case Display.STATE_OFF:
4911 case Display.STATE_DOZE:
4912 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07004913 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07004914 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07004915 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07004916 break;
4917 default:
4918 screenState = Display.STATE_UNKNOWN;
4919 break;
4920 }
4921 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4922 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4923 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4924 }
4925 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
4926 }
4927
Jeff Brown6f357d32014-01-15 20:40:55 -08004928 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07004929 public void setUserInactiveOverrideFromWindowManager() {
4930 setUserInactiveOverrideFromWindowManagerInternal();
4931 }
4932
4933 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08004934 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07004935 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08004936 }
4937
4938 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004939 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
4940 setDrawWakeLockOverrideFromSidekickInternal(keepState);
4941 }
4942
4943 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01004944 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
4945 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08004946 }
4947
4948 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08004949 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Kweku Adams9f488e22019-01-14 16:25:08 -08004950 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004951 }
4952
4953 @Override
4954 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08004955 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004956 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004957
4958 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004959 public boolean setDeviceIdleMode(boolean enabled) {
4960 return setDeviceIdleModeInternal(enabled);
4961 }
4962
4963 @Override
4964 public boolean setLightDeviceIdleMode(boolean enabled) {
4965 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004966 }
4967
4968 @Override
4969 public void setDeviceIdleWhitelist(int[] appids) {
4970 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004971 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004972
4973 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004974 public void setDeviceIdleTempWhitelist(int[] appids) {
4975 setDeviceIdleTempWhitelistInternal(appids);
4976 }
4977
4978 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004979 public void startUidChanges() {
4980 startUidChangesInternal();
4981 }
4982
4983 @Override
4984 public void finishUidChanges() {
4985 finishUidChangesInternal();
4986 }
4987
4988 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004989 public void updateUidProcState(int uid, int procState) {
4990 updateUidProcStateInternal(uid, procState);
4991 }
4992
4993 @Override
4994 public void uidGone(int uid) {
4995 uidGoneInternal(uid);
4996 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01004997
4998 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004999 public void uidActive(int uid) {
5000 uidActiveInternal(uid);
5001 }
5002
5003 @Override
5004 public void uidIdle(int uid) {
5005 uidIdleInternal(uid);
5006 }
5007
5008 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01005009 public void powerHint(int hintId, int data) {
5010 powerHintInternal(hintId, data);
5011 }
Alex Kershaw2418ea92018-10-19 17:17:49 +01005012
5013 @Override
5014 public boolean wasDeviceIdleFor(long ms) {
5015 return wasDeviceIdleForInternal(ms);
5016 }
Santos Cordon623526b2019-04-09 17:02:38 +01005017
5018 @Override
5019 public WakeData getLastWakeup() {
5020 return getLastWakeupInternal();
5021 }
Jeff Brown6f357d32014-01-15 20:40:55 -08005022 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005023}