blob: 697801f7787a6b650398ce0c2c44d88de6caac47 [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;
Pavel Grafov28939982017-10-03 15:11:52 +010025import android.annotation.UserIdInt;
Jason Monkafae4bd2015-12-15 14:20:06 -050026import android.app.ActivityManager;
Pavel Grafov28939982017-10-03 15:11:52 +010027import android.app.SynchronousUserSwitchObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.content.ContentResolver;
30import android.content.Context;
31import android.content.Intent;
32import android.content.IntentFilter;
33import android.content.pm.PackageManager;
Mike Lockwoodd7786b42009-10-15 17:09:16 -070034import android.content.res.Resources;
Doug Zongker43866e02010-01-07 12:09:54 -080035import android.database.ContentObserver;
Jeff Brown3b971592013-01-09 18:46:37 -080036import android.hardware.SensorManager;
37import android.hardware.SystemSensorManager;
Jeff Brown4ccb8232014-01-16 22:16:42 -080038import android.hardware.display.DisplayManagerInternal;
Jeff Brown131206b2014-04-08 17:27:14 -070039import android.hardware.display.DisplayManagerInternal.DisplayPowerRequest;
Ruchi Kandoi0d434042016-10-03 09:12:02 -070040import android.hardware.power.V1_0.PowerHint;
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -070041import android.metrics.LogMaker;
Jeff Brown96307042012-07-27 15:51:34 -070042import android.net.Uri;
Amith Yamasani8b619832010-09-22 16:11:59 -070043import android.os.BatteryManager;
Jeff Brown21392762014-06-13 19:00:36 -070044import android.os.BatteryManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Binder;
46import android.os.Handler;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.os.IBinder;
48import android.os.IPowerManager;
Jeff Brown96307042012-07-27 15:51:34 -070049import android.os.Looper;
Jim Miller92e66dd2012-02-21 18:57:12 -080050import android.os.Message;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.os.PowerManager;
Makoto Onuki2eccd022017-11-01 13:44:23 -070052import android.os.PowerManager.ServiceType;
Jeff Brown6f357d32014-01-15 20:40:55 -080053import android.os.PowerManagerInternal;
jackqdyulei92681e82017-02-28 11:26:28 -080054import android.os.PowerSaveState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Process;
56import android.os.RemoteException;
Jocelyn Dangf2c38c12017-03-31 14:03:37 -070057import android.os.ResultReceiver;
58import android.os.ShellCallback;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.SystemClock;
Nick Kralevichdbcf2d72013-04-18 14:41:40 -070060import android.os.SystemProperties;
Jeff Brown3edf5272014-08-14 19:25:14 -070061import android.os.Trace;
Jeff Brownd4935962012-09-25 13:27:20 -070062import android.os.UserHandle;
Christine Franks732c0432017-06-23 18:12:46 -070063import android.os.UserManager;
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -070064import android.os.WorkSource;
Narayan Kamath2f916ed2017-12-29 13:02:15 +000065import android.os.WorkSource.WorkChain;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066import android.provider.Settings;
Makoto Onukia3cd7b92018-03-19 14:47:05 -070067import android.provider.Settings.Global;
Daichi Hirono82ab9802016-03-02 13:23:29 +090068import android.provider.Settings.SettingNotFoundException;
Jeff Brown567f7ca2014-01-30 23:38:03 -080069import android.service.dreams.DreamManagerInternal;
Ruben Brunkc7be3be2016-04-01 17:07:51 -070070import android.service.vr.IVrManager;
71import android.service.vr.IVrStateCallbacks;
Dianne Hackborn0ef403e2017-01-24 18:22:15 -080072import android.util.KeyValueListParser;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -070073import android.util.PrintWriterPrinter;
Joe Onorato8a9b2202010-02-26 18:56:32 -080074import android.util.Slog;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -070075import android.util.SparseArray;
Jeff Brown96307042012-07-27 15:51:34 -070076import android.util.TimeUtils;
Netta P958d0a52017-02-07 11:20:55 -080077import android.util.proto.ProtoOutputStream;
Jeff Brown037c33e2014-04-09 00:31:55 -070078import android.view.Display;
Makoto Onukiaae89532017-11-08 14:32:03 -080079
jackqdyulei92681e82017-02-28 11:26:28 -080080import com.android.internal.annotations.VisibleForTesting;
Jason Monkafae4bd2015-12-15 14:20:06 -050081import com.android.internal.app.IAppOpsService;
82import com.android.internal.app.IBatteryStats;
Adrian Roos56021892017-02-27 20:25:09 +010083import com.android.internal.hardware.AmbientDisplayConfiguration;
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -070084import com.android.internal.logging.MetricsLogger;
85import com.android.internal.logging.nano.MetricsProto.MetricsEvent;
Jason Monkafae4bd2015-12-15 14:20:06 -050086import com.android.internal.os.BackgroundThread;
Jeff Sharkey3dee8d62016-03-02 13:07:56 -070087import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060088import com.android.internal.util.DumpUtils;
Jason Monkafae4bd2015-12-15 14:20:06 -050089import com.android.server.EventLogTags;
Jeff Sharkey5f3e9342017-03-13 14:53:11 -060090import com.android.server.LockGuard;
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -070091import com.android.server.RescueParty;
Jason Monkafae4bd2015-12-15 14:20:06 -050092import com.android.server.ServiceThread;
93import com.android.server.SystemService;
Michael Wright64c820d2017-03-21 12:36:55 +000094import com.android.server.UiThread;
Jason Monkafae4bd2015-12-15 14:20:06 -050095import com.android.server.Watchdog;
96import com.android.server.am.BatteryStatsService;
97import com.android.server.lights.Light;
98import com.android.server.lights.LightsManager;
Adrian Roose99bc052017-11-20 17:55:31 +010099import com.android.server.policy.WindowManagerPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800100import com.android.server.power.batterysaver.BatterySaverController;
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
Salvador Martineza6f7b252017-04-10 10:46:15 -0700201 // Possible reasons for shutting down for use in data/misc/reboot/last_shutdown_reason
202 private static final String REASON_SHUTDOWN = "shutdown";
203 private static final String REASON_REBOOT = "reboot";
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700204 private static final String REASON_USERREQUESTED = "shutdown,userrequested";
205 private static final String REASON_THERMAL_SHUTDOWN = "shutdown,thermal";
Sudheer Shanka292637f2017-09-25 10:36:23 -0700206 private static final String REASON_LOW_BATTERY = "shutdown,battery";
207 private static final String REASON_BATTERY_THERMAL_STATE = "shutdown,thermal,battery";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700208
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -0700209 private static final String TRACE_SCREEN_ON = "Screen turning on";
210
211 /** If turning screen on takes more than this long, we show a warning on logcat. */
212 private static final int SCREEN_ON_LATENCY_WARNING_MS = 200;
213
Tony Mantlerb8009fd2016-03-14 15:55:35 -0700214 /** Constants for {@link #shutdownOrRebootInternal} */
215 @Retention(RetentionPolicy.SOURCE)
216 @IntDef({HALT_MODE_SHUTDOWN, HALT_MODE_REBOOT, HALT_MODE_REBOOT_SAFE_MODE})
217 public @interface HaltMode {}
218 private static final int HALT_MODE_SHUTDOWN = 0;
219 private static final int HALT_MODE_REBOOT = 1;
220 private static final int HALT_MODE_REBOOT_SAFE_MODE = 2;
221
Mark Salyzyne65c0c62017-08-15 07:53:47 -0700222 // Persistent property for last reboot reason
223 private static final String LAST_REBOOT_PROPERTY = "persist.sys.boot.reason";
Salvador Martineza6f7b252017-04-10 10:46:15 -0700224
Jeff Brownb880d882014-02-10 19:47:07 -0800225 private final Context mContext;
Jeff Brown2c43c332014-06-12 22:38:59 -0700226 private final ServiceThread mHandlerThread;
227 private final PowerManagerHandler mHandler;
Adrian Roos56021892017-02-27 20:25:09 +0100228 private final AmbientDisplayConfiguration mAmbientDisplayConfiguration;
jackqdyulei455e90a2017-02-09 15:29:16 -0800229 private final BatterySaverPolicy mBatterySaverPolicy;
Makoto Onuki66a78122017-11-14 15:03:21 -0800230 private final BatterySaverController mBatterySaverController;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700231 private final BatterySaverStateMachine mBatterySaverStateMachine;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700232 private final BatterySavingStats mBatterySavingStats;
Jeff Brown2c43c332014-06-12 22:38:59 -0700233
Adam Lesinski182f73f2013-12-05 16:48:06 -0800234 private LightsManager mLightsManager;
Jeff Brown21392762014-06-13 19:00:36 -0700235 private BatteryManagerInternal mBatteryManagerInternal;
Jeff Brown4ccb8232014-01-16 22:16:42 -0800236 private DisplayManagerInternal mDisplayManagerInternal;
Jeff Brown96307042012-07-27 15:51:34 -0700237 private IBatteryStats mBatteryStats;
Dianne Hackborn713df152013-05-17 11:27:57 -0700238 private IAppOpsService mAppOps;
Jeff Brown96307042012-07-27 15:51:34 -0700239 private WindowManagerPolicy mPolicy;
240 private Notifier mNotifier;
Jeff Brown3b971592013-01-09 18:46:37 -0800241 private WirelessChargerDetector mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -0700242 private SettingsObserver mSettingsObserver;
Jeff Brown567f7ca2014-01-30 23:38:03 -0800243 private DreamManagerInternal mDreamManager;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800244 private Light mAttentionLight;
Joe Onorato609695d2010-10-14 14:57:49 -0700245
Jeff Sharkey5f3e9342017-03-13 14:53:11 -0600246 private final Object mLock = LockGuard.installNewLock(LockGuard.INDEX_POWER);
Jeff Brown96307042012-07-27 15:51:34 -0700247
248 // A bitfield that indicates what parts of the power state have
249 // changed and need to be recalculated.
250 private int mDirty;
251
252 // Indicates whether the device is awake or asleep or somewhere in between.
253 // This is distinct from the screen power state, which is managed separately.
254 private int mWakefulness;
Jeff Brownfbe96702014-11-19 18:30:58 -0800255 private boolean mWakefulnessChanging;
Jeff Brown96307042012-07-27 15:51:34 -0700256
Jeff Brown26875502014-01-30 21:47:47 -0800257 // True if the sandman has just been summoned for the first time since entering the
258 // dreaming or dozing state. Indicates whether a new dream should begin.
259 private boolean mSandmanSummoned;
260
Jeff Brown96307042012-07-27 15:51:34 -0700261 // True if MSG_SANDMAN has been scheduled.
262 private boolean mSandmanScheduled;
263
264 // Table of all suspend blockers.
265 // There should only be a few of these.
266 private final ArrayList<SuspendBlocker> mSuspendBlockers = new ArrayList<SuspendBlocker>();
267
268 // Table of all wake locks acquired by applications.
269 private final ArrayList<WakeLock> mWakeLocks = new ArrayList<WakeLock>();
270
271 // A bitfield that summarizes the state of all active wakelocks.
272 private int mWakeLockSummary;
273
Dianne Hackbornd0db6f02016-07-18 14:14:20 -0700274 // Have we scheduled a message to check for long wake locks? This is when we will check.
275 private long mNotifyLongScheduled;
276
277 // Last time we checked for long wake locks.
278 private long mNotifyLongDispatched;
279
280 // The time we decided to do next long check.
281 private long mNotifyLongNextCheck;
282
Jeff Brown96307042012-07-27 15:51:34 -0700283 // If true, instructs the display controller to wait for the proximity sensor to
284 // go negative before turning the screen on.
285 private boolean mRequestWaitForNegativeProximity;
286
287 // Timestamp of the last time the device was awoken or put to sleep.
288 private long mLastWakeTime;
289 private long mLastSleepTime;
290
Jeff Brown96307042012-07-27 15:51:34 -0700291 // Timestamp of the last call to user activity.
292 private long mLastUserActivityTime;
293 private long mLastUserActivityTimeNoChangeLights;
294
Jeff Brown0a571122014-08-21 21:50:43 -0700295 // Timestamp of last interactive power hint.
296 private long mLastInteractivePowerHintTime;
297
Jeff Browne333e672014-10-28 13:48:55 -0700298 // Timestamp of the last screen brightness boost.
299 private long mLastScreenBrightnessBoostTime;
300 private boolean mScreenBrightnessBoostInProgress;
301
Jeff Brown96307042012-07-27 15:51:34 -0700302 // A bitfield that summarizes the effect of the user activity timer.
Jeff Brown96307042012-07-27 15:51:34 -0700303 private int mUserActivitySummary;
304
305 // The desired display power state. The actual state may lag behind the
306 // requested because it is updated asynchronously by the display power controller.
307 private final DisplayPowerRequest mDisplayPowerRequest = new DisplayPowerRequest();
308
Jeff Brown96307042012-07-27 15:51:34 -0700309 // True if the display power state has been fully applied, which means the display
310 // is actually on or actually off or whatever was requested.
311 private boolean mDisplayReady;
312
Jeff Brown27f7a862012-12-12 15:43:31 -0800313 // The suspend blocker used to keep the CPU alive when an application has acquired
314 // a wake lock.
315 private final SuspendBlocker mWakeLockSuspendBlocker;
316
317 // True if the wake lock suspend blocker has been acquired.
Jeff Brown96307042012-07-27 15:51:34 -0700318 private boolean mHoldingWakeLockSuspendBlocker;
319
Jeff Brown27f7a862012-12-12 15:43:31 -0800320 // The suspend blocker used to keep the CPU alive when the display is on, the
321 // display is getting ready or there is user activity (in which case the display
322 // must be on).
323 private final SuspendBlocker mDisplaySuspendBlocker;
324
325 // True if the display suspend blocker has been acquired.
326 private boolean mHoldingDisplaySuspendBlocker;
Jeff Brown96307042012-07-27 15:51:34 -0700327
328 // True if systemReady() has been called.
329 private boolean mSystemReady;
330
331 // True if boot completed occurred. We keep the screen on until this happens.
332 private boolean mBootCompleted;
333
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700334 // Runnables that should be triggered on boot completed
335 private Runnable[] mBootCompletedRunnables;
336
Jeff Brown26875502014-01-30 21:47:47 -0800337 // True if auto-suspend mode is enabled.
338 // Refer to autosuspend.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700339 private boolean mHalAutoSuspendModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800340
341 // True if interactive mode is enabled.
342 // Refer to power.h.
Jeff Brown037c33e2014-04-09 00:31:55 -0700343 private boolean mHalInteractiveModeEnabled;
Jeff Brown26875502014-01-30 21:47:47 -0800344
Jeff Brown96307042012-07-27 15:51:34 -0700345 // True if the device is plugged into a power source.
346 private boolean mIsPowered;
347
Jeff Brownf3fb8952012-10-02 20:57:05 -0700348 // The current plug type, such as BatteryManager.BATTERY_PLUGGED_WIRELESS.
349 private int mPlugType;
350
Jeff Brown016ff142012-10-15 16:47:22 -0700351 // The current battery level percentage.
352 private int mBatteryLevel;
353
354 // The battery level percentage at the time the dream started.
355 // This is used to terminate a dream and go to sleep if the battery is
356 // draining faster than it is charging and the user activity timeout has expired.
357 private int mBatteryLevelWhenDreamStarted;
358
Jeff Brownec6aa592012-10-17 20:30:25 -0700359 // The current dock state.
360 private int mDockState = Intent.EXTRA_DOCK_STATE_UNDOCKED;
361
Jeff Brown26875502014-01-30 21:47:47 -0800362 // True to decouple auto-suspend mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700363 private boolean mDecoupleHalAutoSuspendModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800364
365 // True to decouple interactive mode from the display state.
Jeff Brown037c33e2014-04-09 00:31:55 -0700366 private boolean mDecoupleHalInteractiveModeFromDisplayConfig;
Jeff Brown26875502014-01-30 21:47:47 -0800367
Jeff Brown96307042012-07-27 15:51:34 -0700368 // True if the device should wake up when plugged or unplugged.
369 private boolean mWakeUpWhenPluggedOrUnpluggedConfig;
370
Bryce Lee584a4452014-10-21 15:55:55 -0700371 // True if the device should wake up when plugged or unplugged in theater mode.
372 private boolean mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig;
373
Jeff Brownec083212013-09-11 20:45:25 -0700374 // True if the device should suspend when the screen is off due to proximity.
375 private boolean mSuspendWhenScreenOffDueToProximityConfig;
376
Jeff Brown96307042012-07-27 15:51:34 -0700377 // True if dreams are supported on this device.
378 private boolean mDreamsSupportedConfig;
379
John Spurlocked108f32012-10-18 16:49:24 -0400380 // Default value for dreams enabled
381 private boolean mDreamsEnabledByDefaultConfig;
382
383 // Default value for dreams activate-on-sleep
384 private boolean mDreamsActivatedOnSleepByDefaultConfig;
385
386 // Default value for dreams activate-on-dock
387 private boolean mDreamsActivatedOnDockByDefaultConfig;
388
Jeff Brown26875502014-01-30 21:47:47 -0800389 // True if dreams can run while not plugged in.
390 private boolean mDreamsEnabledOnBatteryConfig;
391
392 // Minimum battery level to allow dreaming when powered.
393 // Use -1 to disable this safety feature.
394 private int mDreamsBatteryLevelMinimumWhenPoweredConfig;
395
396 // Minimum battery level to allow dreaming when not powered.
397 // Use -1 to disable this safety feature.
398 private int mDreamsBatteryLevelMinimumWhenNotPoweredConfig;
399
400 // If the battery level drops by this percentage and the user activity timeout
401 // has expired, then assume the device is receiving insufficient current to charge
402 // effectively and terminate the dream. Use -1 to disable this safety feature.
403 private int mDreamsBatteryLevelDrainCutoffConfig;
404
Jeff Brown96307042012-07-27 15:51:34 -0700405 // True if dreams are enabled by the user.
406 private boolean mDreamsEnabledSetting;
407
John Spurlock1a868b72012-08-22 09:56:51 -0400408 // True if dreams should be activated on sleep.
409 private boolean mDreamsActivateOnSleepSetting;
410
Jeff Brownec6aa592012-10-17 20:30:25 -0700411 // True if dreams should be activated on dock.
412 private boolean mDreamsActivateOnDockSetting;
413
Jeff Brown2175e9c2014-09-12 16:11:07 -0700414 // True if doze should not be started until after the screen off transition.
Lucas Dupin16cfe452018-02-08 13:14:50 -0800415 private boolean mDozeAfterScreenOff;
Jeff Brown2175e9c2014-09-12 16:11:07 -0700416
Jeff Brown27736f52014-05-20 17:17:10 -0700417 // The minimum screen off timeout, in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100418 private long mMinimumScreenOffTimeoutConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700419
420 // The screen dim duration, in milliseconds.
421 // This is subtracted from the end of the screen off timeout so the
422 // minimum screen off timeout should be longer than this.
Pavel Grafov28939982017-10-03 15:11:52 +0100423 private long mMaximumScreenDimDurationConfig;
Jeff Brown27736f52014-05-20 17:17:10 -0700424
425 // The maximum screen dim time expressed as a ratio relative to the screen
426 // off timeout. If the screen off timeout is very short then we want the
427 // dim timeout to also be quite short so that most of the time is spent on.
428 // Otherwise the user won't get much screen on time before dimming occurs.
429 private float mMaximumScreenDimRatioConfig;
430
Jason Monk27bbb2d2015-03-31 16:46:39 -0400431 // Whether device supports double tap to wake.
432 private boolean mSupportsDoubleTapWakeConfig;
433
Jeff Brown96307042012-07-27 15:51:34 -0700434 // The screen off timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100435 private long mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -0700436
Jeff Brown05af6ad2014-09-30 20:54:30 -0700437 // The sleep timeout setting value in milliseconds.
Pavel Grafov28939982017-10-03 15:11:52 +0100438 private long mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -0700439
Jeff Brown96307042012-07-27 15:51:34 -0700440 // The maximum allowable screen off timeout according to the device
441 // administration policy. Overrides other settings.
Pavel Grafov28939982017-10-03 15:11:52 +0100442 private long mMaximumScreenOffTimeoutFromDeviceAdmin = Long.MAX_VALUE;
Jeff Brown96307042012-07-27 15:51:34 -0700443
444 // The stay on while plugged in setting.
445 // A bitfield of battery conditions under which to make the screen stay on.
446 private int mStayOnWhilePluggedInSetting;
447
448 // True if the device should stay on.
449 private boolean mStayOn;
450
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800451 // True if the lights should stay off until an explicit user action.
452 private static boolean sQuiescent;
453
Jeff Brown93cbbb22012-10-04 13:18:36 -0700454 // True if the proximity sensor reads a positive result.
455 private boolean mProximityPositive;
456
Jeff Brown96307042012-07-27 15:51:34 -0700457 // Screen brightness setting limits.
458 private int mScreenBrightnessSettingMinimum;
459 private int mScreenBrightnessSettingMaximum;
460 private int mScreenBrightnessSettingDefault;
461
462 // The screen brightness setting, from 0 to 255.
463 // Use -1 if no value has been set.
464 private int mScreenBrightnessSetting;
465
466 // The screen brightness mode.
467 // One of the Settings.System.SCREEN_BRIGHTNESS_MODE_* constants.
468 private int mScreenBrightnessModeSetting;
469
470 // The screen brightness setting override from the window manager
471 // to allow the current foreground activity to override the brightness.
472 // Use -1 to disable.
473 private int mScreenBrightnessOverrideFromWindowManager = -1;
474
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -0700475 // The window manager has determined the user to be inactive via other means.
476 // Set this to false to disable.
477 private boolean mUserInactiveOverrideFromWindowManager;
478
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -0700479 // The next possible user activity timeout after being explicitly told the user is inactive.
480 // Set to -1 when not told the user is inactive since the last period spent dozing or asleep.
481 private long mOverriddenTimeout = -1;
482
Jeff Brown1e3b98d2012-09-30 18:58:59 -0700483 // The user activity timeout override from the window manager
484 // to allow the current foreground activity to override the user activity timeout.
485 // Use -1 to disable.
486 private long mUserActivityTimeoutOverrideFromWindowManager = -1;
487
Jeff Brown970d4132014-07-19 11:33:47 -0700488 // The screen state to use while dozing.
489 private int mDozeScreenStateOverrideFromDreamManager = Display.STATE_UNKNOWN;
490
491 // The screen brightness to use while dozing.
492 private int mDozeScreenBrightnessOverrideFromDreamManager = PowerManager.BRIGHTNESS_DEFAULT;
493
Ivan Podogov56bc6d02018-02-26 16:04:24 +0000494 // Keep display state when dozing.
495 private boolean mDrawWakeLockOverrideFromSidekick;
496
Jeff Brown9ba8d782012-10-01 16:38:23 -0700497 // Time when we last logged a warning about calling userActivity() without permission.
498 private long mLastWarningAboutUserActivityPermission = Long.MIN_VALUE;
499
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700500 // True if the battery level is currently considered low.
501 private boolean mBatteryLevelLow;
502
Dianne Hackborn88e98df2015-03-23 13:29:14 -0700503 // True if we are currently in device idle mode.
504 private boolean mDeviceIdleMode;
505
Dianne Hackborn08c47a52015-10-15 12:38:14 -0700506 // True if we are currently in light device idle mode.
507 private boolean mLightDeviceIdleMode;
508
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -0700509 // Set of app ids that we will always respect the wake locks for.
510 int[] mDeviceIdleWhitelist = new int[0];
511
Amith Yamasaniaf575b92015-05-29 15:35:26 -0700512 // Set of app ids that are temporarily allowed to acquire wakelocks due to high-pri message
513 int[] mDeviceIdleTempWhitelist = new int[0];
514
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700515 private final SparseArray<UidState> mUidState = new SparseArray<>();
516
517 // We are currently in the middle of a batch change of uids.
518 private boolean mUidsChanging;
519
520 // Some uids have actually changed while mUidsChanging was true.
521 private boolean mUidsChanged;
Dianne Hackbornd23e0d62015-05-15 16:36:12 -0700522
Bryce Lee584a4452014-10-21 15:55:55 -0700523 // True if theater mode is enabled
524 private boolean mTheaterModeEnabled;
525
Adrian Roos56021892017-02-27 20:25:09 +0100526 // True if always on display is enabled
527 private boolean mAlwaysOnEnabled;
528
Jason Monk27bbb2d2015-03-31 16:46:39 -0400529 // True if double tap to wake is enabled
530 private boolean mDoubleTapWakeEnabled;
531
Santos Cordon3107d292016-09-20 15:50:35 -0700532 // True if we are currently in VR Mode.
533 private boolean mIsVrModeEnabled;
534
Pavel Grafov28939982017-10-03 15:11:52 +0100535 private final class ForegroundProfileObserver extends SynchronousUserSwitchObserver {
536 @Override
537 public void onUserSwitching(int newUserId) throws RemoteException {}
538
539 @Override
540 public void onForegroundProfileSwitch(@UserIdInt int newProfileId) throws RemoteException {
541 final long now = SystemClock.uptimeMillis();
542 synchronized(mLock) {
543 mForegroundProfile = newProfileId;
544 maybeUpdateForegroundProfileLastActivityLocked(now);
545 }
546 }
547 }
548
549 // User id corresponding to activity the user is currently interacting with.
550 private @UserIdInt int mForegroundProfile;
551
552 // Per-profile state to track when a profile should be locked.
553 private final SparseArray<ProfilePowerState> mProfilePowerState = new SparseArray<>();
554
555 private static final class ProfilePowerState {
556 // Profile user id.
557 final @UserIdInt int mUserId;
558 // Maximum time to lock set by admin.
559 long mScreenOffTimeout;
560 // Like top-level mWakeLockSummary, but only for wake locks that affect current profile.
561 int mWakeLockSummary;
562 // Last user activity that happened in an app running in the profile.
563 long mLastUserActivityTime;
564 // Whether profile has been locked last time it timed out.
565 boolean mLockingNotified;
566
567 public ProfilePowerState(@UserIdInt int userId, long screenOffTimeout) {
568 mUserId = userId;
569 mScreenOffTimeout = screenOffTimeout;
570 // Not accurate but at least won't cause immediate locking of the profile.
571 mLastUserActivityTime = SystemClock.uptimeMillis();
572 }
573 }
574
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800575 /**
576 * All times are in milliseconds. These constants are kept synchronized with the system
577 * global Settings. Any access to this class or its fields should be done while
578 * holding the PowerManagerService.mLock lock.
579 */
580 private final class Constants extends ContentObserver {
581 // Key names stored in the settings value.
582 private static final String KEY_NO_CACHED_WAKE_LOCKS = "no_cached_wake_locks";
583
584 private static final boolean DEFAULT_NO_CACHED_WAKE_LOCKS = true;
585
586 // Prevent processes that are cached from holding wake locks?
587 public boolean NO_CACHED_WAKE_LOCKS = DEFAULT_NO_CACHED_WAKE_LOCKS;
588
589 private ContentResolver mResolver;
590 private final KeyValueListParser mParser = new KeyValueListParser(',');
591
592 public Constants(Handler handler) {
593 super(handler);
594 }
595
596 public void start(ContentResolver resolver) {
597 mResolver = resolver;
598 mResolver.registerContentObserver(Settings.Global.getUriFor(
599 Settings.Global.POWER_MANAGER_CONSTANTS), false, this);
600 updateConstants();
601 }
602
603 @Override
604 public void onChange(boolean selfChange, Uri uri) {
605 updateConstants();
606 }
607
608 private void updateConstants() {
609 synchronized (mLock) {
610 try {
611 mParser.setString(Settings.Global.getString(mResolver,
612 Settings.Global.POWER_MANAGER_CONSTANTS));
613 } catch (IllegalArgumentException e) {
614 // Failed to parse the settings string, log this and move on
615 // with defaults.
616 Slog.e(TAG, "Bad alarm manager settings", e);
617 }
618
619 NO_CACHED_WAKE_LOCKS = mParser.getBoolean(KEY_NO_CACHED_WAKE_LOCKS,
620 DEFAULT_NO_CACHED_WAKE_LOCKS);
621 }
622 }
623
624 void dump(PrintWriter pw) {
625 pw.println(" Settings " + Settings.Global.POWER_MANAGER_CONSTANTS + ":");
626
627 pw.print(" "); pw.print(KEY_NO_CACHED_WAKE_LOCKS); pw.print("=");
628 pw.println(NO_CACHED_WAKE_LOCKS);
629 }
Netta P958d0a52017-02-07 11:20:55 -0800630
631 void dumpProto(ProtoOutputStream proto) {
Kweku Adamse6b00c22017-10-23 16:46:45 -0700632 final long constantsToken = proto.start(PowerManagerServiceDumpProto.CONSTANTS);
633 proto.write(PowerManagerServiceDumpProto.ConstantsProto.IS_NO_CACHED_WAKE_LOCKS,
Netta P958d0a52017-02-07 11:20:55 -0800634 NO_CACHED_WAKE_LOCKS);
635 proto.end(constantsToken);
636 }
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800637 }
638
639 final Constants mConstants;
640
Jeff Brown00fa7bd2010-07-02 15:37:36 -0700641 private native void nativeInit();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642
Jeff Brown96307042012-07-27 15:51:34 -0700643 private static native void nativeAcquireSuspendBlocker(String name);
644 private static native void nativeReleaseSuspendBlocker(String name);
Jeff Brown9e316a12012-10-08 19:17:06 -0700645 private static native void nativeSetInteractive(boolean enable);
646 private static native void nativeSetAutoSuspend(boolean enable);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -0700647 private static native void nativeSendPowerHint(int hintId, int data);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400648 private static native void nativeSetFeature(int featureId, int data);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800649
Jeff Brownb880d882014-02-10 19:47:07 -0800650 public PowerManagerService(Context context) {
651 super(context);
652 mContext = context;
Jeff Brown2c43c332014-06-12 22:38:59 -0700653 mHandlerThread = new ServiceThread(TAG,
654 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
655 mHandlerThread.start();
656 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800657 mConstants = new Constants(mHandler);
Adrian Roos56021892017-02-27 20:25:09 +0100658 mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
Makoto Onuki66a78122017-11-14 15:03:21 -0800659
Makoto Onukibd7a6252018-05-10 13:41:39 -0700660 mBatterySavingStats = new BatterySavingStats(mLock);
661 mBatterySaverPolicy = new BatterySaverPolicy(mLock, mContext, mBatterySavingStats);
662 mBatterySaverController = new BatterySaverController(mLock, mContext,
663 BackgroundThread.get().getLooper(), mBatterySaverPolicy, mBatterySavingStats);
664 mBatterySaverStateMachine = new BatterySaverStateMachine(
665 mLock, mContext, mBatterySaverController);
Jeff Brown2c43c332014-06-12 22:38:59 -0700666
Jeff Brown96307042012-07-27 15:51:34 -0700667 synchronized (mLock) {
Jeff Brown27f7a862012-12-12 15:43:31 -0800668 mWakeLockSuspendBlocker = createSuspendBlockerLocked("PowerManagerService.WakeLocks");
669 mDisplaySuspendBlocker = createSuspendBlockerLocked("PowerManagerService.Display");
670 mDisplaySuspendBlocker.acquire();
671 mHoldingDisplaySuspendBlocker = true;
Jeff Brown037c33e2014-04-09 00:31:55 -0700672 mHalAutoSuspendModeEnabled = false;
673 mHalInteractiveModeEnabled = true;
Jeff Brown27f7a862012-12-12 15:43:31 -0800674
Jeff Brown96307042012-07-27 15:51:34 -0700675 mWakefulness = WAKEFULNESS_AWAKE;
Jeff Brown7304c342012-05-11 18:42:42 -0700676
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -0800677 sQuiescent = SystemProperties.get(SYSTEM_PROPERTY_QUIESCENT, "0").equals("1");
678
Jeff Brown037c33e2014-04-09 00:31:55 -0700679 nativeInit();
680 nativeSetAutoSuspend(false);
681 nativeSetInteractive(true);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400682 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, 0);
Jeff Brown037c33e2014-04-09 00:31:55 -0700683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800684 }
685
jackqdyulei92681e82017-02-28 11:26:28 -0800686 @VisibleForTesting
687 PowerManagerService(Context context, BatterySaverPolicy batterySaverPolicy) {
688 super(context);
689
jackqdyulei92681e82017-02-28 11:26:28 -0800690 mContext = context;
691 mHandlerThread = new ServiceThread(TAG,
692 Process.THREAD_PRIORITY_DISPLAY, false /*allowIo*/);
693 mHandlerThread.start();
694 mHandler = new PowerManagerHandler(mHandlerThread.getLooper());
695 mConstants = new Constants(mHandler);
Adrian Roos56021892017-02-27 20:25:09 +0100696 mAmbientDisplayConfiguration = new AmbientDisplayConfiguration(mContext);
jackqdyulei92681e82017-02-28 11:26:28 -0800697 mDisplaySuspendBlocker = null;
698 mWakeLockSuspendBlocker = null;
Makoto Onuki66a78122017-11-14 15:03:21 -0800699
Makoto Onukibd7a6252018-05-10 13:41:39 -0700700 mBatterySavingStats = new BatterySavingStats(mLock);
Makoto Onuki66a78122017-11-14 15:03:21 -0800701 mBatterySaverPolicy = batterySaverPolicy;
Makoto Onukibd7a6252018-05-10 13:41:39 -0700702 mBatterySaverController = new BatterySaverController(mLock, context,
703 BackgroundThread.getHandler().getLooper(), batterySaverPolicy, mBatterySavingStats);
704 mBatterySaverStateMachine = new BatterySaverStateMachine(
705 mLock, mContext, mBatterySaverController);
jackqdyulei92681e82017-02-28 11:26:28 -0800706 }
707
Jeff Brown6f357d32014-01-15 20:40:55 -0800708 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -0800709 public void onStart() {
710 publishBinderService(Context.POWER_SERVICE, new BinderService());
711 publishLocalService(PowerManagerInternal.class, new LocalService());
Jeff Brown9e316a12012-10-08 19:17:06 -0700712
713 Watchdog.getInstance().addMonitor(this);
Jeff Brown6f357d32014-01-15 20:40:55 -0800714 Watchdog.getInstance().addThread(mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700715 }
Jim Miller92e66dd2012-02-21 18:57:12 -0800716
Jeff Brown6d2a9492014-08-07 19:06:49 -0700717 @Override
718 public void onBootPhase(int phase) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700719 synchronized (mLock) {
Jeff Sharkeyb5e89c62016-04-01 23:20:31 -0600720 if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
721 incrementBootCount();
722
723 } else if (phase == PHASE_BOOT_COMPLETED) {
Craig Mautner6e2f3952014-09-09 14:26:41 -0700724 final long now = SystemClock.uptimeMillis();
725 mBootCompleted = true;
726 mDirty |= DIRTY_BOOT_COMPLETED;
Makoto Onukia3cd7b92018-03-19 14:47:05 -0700727
728 mBatterySaverStateMachine.onBootCompleted();
Craig Mautner6e2f3952014-09-09 14:26:41 -0700729 userActivityNoUpdateLocked(
730 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
731 updatePowerStateLocked();
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700732
733 if (!ArrayUtils.isEmpty(mBootCompletedRunnables)) {
734 Slog.d(TAG, "Posting " + mBootCompletedRunnables.length + " delayed runnables");
735 for (Runnable r : mBootCompletedRunnables) {
736 BackgroundThread.getHandler().post(r);
737 }
738 }
739 mBootCompletedRunnables = null;
Craig Mautner6e2f3952014-09-09 14:26:41 -0700740 }
Jeff Brown6d2a9492014-08-07 19:06:49 -0700741 }
742 }
743
Jeff Brown21392762014-06-13 19:00:36 -0700744 public void systemReady(IAppOpsService appOps) {
Jeff Brown96307042012-07-27 15:51:34 -0700745 synchronized (mLock) {
746 mSystemReady = true;
Jeff Brown2c43c332014-06-12 22:38:59 -0700747 mAppOps = appOps;
748 mDreamManager = getLocalService(DreamManagerInternal.class);
749 mDisplayManagerInternal = getLocalService(DisplayManagerInternal.class);
750 mPolicy = getLocalService(WindowManagerPolicy.class);
Jeff Brown21392762014-06-13 19:00:36 -0700751 mBatteryManagerInternal = getLocalService(BatteryManagerInternal.class);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800752
Adam Lesinski182f73f2013-12-05 16:48:06 -0800753 PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
Jeff Brown96307042012-07-27 15:51:34 -0700754 mScreenBrightnessSettingMinimum = pm.getMinimumScreenBrightnessSetting();
755 mScreenBrightnessSettingMaximum = pm.getMaximumScreenBrightnessSetting();
756 mScreenBrightnessSettingDefault = pm.getDefaultScreenBrightnessSetting();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800757
Jaikumar Ganesh6d0c1d782013-03-27 17:41:33 -0700758 SensorManager sensorManager = new SystemSensorManager(mContext, mHandler.getLooper());
Jeff Brown3b971592013-01-09 18:46:37 -0800759
Jeff Brownc38c9be2012-10-04 13:16:19 -0700760 // The notifier runs on the system server's main looper so as not to interfere
761 // with the animations and other critical functions of the power manager.
Jeff Brown2c43c332014-06-12 22:38:59 -0700762 mBatteryStats = BatteryStatsService.getService();
Jeff Brownc38c9be2012-10-04 13:16:19 -0700763 mNotifier = new Notifier(Looper.getMainLooper(), mContext, mBatteryStats,
Svet Ganovf7b47252018-02-26 11:11:27 -0800764 createSuspendBlockerLocked("PowerManagerService.Broadcasts"), mPolicy);
Jeff Brownc38c9be2012-10-04 13:16:19 -0700765
Jeff Brown3b971592013-01-09 18:46:37 -0800766 mWirelessChargerDetector = new WirelessChargerDetector(sensorManager,
Jeff Browndbcc8a22013-10-01 16:16:44 -0700767 createSuspendBlockerLocked("PowerManagerService.WirelessChargerDetector"),
768 mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700769 mSettingsObserver = new SettingsObserver(mHandler);
Jeff Brown2c43c332014-06-12 22:38:59 -0700770
771 mLightsManager = getLocalService(LightsManager.class);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800772 mAttentionLight = mLightsManager.getLight(LightsManager.LIGHT_ID_ATTENTION);
Mike Lockwoodaa66ea82009-10-31 16:31:27 -0400773
Jeff Brown131206b2014-04-08 17:27:14 -0700774 // Initialize display power management.
775 mDisplayManagerInternal.initPowerManagement(
776 mDisplayPowerCallbacks, mHandler, sensorManager);
777
Pavel Grafov28939982017-10-03 15:11:52 +0100778 try {
779 final ForegroundProfileObserver observer = new ForegroundProfileObserver();
780 ActivityManager.getService().registerUserSwitchObserver(observer, TAG);
781 } catch (RemoteException e) {
782 // Shouldn't happen since in-process.
783 }
Makoto Onuki66a78122017-11-14 15:03:21 -0800784
Jeff Brown96307042012-07-27 15:51:34 -0700785 // Go.
786 readConfigurationLocked();
787 updateSettingsLocked();
788 mDirty |= DIRTY_BATTERY_STATE;
789 updatePowerStateLocked();
790 }
Shibin George43f5de02016-07-06 02:12:10 +0530791
Jeff Sharkey6e544612017-02-20 11:02:26 -0700792 final ContentResolver resolver = mContext.getContentResolver();
793 mConstants.start(resolver);
Makoto Onuki66a78122017-11-14 15:03:21 -0800794
795 mBatterySaverController.systemReady();
Makoto Onukibd7a6252018-05-10 13:41:39 -0700796 mBatterySaverPolicy.systemReady();
Jeff Sharkey6e544612017-02-20 11:02:26 -0700797
798 // Register for settings changes.
799 resolver.registerContentObserver(Settings.Secure.getUriFor(
800 Settings.Secure.SCREENSAVER_ENABLED),
801 false, mSettingsObserver, UserHandle.USER_ALL);
802 resolver.registerContentObserver(Settings.Secure.getUriFor(
803 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP),
804 false, mSettingsObserver, UserHandle.USER_ALL);
805 resolver.registerContentObserver(Settings.Secure.getUriFor(
806 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK),
807 false, mSettingsObserver, UserHandle.USER_ALL);
808 resolver.registerContentObserver(Settings.System.getUriFor(
809 Settings.System.SCREEN_OFF_TIMEOUT),
810 false, mSettingsObserver, UserHandle.USER_ALL);
811 resolver.registerContentObserver(Settings.Secure.getUriFor(
812 Settings.Secure.SLEEP_TIMEOUT),
813 false, mSettingsObserver, UserHandle.USER_ALL);
814 resolver.registerContentObserver(Settings.Global.getUriFor(
815 Settings.Global.STAY_ON_WHILE_PLUGGED_IN),
816 false, mSettingsObserver, UserHandle.USER_ALL);
817 resolver.registerContentObserver(Settings.System.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700818 Settings.System.SCREEN_BRIGHTNESS_MODE),
819 false, mSettingsObserver, UserHandle.USER_ALL);
820 resolver.registerContentObserver(Settings.System.getUriFor(
821 Settings.System.SCREEN_AUTO_BRIGHTNESS_ADJ),
822 false, mSettingsObserver, UserHandle.USER_ALL);
823 resolver.registerContentObserver(Settings.Global.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700824 Settings.Global.THEATER_MODE_ON),
825 false, mSettingsObserver, UserHandle.USER_ALL);
826 resolver.registerContentObserver(Settings.Secure.getUriFor(
Adrian Roos56021892017-02-27 20:25:09 +0100827 Settings.Secure.DOZE_ALWAYS_ON),
828 false, mSettingsObserver, UserHandle.USER_ALL);
829 resolver.registerContentObserver(Settings.Secure.getUriFor(
Jeff Sharkey6e544612017-02-20 11:02:26 -0700830 Settings.Secure.DOUBLE_TAP_TO_WAKE),
831 false, mSettingsObserver, UserHandle.USER_ALL);
Christine Franks732c0432017-06-23 18:12:46 -0700832 resolver.registerContentObserver(Settings.Global.getUriFor(
833 Settings.Global.DEVICE_DEMO_MODE),
834 false, mSettingsObserver, UserHandle.USER_SYSTEM);
Jeff Sharkey6e544612017-02-20 11:02:26 -0700835 IVrManager vrManager = (IVrManager) getBinderService(Context.VR_SERVICE);
836 if (vrManager != null) {
837 try {
838 vrManager.registerListener(mVrStateCallbacks);
839 } catch (RemoteException e) {
840 Slog.e(TAG, "Failed to register VR mode state listener: " + e);
841 }
842 }
843
Shibin George43f5de02016-07-06 02:12:10 +0530844 // Register for broadcasts from other components of the system.
845 IntentFilter filter = new IntentFilter();
846 filter.addAction(Intent.ACTION_BATTERY_CHANGED);
847 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
848 mContext.registerReceiver(new BatteryReceiver(), filter, null, mHandler);
849
850 filter = new IntentFilter();
851 filter.addAction(Intent.ACTION_DREAMING_STARTED);
852 filter.addAction(Intent.ACTION_DREAMING_STOPPED);
853 mContext.registerReceiver(new DreamReceiver(), filter, null, mHandler);
854
855 filter = new IntentFilter();
856 filter.addAction(Intent.ACTION_USER_SWITCHED);
857 mContext.registerReceiver(new UserSwitchedReceiver(), filter, null, mHandler);
858
859 filter = new IntentFilter();
860 filter.addAction(Intent.ACTION_DOCK_EVENT);
861 mContext.registerReceiver(new DockReceiver(), filter, null, mHandler);
Jeff Brown96307042012-07-27 15:51:34 -0700862 }
863
864 private void readConfigurationLocked() {
865 final Resources resources = mContext.getResources();
866
Jeff Brown037c33e2014-04-09 00:31:55 -0700867 mDecoupleHalAutoSuspendModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800868 com.android.internal.R.bool.config_powerDecoupleAutoSuspendModeFromDisplay);
Jeff Brown037c33e2014-04-09 00:31:55 -0700869 mDecoupleHalInteractiveModeFromDisplayConfig = resources.getBoolean(
Jeff Brown26875502014-01-30 21:47:47 -0800870 com.android.internal.R.bool.config_powerDecoupleInteractiveModeFromDisplay);
Jeff Brown96307042012-07-27 15:51:34 -0700871 mWakeUpWhenPluggedOrUnpluggedConfig = resources.getBoolean(
Joe Onorato6d747652010-10-11 15:15:31 -0700872 com.android.internal.R.bool.config_unplugTurnsOnScreen);
Bryce Lee584a4452014-10-21 15:55:55 -0700873 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig = resources.getBoolean(
874 com.android.internal.R.bool.config_allowTheaterModeWakeFromUnplug);
Jeff Brownec083212013-09-11 20:45:25 -0700875 mSuspendWhenScreenOffDueToProximityConfig = resources.getBoolean(
876 com.android.internal.R.bool.config_suspendWhenScreenOffDueToProximity);
Jeff Brown96307042012-07-27 15:51:34 -0700877 mDreamsSupportedConfig = resources.getBoolean(
John Spurlocked108f32012-10-18 16:49:24 -0400878 com.android.internal.R.bool.config_dreamsSupported);
879 mDreamsEnabledByDefaultConfig = resources.getBoolean(
880 com.android.internal.R.bool.config_dreamsEnabledByDefault);
881 mDreamsActivatedOnSleepByDefaultConfig = resources.getBoolean(
882 com.android.internal.R.bool.config_dreamsActivatedOnSleepByDefault);
883 mDreamsActivatedOnDockByDefaultConfig = resources.getBoolean(
884 com.android.internal.R.bool.config_dreamsActivatedOnDockByDefault);
Jeff Brown26875502014-01-30 21:47:47 -0800885 mDreamsEnabledOnBatteryConfig = resources.getBoolean(
886 com.android.internal.R.bool.config_dreamsEnabledOnBattery);
887 mDreamsBatteryLevelMinimumWhenPoweredConfig = resources.getInteger(
888 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenPowered);
889 mDreamsBatteryLevelMinimumWhenNotPoweredConfig = resources.getInteger(
890 com.android.internal.R.integer.config_dreamsBatteryLevelMinimumWhenNotPowered);
891 mDreamsBatteryLevelDrainCutoffConfig = resources.getInteger(
892 com.android.internal.R.integer.config_dreamsBatteryLevelDrainCutoff);
Lucas Dupin16cfe452018-02-08 13:14:50 -0800893 mDozeAfterScreenOff = resources.getBoolean(
Lucas Dupin5354cc02018-03-20 16:09:34 -0700894 com.android.internal.R.bool.config_dozeAfterScreenOffByDefault);
Jeff Brown27736f52014-05-20 17:17:10 -0700895 mMinimumScreenOffTimeoutConfig = resources.getInteger(
896 com.android.internal.R.integer.config_minimumScreenOffTimeout);
897 mMaximumScreenDimDurationConfig = resources.getInteger(
898 com.android.internal.R.integer.config_maximumScreenDimDuration);
899 mMaximumScreenDimRatioConfig = resources.getFraction(
900 com.android.internal.R.fraction.config_maximumScreenDimRatio, 1, 1);
Jason Monk27bbb2d2015-03-31 16:46:39 -0400901 mSupportsDoubleTapWakeConfig = resources.getBoolean(
902 com.android.internal.R.bool.config_supportDoubleTapWake);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800903 }
904
Jeff Brown96307042012-07-27 15:51:34 -0700905 private void updateSettingsLocked() {
906 final ContentResolver resolver = mContext.getContentResolver();
Jeff Brown7304c342012-05-11 18:42:42 -0700907
Jeff Brownd4935962012-09-25 13:27:20 -0700908 mDreamsEnabledSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400909 Settings.Secure.SCREENSAVER_ENABLED,
910 mDreamsEnabledByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700911 UserHandle.USER_CURRENT) != 0);
912 mDreamsActivateOnSleepSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400913 Settings.Secure.SCREENSAVER_ACTIVATE_ON_SLEEP,
914 mDreamsActivatedOnSleepByDefaultConfig ? 1 : 0,
Jeff Brownd4935962012-09-25 13:27:20 -0700915 UserHandle.USER_CURRENT) != 0);
Jeff Brownec6aa592012-10-17 20:30:25 -0700916 mDreamsActivateOnDockSetting = (Settings.Secure.getIntForUser(resolver,
John Spurlocked108f32012-10-18 16:49:24 -0400917 Settings.Secure.SCREENSAVER_ACTIVATE_ON_DOCK,
918 mDreamsActivatedOnDockByDefaultConfig ? 1 : 0,
Jeff Brownec6aa592012-10-17 20:30:25 -0700919 UserHandle.USER_CURRENT) != 0);
Jeff Brownd4935962012-09-25 13:27:20 -0700920 mScreenOffTimeoutSetting = Settings.System.getIntForUser(resolver,
921 Settings.System.SCREEN_OFF_TIMEOUT, DEFAULT_SCREEN_OFF_TIMEOUT,
922 UserHandle.USER_CURRENT);
Jeff Brown05af6ad2014-09-30 20:54:30 -0700923 mSleepTimeoutSetting = Settings.Secure.getIntForUser(resolver,
924 Settings.Secure.SLEEP_TIMEOUT, DEFAULT_SLEEP_TIMEOUT,
925 UserHandle.USER_CURRENT);
Christopher Tatead735322012-09-07 14:19:43 -0700926 mStayOnWhilePluggedInSetting = Settings.Global.getInt(resolver,
Jeff Brownd4935962012-09-25 13:27:20 -0700927 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, BatteryManager.BATTERY_PLUGGED_AC);
Bryce Lee584a4452014-10-21 15:55:55 -0700928 mTheaterModeEnabled = Settings.Global.getInt(mContext.getContentResolver(),
929 Settings.Global.THEATER_MODE_ON, 0) == 1;
Adrian Roos56021892017-02-27 20:25:09 +0100930 mAlwaysOnEnabled = mAmbientDisplayConfiguration.alwaysOnEnabled(UserHandle.USER_CURRENT);
Jeff Brown7304c342012-05-11 18:42:42 -0700931
Jason Monk27bbb2d2015-03-31 16:46:39 -0400932 if (mSupportsDoubleTapWakeConfig) {
933 boolean doubleTapWakeEnabled = Settings.Secure.getIntForUser(resolver,
934 Settings.Secure.DOUBLE_TAP_TO_WAKE, DEFAULT_DOUBLE_TAP_TO_WAKE,
935 UserHandle.USER_CURRENT) != 0;
936 if (doubleTapWakeEnabled != mDoubleTapWakeEnabled) {
937 mDoubleTapWakeEnabled = doubleTapWakeEnabled;
938 nativeSetFeature(POWER_FEATURE_DOUBLE_TAP_TO_WAKE, mDoubleTapWakeEnabled ? 1 : 0);
939 }
940 }
941
Christine Franks732c0432017-06-23 18:12:46 -0700942 final String retailDemoValue = UserManager.isDeviceInDemoMode(mContext) ? "1" : "0";
943 if (!retailDemoValue.equals(SystemProperties.get(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED))) {
944 SystemProperties.set(SYSTEM_PROPERTY_RETAIL_DEMO_ENABLED, retailDemoValue);
945 }
946
Jeff Brownd4935962012-09-25 13:27:20 -0700947 mScreenBrightnessModeSetting = Settings.System.getIntForUser(resolver,
Jeff Brown96307042012-07-27 15:51:34 -0700948 Settings.System.SCREEN_BRIGHTNESS_MODE,
Jeff Brownd4935962012-09-25 13:27:20 -0700949 Settings.System.SCREEN_BRIGHTNESS_MODE_MANUAL, UserHandle.USER_CURRENT);
Jeff Brown96307042012-07-27 15:51:34 -0700950
Dianne Hackborneb94fa72014-06-03 17:48:12 -0700951 mDirty |= DIRTY_SETTINGS;
952 }
953
Jeff Sharkey3dee8d62016-03-02 13:07:56 -0700954 private void postAfterBootCompleted(Runnable r) {
955 if (mBootCompleted) {
956 BackgroundThread.getHandler().post(r);
957 } else {
958 Slog.d(TAG, "Delaying runnable until system is booted");
959 mBootCompletedRunnables = ArrayUtils.appendElement(Runnable.class,
960 mBootCompletedRunnables, r);
961 }
962 }
963
Jeff Brown96307042012-07-27 15:51:34 -0700964 private void handleSettingsChangedLocked() {
965 updateSettingsLocked();
966 updatePowerStateLocked();
967 }
968
Dianne Hackborn713df152013-05-17 11:27:57 -0700969 private void acquireWakeLockInternal(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800970 WorkSource ws, String historyTag, int uid, int pid) {
Jeff Brown96307042012-07-27 15:51:34 -0700971 synchronized (mLock) {
972 if (DEBUG_SPEW) {
973 Slog.d(TAG, "acquireWakeLockInternal: lock=" + Objects.hashCode(lock)
974 + ", flags=0x" + Integer.toHexString(flags)
975 + ", tag=\"" + tag + "\", ws=" + ws + ", uid=" + uid + ", pid=" + pid);
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -0700976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800977
Jeff Brown96307042012-07-27 15:51:34 -0700978 WakeLock wakeLock;
979 int index = findWakeLockIndexLocked(lock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700980 boolean notifyAcquire;
Jeff Brown96307042012-07-27 15:51:34 -0700981 if (index >= 0) {
982 wakeLock = mWakeLocks.get(index);
983 if (!wakeLock.hasSameProperties(flags, tag, ws, uid, pid)) {
984 // Update existing wake lock. This shouldn't happen but is harmless.
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800985 notifyWakeLockChangingLocked(wakeLock, flags, tag, packageName,
986 uid, pid, ws, historyTag);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -0800987 wakeLock.updateProperties(flags, tag, packageName, ws, historyTag, uid, pid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 }
Dianne Hackborn0d192a92014-07-15 16:39:47 -0700989 notifyAcquire = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 } else {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -0700991 UidState state = mUidState.get(uid);
992 if (state == null) {
993 state = new UidState(uid);
994 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
995 mUidState.put(uid, state);
996 }
997 state.mNumWakeLocks++;
998 wakeLock = new WakeLock(lock, flags, tag, packageName, ws, historyTag, uid, pid,
999 state);
Jeff Brown96307042012-07-27 15:51:34 -07001000 try {
1001 lock.linkToDeath(wakeLock, 0);
1002 } catch (RemoteException ex) {
1003 throw new IllegalArgumentException("Wake lock is already dead.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 }
Jeff Brown96307042012-07-27 15:51:34 -07001005 mWakeLocks.add(wakeLock);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001006 setWakeLockDisabledStateLocked(wakeLock);
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001007 notifyAcquire = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001009
Jeff Brownc12035c2014-08-13 18:52:25 -07001010 applyWakeLockFlagsOnAcquireLocked(wakeLock, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001011 mDirty |= DIRTY_WAKE_LOCKS;
1012 updatePowerStateLocked();
Dianne Hackborn0d192a92014-07-15 16:39:47 -07001013 if (notifyAcquire) {
1014 // This needs to be done last so we are sure we have acquired the
1015 // kernel wake lock. Otherwise we have a race where the system may
1016 // go to sleep between the time we start the accounting in battery
1017 // stats and when we actually get around to telling the kernel to
1018 // stay awake.
1019 notifyWakeLockAcquiredLocked(wakeLock);
1020 }
Dianne Hackborn7e9f4eb2010-09-10 18:43:00 -07001021 }
1022 }
1023
Jeff Brownec083212013-09-11 20:45:25 -07001024 @SuppressWarnings("deprecation")
Craig Mautner6edb6db2012-11-20 18:21:12 -08001025 private static boolean isScreenLock(final WakeLock wakeLock) {
1026 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1027 case PowerManager.FULL_WAKE_LOCK:
1028 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1029 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1030 return true;
1031 }
1032 return false;
1033 }
1034
Jeff Brownc12035c2014-08-13 18:52:25 -07001035 private void applyWakeLockFlagsOnAcquireLocked(WakeLock wakeLock, int uid) {
Jeff Brown6eade792013-09-10 18:45:25 -07001036 if ((wakeLock.mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0
1037 && isScreenLock(wakeLock)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001038 String opPackageName;
1039 int opUid;
1040 if (wakeLock.mWorkSource != null && wakeLock.mWorkSource.getName(0) != null) {
1041 opPackageName = wakeLock.mWorkSource.getName(0);
1042 opUid = wakeLock.mWorkSource.get(0);
1043 } else {
1044 opPackageName = wakeLock.mPackageName;
1045 opUid = wakeLock.mWorkSource != null ? wakeLock.mWorkSource.get(0)
1046 : wakeLock.mOwnerUid;
1047 }
1048 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), wakeLock.mTag, opUid,
1049 opPackageName, opUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001050 }
1051 }
1052
Jeff Brown96307042012-07-27 15:51:34 -07001053 private void releaseWakeLockInternal(IBinder lock, int flags) {
1054 synchronized (mLock) {
Jeff Brown96307042012-07-27 15:51:34 -07001055 int index = findWakeLockIndexLocked(lock);
1056 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001057 if (DEBUG_SPEW) {
1058 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1059 + " [not found], flags=0x" + Integer.toHexString(flags));
1060 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 return;
1062 }
Mike Lockwood3333fa42009-10-26 14:50:42 -04001063
Jeff Brown96307042012-07-27 15:51:34 -07001064 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001065 if (DEBUG_SPEW) {
1066 Slog.d(TAG, "releaseWakeLockInternal: lock=" + Objects.hashCode(lock)
1067 + " [" + wakeLock.mTag + "], flags=0x" + Integer.toHexString(flags));
1068 }
1069
Michael Wright1208e272014-09-08 19:57:50 -07001070 if ((flags & PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001071 mRequestWaitForNegativeProximity = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
1073
Jeff Brown3edf5272014-08-14 19:25:14 -07001074 wakeLock.mLock.unlinkToDeath(wakeLock, 0);
1075 removeWakeLockLocked(wakeLock, index);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 }
1077 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001078
Jeff Brown96307042012-07-27 15:51:34 -07001079 private void handleWakeLockDeath(WakeLock wakeLock) {
1080 synchronized (mLock) {
1081 if (DEBUG_SPEW) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001082 Slog.d(TAG, "handleWakeLockDeath: lock=" + Objects.hashCode(wakeLock.mLock)
1083 + " [" + wakeLock.mTag + "]");
Jeff Brown96307042012-07-27 15:51:34 -07001084 }
1085
1086 int index = mWakeLocks.indexOf(wakeLock);
1087 if (index < 0) {
1088 return;
1089 }
1090
Jeff Brown3edf5272014-08-14 19:25:14 -07001091 removeWakeLockLocked(wakeLock, index);
Mike Lockwood3a74bd32011-08-12 13:55:22 -07001092 }
Jeff Brown00fa7bd2010-07-02 15:37:36 -07001093 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001094
Jeff Brown3edf5272014-08-14 19:25:14 -07001095 private void removeWakeLockLocked(WakeLock wakeLock, int index) {
1096 mWakeLocks.remove(index);
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07001097 UidState state = wakeLock.mUidState;
1098 state.mNumWakeLocks--;
1099 if (state.mNumWakeLocks <= 0 &&
1100 state.mProcState == ActivityManager.PROCESS_STATE_NONEXISTENT) {
1101 mUidState.remove(state.mUid);
1102 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001103 notifyWakeLockReleasedLocked(wakeLock);
1104
1105 applyWakeLockFlagsOnReleaseLocked(wakeLock);
1106 mDirty |= DIRTY_WAKE_LOCKS;
1107 updatePowerStateLocked();
1108 }
1109
Jeff Brown96307042012-07-27 15:51:34 -07001110 private void applyWakeLockFlagsOnReleaseLocked(WakeLock wakeLock) {
Jeff Brown6eade792013-09-10 18:45:25 -07001111 if ((wakeLock.mFlags & PowerManager.ON_AFTER_RELEASE) != 0
1112 && isScreenLock(wakeLock)) {
Jeff Brown96307042012-07-27 15:51:34 -07001113 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
1114 PowerManager.USER_ACTIVITY_EVENT_OTHER,
1115 PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS,
1116 wakeLock.mOwnerUid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 }
1119
Dianne Hackbornd953c532014-08-16 18:17:38 -07001120 private void updateWakeLockWorkSourceInternal(IBinder lock, WorkSource ws, String historyTag,
1121 int callingUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001122 synchronized (mLock) {
1123 int index = findWakeLockIndexLocked(lock);
1124 if (index < 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08001125 if (DEBUG_SPEW) {
1126 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1127 + " [not found], ws=" + ws);
1128 }
Dianne Hackbornd953c532014-08-16 18:17:38 -07001129 throw new IllegalArgumentException("Wake lock not active: " + lock
1130 + " from uid " + callingUid);
Jeff Brown96307042012-07-27 15:51:34 -07001131 }
1132
1133 WakeLock wakeLock = mWakeLocks.get(index);
Jeff Brown27f7a862012-12-12 15:43:31 -08001134 if (DEBUG_SPEW) {
1135 Slog.d(TAG, "updateWakeLockWorkSourceInternal: lock=" + Objects.hashCode(lock)
1136 + " [" + wakeLock.mTag + "], ws=" + ws);
1137 }
1138
Jeff Brown96307042012-07-27 15:51:34 -07001139 if (!wakeLock.hasSameWorkSource(ws)) {
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001140 notifyWakeLockChangingLocked(wakeLock, wakeLock.mFlags, wakeLock.mTag,
1141 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
Dianne Hackborn4590e522014-03-24 13:36:46 -07001142 ws, historyTag);
1143 wakeLock.mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07001144 wakeLock.updateWorkSource(ws);
Jeff Brown96307042012-07-27 15:51:34 -07001145 }
1146 }
1147 }
1148
1149 private int findWakeLockIndexLocked(IBinder lock) {
1150 final int count = mWakeLocks.size();
1151 for (int i = 0; i < count; i++) {
1152 if (mWakeLocks.get(i).mLock == lock) {
1153 return i;
1154 }
1155 }
1156 return -1;
1157 }
1158
1159 private void notifyWakeLockAcquiredLocked(WakeLock wakeLock) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07001160 if (mSystemReady && !wakeLock.mDisabled) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001161 wakeLock.mNotifiedAcquired = true;
1162 mNotifier.onWakeLockAcquired(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001163 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1164 wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001165 restartNofifyLongTimerLocked(wakeLock);
1166 }
1167 }
1168
1169 private void enqueueNotifyLongMsgLocked(long time) {
1170 mNotifyLongScheduled = time;
1171 Message msg = mHandler.obtainMessage(MSG_CHECK_FOR_LONG_WAKELOCKS);
1172 msg.setAsynchronous(true);
1173 mHandler.sendMessageAtTime(msg, time);
1174 }
1175
1176 private void restartNofifyLongTimerLocked(WakeLock wakeLock) {
1177 wakeLock.mAcquireTime = SystemClock.uptimeMillis();
1178 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1179 == PowerManager.PARTIAL_WAKE_LOCK && mNotifyLongScheduled == 0) {
1180 enqueueNotifyLongMsgLocked(wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL);
1181 }
1182 }
1183
1184 private void notifyWakeLockLongStartedLocked(WakeLock wakeLock) {
1185 if (mSystemReady && !wakeLock.mDisabled) {
1186 wakeLock.mNotifiedLong = true;
1187 mNotifier.onLongPartialWakeLockStart(wakeLock.mTag, wakeLock.mOwnerUid,
1188 wakeLock.mWorkSource, wakeLock.mHistoryTag);
1189 }
1190 }
1191
1192 private void notifyWakeLockLongFinishedLocked(WakeLock wakeLock) {
1193 if (wakeLock.mNotifiedLong) {
1194 wakeLock.mNotifiedLong = false;
1195 mNotifier.onLongPartialWakeLockFinish(wakeLock.mTag, wakeLock.mOwnerUid,
1196 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Jeff Brown96307042012-07-27 15:51:34 -07001197 }
1198 }
1199
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001200 private void notifyWakeLockChangingLocked(WakeLock wakeLock, int flags, String tag,
1201 String packageName, int uid, int pid, WorkSource ws, String historyTag) {
1202 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1203 mNotifier.onWakeLockChanging(wakeLock.mFlags, wakeLock.mTag, wakeLock.mPackageName,
1204 wakeLock.mOwnerUid, wakeLock.mOwnerPid, wakeLock.mWorkSource,
1205 wakeLock.mHistoryTag, flags, tag, packageName, uid, pid, ws, historyTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001206 notifyWakeLockLongFinishedLocked(wakeLock);
1207 // Changing the wake lock will count as releasing the old wake lock(s) and
1208 // acquiring the new ones... we do this because otherwise once a wakelock
1209 // becomes long, if we just continued to treat it as long we can get in to
1210 // situations where we spam battery stats with every following change to it.
1211 restartNofifyLongTimerLocked(wakeLock);
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001212 }
1213 }
1214
Jeff Brown96307042012-07-27 15:51:34 -07001215 private void notifyWakeLockReleasedLocked(WakeLock wakeLock) {
Dianne Hackborn713df152013-05-17 11:27:57 -07001216 if (mSystemReady && wakeLock.mNotifiedAcquired) {
1217 wakeLock.mNotifiedAcquired = false;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001218 wakeLock.mAcquireTime = 0;
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07001219 mNotifier.onWakeLockReleased(wakeLock.mFlags, wakeLock.mTag,
1220 wakeLock.mPackageName, wakeLock.mOwnerUid, wakeLock.mOwnerPid,
1221 wakeLock.mWorkSource, wakeLock.mHistoryTag);
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001222 notifyWakeLockLongFinishedLocked(wakeLock);
Jeff Brown96307042012-07-27 15:51:34 -07001223 }
1224 }
1225
Jeff Brownec083212013-09-11 20:45:25 -07001226 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001227 private boolean isWakeLockLevelSupportedInternal(int level) {
1228 synchronized (mLock) {
1229 switch (level) {
1230 case PowerManager.PARTIAL_WAKE_LOCK:
1231 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1232 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1233 case PowerManager.FULL_WAKE_LOCK:
Jeff Brown26875502014-01-30 21:47:47 -08001234 case PowerManager.DOZE_WAKE_LOCK:
Jeff Brownc4bd42c2015-06-12 18:00:11 -07001235 case PowerManager.DRAW_WAKE_LOCK:
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001236 return true;
Jeff Brown96307042012-07-27 15:51:34 -07001237
1238 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
Jeff Brown131206b2014-04-08 17:27:14 -07001239 return mSystemReady && mDisplayManagerInternal.isProximitySensorAvailable();
Jeff Brown96307042012-07-27 15:51:34 -07001240
1241 default:
1242 return false;
1243 }
1244 }
1245 }
1246
Jeff Brown96307042012-07-27 15:51:34 -07001247 // Called from native code.
1248 private void userActivityFromNative(long eventTime, int event, int flags) {
1249 userActivityInternal(eventTime, event, flags, Process.SYSTEM_UID);
1250 }
1251
1252 private void userActivityInternal(long eventTime, int event, int flags, int uid) {
1253 synchronized (mLock) {
1254 if (userActivityNoUpdateLocked(eventTime, event, flags, uid)) {
1255 updatePowerStateLocked();
1256 }
1257 }
1258 }
1259
1260 private boolean userActivityNoUpdateLocked(long eventTime, int event, int flags, int uid) {
1261 if (DEBUG_SPEW) {
1262 Slog.d(TAG, "userActivityNoUpdateLocked: eventTime=" + eventTime
1263 + ", event=" + event + ", flags=0x" + Integer.toHexString(flags)
1264 + ", uid=" + uid);
1265 }
1266
1267 if (eventTime < mLastSleepTime || eventTime < mLastWakeTime
Jeff Brown26875502014-01-30 21:47:47 -08001268 || !mBootCompleted || !mSystemReady) {
Jeff Brown96307042012-07-27 15:51:34 -07001269 return false;
1270 }
1271
Jeff Brown3edf5272014-08-14 19:25:14 -07001272 Trace.traceBegin(Trace.TRACE_TAG_POWER, "userActivity");
1273 try {
Jeff Brown0a571122014-08-21 21:50:43 -07001274 if (eventTime > mLastInteractivePowerHintTime) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07001275 powerHintInternal(PowerHint.INTERACTION, 0);
Jeff Brown0a571122014-08-21 21:50:43 -07001276 mLastInteractivePowerHintTime = eventTime;
1277 }
1278
Jeff Brown3edf5272014-08-14 19:25:14 -07001279 mNotifier.onUserActivity(event, uid);
Jeff Brown96307042012-07-27 15:51:34 -07001280
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001281 if (mUserInactiveOverrideFromWindowManager) {
1282 mUserInactiveOverrideFromWindowManager = false;
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001283 mOverriddenTimeout = -1;
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001284 }
1285
Jeff Brown0a571122014-08-21 21:50:43 -07001286 if (mWakefulness == WAKEFULNESS_ASLEEP
1287 || mWakefulness == WAKEFULNESS_DOZING
1288 || (flags & PowerManager.USER_ACTIVITY_FLAG_INDIRECT) != 0) {
1289 return false;
1290 }
1291
Pavel Grafov28939982017-10-03 15:11:52 +01001292 maybeUpdateForegroundProfileLastActivityLocked(eventTime);
1293
Jeff Brown3edf5272014-08-14 19:25:14 -07001294 if ((flags & PowerManager.USER_ACTIVITY_FLAG_NO_CHANGE_LIGHTS) != 0) {
1295 if (eventTime > mLastUserActivityTimeNoChangeLights
1296 && eventTime > mLastUserActivityTime) {
1297 mLastUserActivityTimeNoChangeLights = eventTime;
1298 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001299 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1300 mDirty |= DIRTY_QUIESCENT;
1301 }
1302
Jeff Brown3edf5272014-08-14 19:25:14 -07001303 return true;
1304 }
1305 } else {
1306 if (eventTime > mLastUserActivityTime) {
1307 mLastUserActivityTime = eventTime;
1308 mDirty |= DIRTY_USER_ACTIVITY;
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08001309 if (event == PowerManager.USER_ACTIVITY_EVENT_BUTTON) {
1310 mDirty |= DIRTY_QUIESCENT;
1311 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001312 return true;
1313 }
Jeff Brown96307042012-07-27 15:51:34 -07001314 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001315 } finally {
1316 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001317 }
1318 return false;
1319 }
1320
Pavel Grafov28939982017-10-03 15:11:52 +01001321 private void maybeUpdateForegroundProfileLastActivityLocked(long eventTime) {
1322 final ProfilePowerState profile = mProfilePowerState.get(mForegroundProfile);
1323 if (profile != null && eventTime > profile.mLastUserActivityTime) {
1324 profile.mLastUserActivityTime = eventTime;
1325 }
1326 }
1327
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001328 private void wakeUpInternal(long eventTime, String reason, int uid, String opPackageName,
1329 int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001330 synchronized (mLock) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001331 if (wakeUpNoUpdateLocked(eventTime, reason, uid, opPackageName, opUid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001332 updatePowerStateLocked();
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001333 }
1334 }
Jeff Brown96307042012-07-27 15:51:34 -07001335 }
Dianne Hackbornbeae3bd2011-09-21 10:55:12 -07001336
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001337 private boolean wakeUpNoUpdateLocked(long eventTime, String reason, int reasonUid,
1338 String opPackageName, int opUid) {
Jeff Brown96307042012-07-27 15:51:34 -07001339 if (DEBUG_SPEW) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001340 Slog.d(TAG, "wakeUpNoUpdateLocked: eventTime=" + eventTime + ", uid=" + reasonUid);
Joe Onorato60607a92010-10-23 14:49:30 -07001341 }
Jeff Brown96307042012-07-27 15:51:34 -07001342
1343 if (eventTime < mLastSleepTime || mWakefulness == WAKEFULNESS_AWAKE
1344 || !mBootCompleted || !mSystemReady) {
1345 return false;
1346 }
1347
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001348 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1349
Jeff Brown3edf5272014-08-14 19:25:14 -07001350 Trace.traceBegin(Trace.TRACE_TAG_POWER, "wakeUp");
1351 try {
1352 switch (mWakefulness) {
1353 case WAKEFULNESS_ASLEEP:
Adrian Roos7ac5a0b2017-05-17 14:23:54 -07001354 Slog.i(TAG, "Waking up from sleep (uid=" + reasonUid + " reason=" + reason
1355 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001356 break;
1357 case WAKEFULNESS_DREAMING:
Adrian Roos7ac5a0b2017-05-17 14:23:54 -07001358 Slog.i(TAG, "Waking up from dream (uid=" + reasonUid + " reason=" + reason
1359 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001360 break;
1361 case WAKEFULNESS_DOZING:
Adrian Roos7ac5a0b2017-05-17 14:23:54 -07001362 Slog.i(TAG, "Waking up from dozing (uid=" + reasonUid + " reason=" + reason
1363 + ")...");
Jeff Brown3edf5272014-08-14 19:25:14 -07001364 break;
1365 }
1366
1367 mLastWakeTime = eventTime;
Jeff Brownfbe96702014-11-19 18:30:58 -08001368 setWakefulnessLocked(WAKEFULNESS_AWAKE, 0);
Jeff Brown3edf5272014-08-14 19:25:14 -07001369
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001370 mNotifier.onWakeUp(reason, reasonUid, opPackageName, opUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001371 userActivityNoUpdateLocked(
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001372 eventTime, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, reasonUid);
Jeff Brown3edf5272014-08-14 19:25:14 -07001373 } finally {
1374 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown96307042012-07-27 15:51:34 -07001375 }
Jeff Brown96307042012-07-27 15:51:34 -07001376 return true;
1377 }
1378
Jeff Brownc12035c2014-08-13 18:52:25 -07001379 private void goToSleepInternal(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001380 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001381 if (goToSleepNoUpdateLocked(eventTime, reason, flags, uid)) {
Jeff Brown96307042012-07-27 15:51:34 -07001382 updatePowerStateLocked();
1383 }
1384 }
1385 }
1386
Jeff Brown26875502014-01-30 21:47:47 -08001387 // This method is called goToSleep for historical reasons but we actually start
1388 // dozing before really going to sleep.
Jeff Brownec083212013-09-11 20:45:25 -07001389 @SuppressWarnings("deprecation")
Jeff Brownc12035c2014-08-13 18:52:25 -07001390 private boolean goToSleepNoUpdateLocked(long eventTime, int reason, int flags, int uid) {
Jeff Brown96307042012-07-27 15:51:34 -07001391 if (DEBUG_SPEW) {
Jeff Brown6d8fd272014-05-20 21:24:38 -07001392 Slog.d(TAG, "goToSleepNoUpdateLocked: eventTime=" + eventTime
Jeff Brownc12035c2014-08-13 18:52:25 -07001393 + ", reason=" + reason + ", flags=" + flags + ", uid=" + uid);
Jeff Brown96307042012-07-27 15:51:34 -07001394 }
1395
Jeff Brown26875502014-01-30 21:47:47 -08001396 if (eventTime < mLastWakeTime
1397 || mWakefulness == WAKEFULNESS_ASLEEP
1398 || mWakefulness == WAKEFULNESS_DOZING
Jeff Brown96307042012-07-27 15:51:34 -07001399 || !mBootCompleted || !mSystemReady) {
1400 return false;
1401 }
1402
Jeff Brown3edf5272014-08-14 19:25:14 -07001403 Trace.traceBegin(Trace.TRACE_TAG_POWER, "goToSleep");
1404 try {
1405 switch (reason) {
1406 case PowerManager.GO_TO_SLEEP_REASON_DEVICE_ADMIN:
1407 Slog.i(TAG, "Going to sleep due to device administration policy "
1408 + "(uid " + uid +")...");
1409 break;
1410 case PowerManager.GO_TO_SLEEP_REASON_TIMEOUT:
1411 Slog.i(TAG, "Going to sleep due to screen timeout (uid " + uid +")...");
1412 break;
1413 case PowerManager.GO_TO_SLEEP_REASON_LID_SWITCH:
1414 Slog.i(TAG, "Going to sleep due to lid switch (uid " + uid +")...");
1415 break;
1416 case PowerManager.GO_TO_SLEEP_REASON_POWER_BUTTON:
1417 Slog.i(TAG, "Going to sleep due to power button (uid " + uid +")...");
1418 break;
Filip Gruszczynski9779e122015-03-13 17:39:31 -07001419 case PowerManager.GO_TO_SLEEP_REASON_SLEEP_BUTTON:
1420 Slog.i(TAG, "Going to sleep due to sleep button (uid " + uid +")...");
1421 break;
Jeff Brown3edf5272014-08-14 19:25:14 -07001422 case PowerManager.GO_TO_SLEEP_REASON_HDMI:
1423 Slog.i(TAG, "Going to sleep due to HDMI standby (uid " + uid +")...");
1424 break;
Eugene Suslaf9a651d2017-10-11 12:06:27 -07001425 case PowerManager.GO_TO_SLEEP_REASON_ACCESSIBILITY:
1426 Slog.i(TAG, "Going to sleep by an accessibility service request (uid "
1427 + uid +")...");
1428 break;
Jeff Brown3edf5272014-08-14 19:25:14 -07001429 default:
1430 Slog.i(TAG, "Going to sleep by application request (uid " + uid +")...");
1431 reason = PowerManager.GO_TO_SLEEP_REASON_APPLICATION;
Jeff Brown96307042012-07-27 15:51:34 -07001432 break;
1433 }
Jeff Brown6d8fd272014-05-20 21:24:38 -07001434
Jeff Brown3edf5272014-08-14 19:25:14 -07001435 mLastSleepTime = eventTime;
Jeff Brown3edf5272014-08-14 19:25:14 -07001436 mSandmanSummoned = true;
Jeff Brownfbe96702014-11-19 18:30:58 -08001437 setWakefulnessLocked(WAKEFULNESS_DOZING, reason);
Jeff Brown3edf5272014-08-14 19:25:14 -07001438
1439 // Report the number of wake locks that will be cleared by going to sleep.
1440 int numWakeLocksCleared = 0;
1441 final int numWakeLocks = mWakeLocks.size();
1442 for (int i = 0; i < numWakeLocks; i++) {
1443 final WakeLock wakeLock = mWakeLocks.get(i);
1444 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1445 case PowerManager.FULL_WAKE_LOCK:
1446 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1447 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1448 numWakeLocksCleared += 1;
1449 break;
1450 }
1451 }
Michael Wrightb55e3a12018-03-06 15:14:06 +00001452 EventLogTags.writePowerSleepRequested(numWakeLocksCleared);
Jeff Brown3edf5272014-08-14 19:25:14 -07001453
1454 // Skip dozing if requested.
1455 if ((flags & PowerManager.GO_TO_SLEEP_FLAG_NO_DOZE) != 0) {
1456 reallyGoToSleepNoUpdateLocked(eventTime, uid);
1457 }
1458 } finally {
1459 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Jeff Brown6d8fd272014-05-20 21:24:38 -07001460 }
Jeff Brown96307042012-07-27 15:51:34 -07001461 return true;
1462 }
1463
Jeff Brownc12035c2014-08-13 18:52:25 -07001464 private void napInternal(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001465 synchronized (mLock) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001466 if (napNoUpdateLocked(eventTime, uid)) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001467 updatePowerStateLocked();
1468 }
1469 }
1470 }
1471
Jeff Brownc12035c2014-08-13 18:52:25 -07001472 private boolean napNoUpdateLocked(long eventTime, int uid) {
Jeff Brown62c82e42012-09-26 01:30:41 -07001473 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001474 Slog.d(TAG, "napNoUpdateLocked: eventTime=" + eventTime + ", uid=" + uid);
Jeff Brown62c82e42012-09-26 01:30:41 -07001475 }
1476
1477 if (eventTime < mLastWakeTime || mWakefulness != WAKEFULNESS_AWAKE
1478 || !mBootCompleted || !mSystemReady) {
1479 return false;
1480 }
1481
Jeff Brown3edf5272014-08-14 19:25:14 -07001482 Trace.traceBegin(Trace.TRACE_TAG_POWER, "nap");
1483 try {
1484 Slog.i(TAG, "Nap time (uid " + uid +")...");
Jeff Brown62c82e42012-09-26 01:30:41 -07001485
Jeff Brown3edf5272014-08-14 19:25:14 -07001486 mSandmanSummoned = true;
Jeff Brownfbe96702014-11-19 18:30:58 -08001487 setWakefulnessLocked(WAKEFULNESS_DREAMING, 0);
Jeff Brown3edf5272014-08-14 19:25:14 -07001488 } finally {
1489 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1490 }
Jeff Brown26875502014-01-30 21:47:47 -08001491 return true;
1492 }
1493
1494 // Done dozing, drop everything and go to sleep.
Jeff Brownc12035c2014-08-13 18:52:25 -07001495 private boolean reallyGoToSleepNoUpdateLocked(long eventTime, int uid) {
Jeff Brown26875502014-01-30 21:47:47 -08001496 if (DEBUG_SPEW) {
Jeff Brownc12035c2014-08-13 18:52:25 -07001497 Slog.d(TAG, "reallyGoToSleepNoUpdateLocked: eventTime=" + eventTime
1498 + ", uid=" + uid);
Jeff Brown26875502014-01-30 21:47:47 -08001499 }
1500
1501 if (eventTime < mLastWakeTime || mWakefulness == WAKEFULNESS_ASLEEP
1502 || !mBootCompleted || !mSystemReady) {
1503 return false;
1504 }
1505
Jeff Brown3edf5272014-08-14 19:25:14 -07001506 Trace.traceBegin(Trace.TRACE_TAG_POWER, "reallyGoToSleep");
1507 try {
1508 Slog.i(TAG, "Sleeping (uid " + uid +")...");
Jeff Brown26875502014-01-30 21:47:47 -08001509
Jeff Brownfbe96702014-11-19 18:30:58 -08001510 setWakefulnessLocked(WAKEFULNESS_ASLEEP, PowerManager.GO_TO_SLEEP_REASON_TIMEOUT);
Jeff Brown3edf5272014-08-14 19:25:14 -07001511 } finally {
1512 Trace.traceEnd(Trace.TRACE_TAG_POWER);
1513 }
Jeff Brown62c82e42012-09-26 01:30:41 -07001514 return true;
1515 }
1516
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001517 @VisibleForTesting
1518 void setWakefulnessLocked(int wakefulness, int reason) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001519 if (mWakefulness != wakefulness) {
Jeff Brownfbe96702014-11-19 18:30:58 -08001520 mWakefulness = wakefulness;
1521 mWakefulnessChanging = true;
1522 mDirty |= DIRTY_WAKEFULNESS;
Santos Cordon21e9f2b2017-09-13 11:59:39 -07001523 if (mNotifier != null) {
1524 mNotifier.onWakefulnessChangeStarted(wakefulness, reason);
1525 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001526 }
1527 }
1528
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001529 /**
1530 * Logs the time the device would have spent awake before user activity timeout,
1531 * had the system not been told the user was inactive.
1532 */
1533 private void logSleepTimeoutRecapturedLocked() {
1534 final long now = SystemClock.uptimeMillis();
1535 final long savedWakeTimeMs = mOverriddenTimeout - now;
1536 if (savedWakeTimeMs >= 0) {
Michael Wrightb55e3a12018-03-06 15:14:06 +00001537 EventLogTags.writePowerSoftSleepRequested(savedWakeTimeMs);
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001538 mOverriddenTimeout = -1;
1539 }
1540 }
1541
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001542 private void logScreenOn() {
1543 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, TRACE_SCREEN_ON, 0);
1544
1545 final int latencyMs = (int) (SystemClock.uptimeMillis() - mLastWakeTime);
1546
1547 LogMaker log = new LogMaker(MetricsEvent.SCREEN);
1548 log.setType(MetricsEvent.TYPE_OPEN);
1549 log.setSubtype(0); // not user initiated
1550 log.setLatency(latencyMs); // How long it took.
1551 MetricsLogger.action(log);
1552 EventLogTags.writePowerScreenState(1, 0, 0, 0, latencyMs);
1553
1554 if (latencyMs >= SCREEN_ON_LATENCY_WARNING_MS) {
1555 Slog.w(TAG, "Screen on took " + latencyMs+ " ms");
1556 }
1557 }
1558
Jeff Brown416c49c2015-05-26 19:50:18 -07001559 private void finishWakefulnessChangeIfNeededLocked() {
1560 if (mWakefulnessChanging && mDisplayReady) {
1561 if (mWakefulness == WAKEFULNESS_DOZING
1562 && (mWakeLockSummary & WAKE_LOCK_DOZE) == 0) {
1563 return; // wait until dream has enabled dozing
1564 }
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07001565 if (mWakefulness == WAKEFULNESS_DOZING || mWakefulness == WAKEFULNESS_ASLEEP) {
1566 logSleepTimeoutRecapturedLocked();
1567 }
Makoto Onuki5ab5e1d2017-04-14 17:04:26 -07001568 if (mWakefulness == WAKEFULNESS_AWAKE) {
1569 logScreenOn();
1570 }
Jeff Brownfbe96702014-11-19 18:30:58 -08001571 mWakefulnessChanging = false;
Jeff Brown416c49c2015-05-26 19:50:18 -07001572 mNotifier.onWakefulnessChangeFinished();
Jeff Brown037c33e2014-04-09 00:31:55 -07001573 }
1574 }
1575
Jeff Brown96307042012-07-27 15:51:34 -07001576 /**
1577 * Updates the global power state based on dirty bits recorded in mDirty.
1578 *
1579 * This is the main function that performs power state transitions.
1580 * We centralize them here so that we can recompute the power state completely
1581 * each time something important changes, and ensure that we do it the same
1582 * way each time. The point is to gather all of the transition logic here.
1583 */
1584 private void updatePowerStateLocked() {
1585 if (!mSystemReady || mDirty == 0) {
The Android Open Source Project10592532009-03-18 17:39:46 -07001586 return;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
Jeff Brown2d8a3902014-03-11 23:02:35 -07001588 if (!Thread.holdsLock(mLock)) {
1589 Slog.wtf(TAG, "Power manager lock was not held when calling updatePowerStateLocked");
1590 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001591
Jeff Brown3edf5272014-08-14 19:25:14 -07001592 Trace.traceBegin(Trace.TRACE_TAG_POWER, "updatePowerState");
1593 try {
1594 // Phase 0: Basic state updates.
1595 updateIsPoweredLocked(mDirty);
1596 updateStayOnLocked(mDirty);
Jeff Brown7b5be5e2014-11-12 18:45:31 -08001597 updateScreenBrightnessBoostLocked(mDirty);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001598
Jeff Brown3edf5272014-08-14 19:25:14 -07001599 // Phase 1: Update wakefulness.
1600 // Loop because the wake lock and user activity computations are influenced
1601 // by changes in wakefulness.
1602 final long now = SystemClock.uptimeMillis();
1603 int dirtyPhase2 = 0;
1604 for (;;) {
1605 int dirtyPhase1 = mDirty;
1606 dirtyPhase2 |= dirtyPhase1;
1607 mDirty = 0;
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001608
Jeff Brown3edf5272014-08-14 19:25:14 -07001609 updateWakeLockSummaryLocked(dirtyPhase1);
1610 updateUserActivitySummaryLocked(now, dirtyPhase1);
1611 if (!updateWakefulnessLocked(dirtyPhase1)) {
1612 break;
1613 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001614 }
Jeff Brown3edf5272014-08-14 19:25:14 -07001615
Pavel Grafov28939982017-10-03 15:11:52 +01001616 // Phase 2: Lock profiles that became inactive/not kept awake.
1617 updateProfilesLocked(now);
Jeff Brown3edf5272014-08-14 19:25:14 -07001618
Pavel Grafov28939982017-10-03 15:11:52 +01001619 // Phase 3: Update display power state.
1620 final boolean displayBecameReady = updateDisplayPowerStateLocked(dirtyPhase2);
1621
1622 // Phase 4: Update dream state (depends on display ready signal).
Jeff Brown2175e9c2014-09-12 16:11:07 -07001623 updateDreamLocked(dirtyPhase2, displayBecameReady);
1624
Pavel Grafov28939982017-10-03 15:11:52 +01001625 // Phase 5: Send notifications, if needed.
Jeff Brown416c49c2015-05-26 19:50:18 -07001626 finishWakefulnessChangeIfNeededLocked();
Jeff Brown3edf5272014-08-14 19:25:14 -07001627
Pavel Grafov28939982017-10-03 15:11:52 +01001628 // Phase 6: Update suspend blocker.
Jeff Brown3edf5272014-08-14 19:25:14 -07001629 // Because we might release the last suspend blocker here, we need to make sure
1630 // we finished everything else first!
1631 updateSuspendBlockerLocked();
1632 } finally {
1633 Trace.traceEnd(Trace.TRACE_TAG_POWER);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
Jeff Brown96307042012-07-27 15:51:34 -07001635 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08001636
Jim Miller92e66dd2012-02-21 18:57:12 -08001637 /**
Pavel Grafov28939982017-10-03 15:11:52 +01001638 * Check profile timeouts and notify profiles that should be locked.
1639 */
1640 private void updateProfilesLocked(long now) {
1641 final int numProfiles = mProfilePowerState.size();
1642 for (int i = 0; i < numProfiles; i++) {
1643 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1644 if (isProfileBeingKeptAwakeLocked(profile, now)) {
1645 profile.mLockingNotified = false;
1646 } else if (!profile.mLockingNotified) {
1647 profile.mLockingNotified = true;
1648 mNotifier.onProfileTimeout(profile.mUserId);
1649 }
1650 }
1651 }
1652
1653 private boolean isProfileBeingKeptAwakeLocked(ProfilePowerState profile, long now) {
1654 return (profile.mLastUserActivityTime + profile.mScreenOffTimeout > now)
1655 || (profile.mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
1656 || (mProximityPositive &&
1657 (profile.mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
1658 }
1659
1660 /**
Jeff Brown96307042012-07-27 15:51:34 -07001661 * Updates the value of mIsPowered.
1662 * Sets DIRTY_IS_POWERED if a change occurred.
Jim Miller92e66dd2012-02-21 18:57:12 -08001663 */
Jeff Brown96307042012-07-27 15:51:34 -07001664 private void updateIsPoweredLocked(int dirty) {
1665 if ((dirty & DIRTY_BATTERY_STATE) != 0) {
Jeff Brownf3fb8952012-10-02 20:57:05 -07001666 final boolean wasPowered = mIsPowered;
1667 final int oldPlugType = mPlugType;
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001668 final boolean oldLevelLow = mBatteryLevelLow;
Jeff Brown21392762014-06-13 19:00:36 -07001669 mIsPowered = mBatteryManagerInternal.isPowered(BatteryManager.BATTERY_PLUGGED_ANY);
1670 mPlugType = mBatteryManagerInternal.getPlugType();
1671 mBatteryLevel = mBatteryManagerInternal.getBatteryLevel();
1672 mBatteryLevelLow = mBatteryManagerInternal.getBatteryLevelLow();
Jeff Browna4d82042012-10-02 19:11:19 -07001673
Jeff Brown26875502014-01-30 21:47:47 -08001674 if (DEBUG_SPEW) {
Jeff Browna4d82042012-10-02 19:11:19 -07001675 Slog.d(TAG, "updateIsPoweredLocked: wasPowered=" + wasPowered
Jeff Brownf3fb8952012-10-02 20:57:05 -07001676 + ", mIsPowered=" + mIsPowered
1677 + ", oldPlugType=" + oldPlugType
Jeff Brown016ff142012-10-15 16:47:22 -07001678 + ", mPlugType=" + mPlugType
1679 + ", mBatteryLevel=" + mBatteryLevel);
Jeff Browna4d82042012-10-02 19:11:19 -07001680 }
Jim Miller92e66dd2012-02-21 18:57:12 -08001681
Jeff Brownf3fb8952012-10-02 20:57:05 -07001682 if (wasPowered != mIsPowered || oldPlugType != mPlugType) {
Jeff Brown96307042012-07-27 15:51:34 -07001683 mDirty |= DIRTY_IS_POWERED;
1684
Jeff Brown3b971592013-01-09 18:46:37 -08001685 // Update wireless dock detection state.
1686 final boolean dockedOnWirelessCharger = mWirelessChargerDetector.update(
Beverlyfcaab292018-03-19 10:42:06 -04001687 mIsPowered, mPlugType);
Jeff Brown3b971592013-01-09 18:46:37 -08001688
Jeff Brown96307042012-07-27 15:51:34 -07001689 // Treat plugging and unplugging the devices as a user activity.
1690 // Users find it disconcerting when they plug or unplug the device
1691 // and it shuts off right away.
1692 // Some devices also wake the device when plugged or unplugged because
1693 // they don't have a charging LED.
1694 final long now = SystemClock.uptimeMillis();
Jeff Brown3b971592013-01-09 18:46:37 -08001695 if (shouldWakeUpWhenPluggedOrUnpluggedLocked(wasPowered, oldPlugType,
1696 dockedOnWirelessCharger)) {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07001697 wakeUpNoUpdateLocked(now, "android.server.power:POWER", Process.SYSTEM_UID,
1698 mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown96307042012-07-27 15:51:34 -07001699 }
1700 userActivityNoUpdateLocked(
1701 now, PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Brown84e27562012-12-07 13:56:34 -08001702
Beverlyac32c9a2018-01-31 16:10:41 -05001703 // only play charging sounds if boot is completed so charging sounds don't play
1704 // with potential notification sounds
1705 if (mBootCompleted) {
1706 if (mIsPowered && !BatteryManager.isPlugWired(oldPlugType)
1707 && BatteryManager.isPlugWired(mPlugType)) {
1708 mNotifier.onWiredChargingStarted();
1709 } else if (dockedOnWirelessCharger) {
1710 mNotifier.onWirelessChargingStarted(mBatteryLevel);
1711 }
Jeff Brown84e27562012-12-07 13:56:34 -08001712 }
Jeff Brown96307042012-07-27 15:51:34 -07001713 }
Dianne Hackborneb94fa72014-06-03 17:48:12 -07001714
Makoto Onukia3cd7b92018-03-19 14:47:05 -07001715 mBatterySaverStateMachine.setBatteryStatus(mIsPowered, mBatteryLevel, mBatteryLevelLow);
Jeff Brown96307042012-07-27 15:51:34 -07001716 }
1717 }
1718
Jeff Brown3b971592013-01-09 18:46:37 -08001719 private boolean shouldWakeUpWhenPluggedOrUnpluggedLocked(
1720 boolean wasPowered, int oldPlugType, boolean dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001721 // Don't wake when powered unless configured to do so.
1722 if (!mWakeUpWhenPluggedOrUnpluggedConfig) {
1723 return false;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001724 }
Jeff Brown9fca9e92012-10-05 14:42:56 -07001725
Jeff Brown3b971592013-01-09 18:46:37 -08001726 // Don't wake when undocked from wireless charger.
1727 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001728 if (wasPowered && !mIsPowered
1729 && oldPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS) {
1730 return false;
1731 }
Jeff Brown3b971592013-01-09 18:46:37 -08001732
1733 // Don't wake when docked on wireless charger unless we are certain of it.
1734 // See WirelessChargerDetector for justification.
Jeff Brown9fca9e92012-10-05 14:42:56 -07001735 if (!wasPowered && mIsPowered
1736 && mPlugType == BatteryManager.BATTERY_PLUGGED_WIRELESS
Jeff Brown3b971592013-01-09 18:46:37 -08001737 && !dockedOnWirelessCharger) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001738 return false;
1739 }
1740
1741 // If already dreaming and becoming powered, then don't wake.
Jeff Brown26875502014-01-30 21:47:47 -08001742 if (mIsPowered && mWakefulness == WAKEFULNESS_DREAMING) {
Jeff Brown9fca9e92012-10-05 14:42:56 -07001743 return false;
1744 }
1745
Bryce Lee584a4452014-10-21 15:55:55 -07001746 // Don't wake while theater mode is enabled.
1747 if (mTheaterModeEnabled && !mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig) {
1748 return false;
1749 }
1750
Adrian Roos56021892017-02-27 20:25:09 +01001751 // On Always On Display, SystemUI shows the charging indicator
1752 if (mAlwaysOnEnabled && mWakefulness == WAKEFULNESS_DOZING) {
1753 return false;
1754 }
1755
Jeff Brown9fca9e92012-10-05 14:42:56 -07001756 // Otherwise wake up!
1757 return true;
Jeff Brownf3fb8952012-10-02 20:57:05 -07001758 }
1759
Jeff Brown96307042012-07-27 15:51:34 -07001760 /**
1761 * Updates the value of mStayOn.
1762 * Sets DIRTY_STAY_ON if a change occurred.
1763 */
1764 private void updateStayOnLocked(int dirty) {
1765 if ((dirty & (DIRTY_BATTERY_STATE | DIRTY_SETTINGS)) != 0) {
Jeff Brown93cbbb22012-10-04 13:18:36 -07001766 final boolean wasStayOn = mStayOn;
Jeff Brown96307042012-07-27 15:51:34 -07001767 if (mStayOnWhilePluggedInSetting != 0
1768 && !isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
Jeff Brown21392762014-06-13 19:00:36 -07001769 mStayOn = mBatteryManagerInternal.isPowered(mStayOnWhilePluggedInSetting);
Jeff Brown96307042012-07-27 15:51:34 -07001770 } else {
1771 mStayOn = false;
1772 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07001773
1774 if (mStayOn != wasStayOn) {
1775 mDirty |= DIRTY_STAY_ON;
1776 }
Jeff Brown96307042012-07-27 15:51:34 -07001777 }
1778 }
1779
1780 /**
1781 * Updates the value of mWakeLockSummary to summarize the state of all active wake locks.
1782 * Note that most wake-locks are ignored when the system is asleep.
1783 *
1784 * This function must have no other side-effects.
1785 */
Jeff Brownec083212013-09-11 20:45:25 -07001786 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07001787 private void updateWakeLockSummaryLocked(int dirty) {
1788 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_WAKEFULNESS)) != 0) {
1789 mWakeLockSummary = 0;
1790
Pavel Grafov28939982017-10-03 15:11:52 +01001791 final int numProfiles = mProfilePowerState.size();
1792 for (int i = 0; i < numProfiles; i++) {
1793 mProfilePowerState.valueAt(i).mWakeLockSummary = 0;
1794 }
1795
Jeff Brown96307042012-07-27 15:51:34 -07001796 final int numWakeLocks = mWakeLocks.size();
1797 for (int i = 0; i < numWakeLocks; i++) {
1798 final WakeLock wakeLock = mWakeLocks.get(i);
Pavel Grafov28939982017-10-03 15:11:52 +01001799 final int wakeLockFlags = getWakeLockSummaryFlags(wakeLock);
1800 mWakeLockSummary |= wakeLockFlags;
1801 for (int j = 0; j < numProfiles; j++) {
1802 final ProfilePowerState profile = mProfilePowerState.valueAt(j);
1803 if (wakeLockAffectsUser(wakeLock, profile.mUserId)) {
1804 profile.mWakeLockSummary |= wakeLockFlags;
1805 }
Jeff Brown96307042012-07-27 15:51:34 -07001806 }
1807 }
1808
Pavel Grafov28939982017-10-03 15:11:52 +01001809 mWakeLockSummary = adjustWakeLockSummaryLocked(mWakeLockSummary);
1810 for (int i = 0; i < numProfiles; i++) {
1811 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
1812 profile.mWakeLockSummary = adjustWakeLockSummaryLocked(profile.mWakeLockSummary);
Jeff Brownc2932a12014-11-20 18:04:05 -08001813 }
Jeff Brown037c33e2014-04-09 00:31:55 -07001814
Jeff Brown96307042012-07-27 15:51:34 -07001815 if (DEBUG_SPEW) {
1816 Slog.d(TAG, "updateWakeLockSummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08001817 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07001818 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
1819 }
1820 }
1821 }
1822
Pavel Grafov28939982017-10-03 15:11:52 +01001823 private int adjustWakeLockSummaryLocked(int wakeLockSummary) {
1824 // Cancel wake locks that make no sense based on the current state.
1825 if (mWakefulness != WAKEFULNESS_DOZING) {
1826 wakeLockSummary &= ~(WAKE_LOCK_DOZE | WAKE_LOCK_DRAW);
1827 }
1828 if (mWakefulness == WAKEFULNESS_ASLEEP
1829 || (wakeLockSummary & WAKE_LOCK_DOZE) != 0) {
1830 wakeLockSummary &= ~(WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM
1831 | WAKE_LOCK_BUTTON_BRIGHT);
1832 if (mWakefulness == WAKEFULNESS_ASLEEP) {
1833 wakeLockSummary &= ~WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1834 }
1835 }
1836
1837 // Infer implied wake locks where necessary based on the current state.
1838 if ((wakeLockSummary & (WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_SCREEN_DIM)) != 0) {
1839 if (mWakefulness == WAKEFULNESS_AWAKE) {
1840 wakeLockSummary |= WAKE_LOCK_CPU | WAKE_LOCK_STAY_AWAKE;
1841 } else if (mWakefulness == WAKEFULNESS_DREAMING) {
1842 wakeLockSummary |= WAKE_LOCK_CPU;
1843 }
1844 }
1845 if ((wakeLockSummary & WAKE_LOCK_DRAW) != 0) {
1846 wakeLockSummary |= WAKE_LOCK_CPU;
1847 }
1848
1849 return wakeLockSummary;
1850 }
1851
1852 /** Get wake lock summary flags that correspond to the given wake lock. */
1853 private int getWakeLockSummaryFlags(WakeLock wakeLock) {
1854 switch (wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
1855 case PowerManager.PARTIAL_WAKE_LOCK:
1856 if (!wakeLock.mDisabled) {
1857 // We only respect this if the wake lock is not disabled.
1858 return WAKE_LOCK_CPU;
1859 }
1860 break;
1861 case PowerManager.FULL_WAKE_LOCK:
1862 return WAKE_LOCK_SCREEN_BRIGHT | WAKE_LOCK_BUTTON_BRIGHT;
1863 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
1864 return WAKE_LOCK_SCREEN_BRIGHT;
1865 case PowerManager.SCREEN_DIM_WAKE_LOCK:
1866 return WAKE_LOCK_SCREEN_DIM;
1867 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
1868 return WAKE_LOCK_PROXIMITY_SCREEN_OFF;
1869 case PowerManager.DOZE_WAKE_LOCK:
1870 return WAKE_LOCK_DOZE;
1871 case PowerManager.DRAW_WAKE_LOCK:
1872 return WAKE_LOCK_DRAW;
1873 }
1874 return 0;
1875 }
1876
1877 private boolean wakeLockAffectsUser(WakeLock wakeLock, @UserIdInt int userId) {
1878 if (wakeLock.mWorkSource != null) {
1879 for (int k = 0; k < wakeLock.mWorkSource.size(); k++) {
1880 final int uid = wakeLock.mWorkSource.get(k);
1881 if (userId == UserHandle.getUserId(uid)) {
1882 return true;
1883 }
1884 }
Narayan Kamath2f916ed2017-12-29 13:02:15 +00001885
1886 final ArrayList<WorkChain> workChains = wakeLock.mWorkSource.getWorkChains();
1887 if (workChains != null) {
1888 for (int k = 0; k < workChains.size(); k++) {
1889 final int uid = workChains.get(k).getAttributionUid();
1890 if (userId == UserHandle.getUserId(uid)) {
1891 return true;
1892 }
1893 }
1894 }
Pavel Grafov28939982017-10-03 15:11:52 +01001895 }
1896 return userId == UserHandle.getUserId(wakeLock.mOwnerUid);
1897 }
1898
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07001899 void checkForLongWakeLocks() {
1900 synchronized (mLock) {
1901 final long now = SystemClock.uptimeMillis();
1902 mNotifyLongDispatched = now;
1903 final long when = now - MIN_LONG_WAKE_CHECK_INTERVAL;
1904 long nextCheckTime = Long.MAX_VALUE;
1905 final int numWakeLocks = mWakeLocks.size();
1906 for (int i = 0; i < numWakeLocks; i++) {
1907 final WakeLock wakeLock = mWakeLocks.get(i);
1908 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
1909 == PowerManager.PARTIAL_WAKE_LOCK) {
1910 if (wakeLock.mNotifiedAcquired && !wakeLock.mNotifiedLong) {
1911 if (wakeLock.mAcquireTime < when) {
1912 // This wake lock has exceeded the long acquire time, report!
1913 notifyWakeLockLongStartedLocked(wakeLock);
1914 } else {
1915 // This wake lock could still become a long one, at this time.
1916 long checkTime = wakeLock.mAcquireTime + MIN_LONG_WAKE_CHECK_INTERVAL;
1917 if (checkTime < nextCheckTime) {
1918 nextCheckTime = checkTime;
1919 }
1920 }
1921 }
1922 }
1923 }
1924 mNotifyLongScheduled = 0;
1925 mHandler.removeMessages(MSG_CHECK_FOR_LONG_WAKELOCKS);
1926 if (nextCheckTime != Long.MAX_VALUE) {
1927 mNotifyLongNextCheck = nextCheckTime;
1928 enqueueNotifyLongMsgLocked(nextCheckTime);
1929 } else {
1930 mNotifyLongNextCheck = 0;
1931 }
1932 }
1933 }
1934
Jeff Brown96307042012-07-27 15:51:34 -07001935 /**
1936 * Updates the value of mUserActivitySummary to summarize the user requested
1937 * state of the system such as whether the screen should be bright or dim.
1938 * Note that user activity is ignored when the system is asleep.
1939 *
1940 * This function must have no other side-effects.
1941 */
1942 private void updateUserActivitySummaryLocked(long now, int dirty) {
1943 // Update the status of the user activity timeout timer.
Jeff Brown037c33e2014-04-09 00:31:55 -07001944 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY
Jeff Browna191aa92014-11-12 23:01:12 -08001945 | DIRTY_WAKEFULNESS | DIRTY_SETTINGS)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07001946 mHandler.removeMessages(MSG_USER_ACTIVITY_TIMEOUT);
1947
1948 long nextTimeout = 0;
Jeff Brown26875502014-01-30 21:47:47 -08001949 if (mWakefulness == WAKEFULNESS_AWAKE
Jeff Brown037c33e2014-04-09 00:31:55 -07001950 || mWakefulness == WAKEFULNESS_DREAMING
1951 || mWakefulness == WAKEFULNESS_DOZING) {
Pavel Grafov28939982017-10-03 15:11:52 +01001952 final long sleepTimeout = getSleepTimeoutLocked();
1953 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
1954 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001955 final boolean userInactiveOverride = mUserInactiveOverrideFromWindowManager;
Pavel Grafov28939982017-10-03 15:11:52 +01001956 final long nextProfileTimeout = getNextProfileTimeoutLocked(now);
Jeff Brown96307042012-07-27 15:51:34 -07001957
1958 mUserActivitySummary = 0;
1959 if (mLastUserActivityTime >= mLastWakeTime) {
1960 nextTimeout = mLastUserActivityTime
1961 + screenOffTimeout - screenDimDuration;
1962 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001963 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07001964 } else {
1965 nextTimeout = mLastUserActivityTime + screenOffTimeout;
1966 if (now < nextTimeout) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07001967 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07001968 }
1969 }
1970 }
1971 if (mUserActivitySummary == 0
1972 && mLastUserActivityTimeNoChangeLights >= mLastWakeTime) {
1973 nextTimeout = mLastUserActivityTimeNoChangeLights + screenOffTimeout;
Jeff Brown970d4132014-07-19 11:33:47 -07001974 if (now < nextTimeout) {
Andrii Kulian9407a6b2017-05-24 12:24:09 -07001975 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_BRIGHT
1976 || mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_VR) {
Jeff Brown970d4132014-07-19 11:33:47 -07001977 mUserActivitySummary = USER_ACTIVITY_SCREEN_BRIGHT;
1978 } else if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DIM) {
1979 mUserActivitySummary = USER_ACTIVITY_SCREEN_DIM;
1980 }
Jeff Brown96307042012-07-27 15:51:34 -07001981 }
1982 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001983
Jeff Brown05af6ad2014-09-30 20:54:30 -07001984 if (mUserActivitySummary == 0) {
1985 if (sleepTimeout >= 0) {
1986 final long anyUserActivity = Math.max(mLastUserActivityTime,
1987 mLastUserActivityTimeNoChangeLights);
1988 if (anyUserActivity >= mLastWakeTime) {
1989 nextTimeout = anyUserActivity + sleepTimeout;
1990 if (now < nextTimeout) {
1991 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1992 }
1993 }
1994 } else {
1995 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
1996 nextTimeout = -1;
1997 }
1998 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07001999
2000 if (mUserActivitySummary != USER_ACTIVITY_SCREEN_DREAM && userInactiveOverride) {
Mojtaba2d80edc2015-09-18 16:35:24 -07002001 if ((mUserActivitySummary &
2002 (USER_ACTIVITY_SCREEN_BRIGHT | USER_ACTIVITY_SCREEN_DIM)) != 0) {
Nick Armstrong-Crews024872e2015-09-30 16:49:19 -07002003 // Device is being kept awake by recent user activity
2004 if (nextTimeout >= now && mOverriddenTimeout == -1) {
2005 // Save when the next timeout would have occurred
2006 mOverriddenTimeout = nextTimeout;
2007 }
Mojtaba2d80edc2015-09-18 16:35:24 -07002008 }
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07002009 mUserActivitySummary = USER_ACTIVITY_SCREEN_DREAM;
2010 nextTimeout = -1;
2011 }
2012
Pavel Grafov28939982017-10-03 15:11:52 +01002013 if (nextProfileTimeout > 0) {
2014 nextTimeout = Math.min(nextTimeout, nextProfileTimeout);
2015 }
2016
Jeff Brown05af6ad2014-09-30 20:54:30 -07002017 if (mUserActivitySummary != 0 && nextTimeout >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002018 scheduleUserInactivityTimeout(nextTimeout);
Jeff Brown96307042012-07-27 15:51:34 -07002019 }
2020 } else {
2021 mUserActivitySummary = 0;
2022 }
2023
2024 if (DEBUG_SPEW) {
2025 Slog.d(TAG, "updateUserActivitySummaryLocked: mWakefulness="
Jeff Brownfbe96702014-11-19 18:30:58 -08002026 + PowerManagerInternal.wakefulnessToString(mWakefulness)
Jeff Brown96307042012-07-27 15:51:34 -07002027 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
2028 + ", nextTimeout=" + TimeUtils.formatUptime(nextTimeout));
2029 }
2030 }
2031 }
2032
Pavel Grafov28939982017-10-03 15:11:52 +01002033 private void scheduleUserInactivityTimeout(long timeMs) {
2034 final Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY_TIMEOUT);
2035 msg.setAsynchronous(true);
2036 mHandler.sendMessageAtTime(msg, timeMs);
2037 }
2038
2039 /**
2040 * Finds the next profile timeout time or returns -1 if there are no profiles to be locked.
2041 */
2042 private long getNextProfileTimeoutLocked(long now) {
2043 long nextTimeout = -1;
2044 final int numProfiles = mProfilePowerState.size();
2045 for (int i = 0; i < numProfiles; i++) {
2046 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
2047 final long timeout = profile.mLastUserActivityTime + profile.mScreenOffTimeout;
2048 if (timeout > now && (nextTimeout == -1 || timeout < nextTimeout)) {
2049 nextTimeout = timeout;
2050 }
2051 }
2052 return nextTimeout;
2053 }
2054
Jeff Brown96307042012-07-27 15:51:34 -07002055 /**
2056 * Called when a user activity timeout has occurred.
2057 * Simply indicates that something about user activity has changed so that the new
2058 * state can be recomputed when the power state is updated.
2059 *
2060 * This function must have no other side-effects besides setting the dirty
2061 * bit and calling update power state. Wakefulness transitions are handled elsewhere.
2062 */
2063 private void handleUserActivityTimeout() { // runs on handler thread
2064 synchronized (mLock) {
2065 if (DEBUG_SPEW) {
2066 Slog.d(TAG, "handleUserActivityTimeout");
2067 }
2068
2069 mDirty |= DIRTY_USER_ACTIVITY;
2070 updatePowerStateLocked();
2071 }
2072 }
2073
Pavel Grafov28939982017-10-03 15:11:52 +01002074 private long getSleepTimeoutLocked() {
2075 final long timeout = mSleepTimeoutSetting;
Jeff Brown05af6ad2014-09-30 20:54:30 -07002076 if (timeout <= 0) {
2077 return -1;
2078 }
2079 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
2080 }
2081
Pavel Grafov28939982017-10-03 15:11:52 +01002082 private long getScreenOffTimeoutLocked(long sleepTimeout) {
2083 long timeout = mScreenOffTimeoutSetting;
Jeff Brown96307042012-07-27 15:51:34 -07002084 if (isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked()) {
2085 timeout = Math.min(timeout, mMaximumScreenOffTimeoutFromDeviceAdmin);
2086 }
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002087 if (mUserActivityTimeoutOverrideFromWindowManager >= 0) {
Pavel Grafov28939982017-10-03 15:11:52 +01002088 timeout = Math.min(timeout, mUserActivityTimeoutOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07002089 }
Jeff Brown05af6ad2014-09-30 20:54:30 -07002090 if (sleepTimeout >= 0) {
2091 timeout = Math.min(timeout, sleepTimeout);
2092 }
Jeff Brown27736f52014-05-20 17:17:10 -07002093 return Math.max(timeout, mMinimumScreenOffTimeoutConfig);
Jeff Brown96307042012-07-27 15:51:34 -07002094 }
2095
Pavel Grafov28939982017-10-03 15:11:52 +01002096 private long getScreenDimDurationLocked(long screenOffTimeout) {
Jeff Brown27736f52014-05-20 17:17:10 -07002097 return Math.min(mMaximumScreenDimDurationConfig,
Pavel Grafov28939982017-10-03 15:11:52 +01002098 (long)(screenOffTimeout * mMaximumScreenDimRatioConfig));
Jeff Brown96307042012-07-27 15:51:34 -07002099 }
2100
2101 /**
2102 * Updates the wakefulness of the device.
2103 *
Jeff Brown26875502014-01-30 21:47:47 -08002104 * This is the function that decides whether the device should start dreaming
Jeff Brown96307042012-07-27 15:51:34 -07002105 * based on the current wake locks and user activity state. It may modify mDirty
2106 * if the wakefulness changes.
2107 *
2108 * Returns true if the wakefulness changed and we need to restart power state calculation.
2109 */
2110 private boolean updateWakefulnessLocked(int dirty) {
2111 boolean changed = false;
2112 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_BOOT_COMPLETED
Jeff Brownec6aa592012-10-17 20:30:25 -07002113 | DIRTY_WAKEFULNESS | DIRTY_STAY_ON | DIRTY_PROXIMITY_POSITIVE
2114 | DIRTY_DOCK_STATE)) != 0) {
Jeff Brown96307042012-07-27 15:51:34 -07002115 if (mWakefulness == WAKEFULNESS_AWAKE && isItBedTimeYetLocked()) {
2116 if (DEBUG_SPEW) {
Jeff Brown62c82e42012-09-26 01:30:41 -07002117 Slog.d(TAG, "updateWakefulnessLocked: Bed time...");
Jeff Brown96307042012-07-27 15:51:34 -07002118 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002119 final long time = SystemClock.uptimeMillis();
Jeff Brownec6aa592012-10-17 20:30:25 -07002120 if (shouldNapAtBedTimeLocked()) {
Jeff Brownc12035c2014-08-13 18:52:25 -07002121 changed = napNoUpdateLocked(time, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002122 } else {
2123 changed = goToSleepNoUpdateLocked(time,
Jeff Brownc12035c2014-08-13 18:52:25 -07002124 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown62c82e42012-09-26 01:30:41 -07002125 }
Jeff Brown96307042012-07-27 15:51:34 -07002126 }
2127 }
2128 return changed;
2129 }
2130
Jeff Brown645832d2012-10-03 14:57:03 -07002131 /**
Jeff Brownec6aa592012-10-17 20:30:25 -07002132 * Returns true if the device should automatically nap and start dreaming when the user
2133 * activity timeout has expired and it's bedtime.
2134 */
2135 private boolean shouldNapAtBedTimeLocked() {
2136 return mDreamsActivateOnSleepSetting
2137 || (mDreamsActivateOnDockSetting
2138 && mDockState != Intent.EXTRA_DOCK_STATE_UNDOCKED);
2139 }
2140
2141 /**
Jeff Brown645832d2012-10-03 14:57:03 -07002142 * Returns true if the device should go to sleep now.
2143 * Also used when exiting a dream to determine whether we should go back
2144 * to being fully awake or else go to sleep for good.
2145 */
Jeff Brown96307042012-07-27 15:51:34 -07002146 private boolean isItBedTimeYetLocked() {
Jeff Brown93cbbb22012-10-04 13:18:36 -07002147 return mBootCompleted && !isBeingKeptAwakeLocked();
Jeff Brown645832d2012-10-03 14:57:03 -07002148 }
2149
2150 /**
Jeff Brown93cbbb22012-10-04 13:18:36 -07002151 * Returns true if the device is being kept awake by a wake lock, user activity
Jeff Brownec083212013-09-11 20:45:25 -07002152 * or the stay on while powered setting. We also keep the phone awake when
2153 * the proximity sensor returns a positive result so that the device does not
2154 * lock while in a phone call. This function only controls whether the device
2155 * will go to sleep or dream which is independent of whether it will be allowed
2156 * to suspend.
Jeff Brown645832d2012-10-03 14:57:03 -07002157 */
Jeff Brown93cbbb22012-10-04 13:18:36 -07002158 private boolean isBeingKeptAwakeLocked() {
Jeff Brown645832d2012-10-03 14:57:03 -07002159 return mStayOn
Jeff Brown93cbbb22012-10-04 13:18:36 -07002160 || mProximityPositive
Jeff Brown10428742012-10-09 15:47:30 -07002161 || (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0
Jeff Brown645832d2012-10-03 14:57:03 -07002162 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002163 | USER_ACTIVITY_SCREEN_DIM)) != 0
2164 || mScreenBrightnessBoostInProgress;
Jeff Brown96307042012-07-27 15:51:34 -07002165 }
2166
2167 /**
2168 * Determines whether to post a message to the sandman to update the dream state.
2169 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002170 private void updateDreamLocked(int dirty, boolean displayBecameReady) {
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002171 if ((dirty & (DIRTY_WAKEFULNESS
Jeff Brown645832d2012-10-03 14:57:03 -07002172 | DIRTY_USER_ACTIVITY
2173 | DIRTY_WAKE_LOCKS
2174 | DIRTY_BOOT_COMPLETED
John Spurlockf4f6b4c2012-08-25 12:08:03 -04002175 | DIRTY_SETTINGS
2176 | DIRTY_IS_POWERED
2177 | DIRTY_STAY_ON
Jeff Brown93cbbb22012-10-04 13:18:36 -07002178 | DIRTY_PROXIMITY_POSITIVE
Jeff Brown2175e9c2014-09-12 16:11:07 -07002179 | DIRTY_BATTERY_STATE)) != 0 || displayBecameReady) {
2180 if (mDisplayReady) {
2181 scheduleSandmanLocked();
2182 }
Jeff Brown96307042012-07-27 15:51:34 -07002183 }
2184 }
2185
2186 private void scheduleSandmanLocked() {
2187 if (!mSandmanScheduled) {
2188 mSandmanScheduled = true;
2189 Message msg = mHandler.obtainMessage(MSG_SANDMAN);
2190 msg.setAsynchronous(true);
2191 mHandler.sendMessage(msg);
2192 }
2193 }
2194
2195 /**
Jeff Brown26875502014-01-30 21:47:47 -08002196 * Called when the device enters or exits a dreaming or dozing state.
Jeff Brown96307042012-07-27 15:51:34 -07002197 *
2198 * We do this asynchronously because we must call out of the power manager to start
2199 * the dream and we don't want to hold our lock while doing so. There is a risk that
2200 * the device will wake or go to sleep in the meantime so we have to handle that case.
2201 */
2202 private void handleSandman() { // runs on handler thread
2203 // Handle preconditions.
Jeff Brown26875502014-01-30 21:47:47 -08002204 final boolean startDreaming;
2205 final int wakefulness;
Jeff Brown96307042012-07-27 15:51:34 -07002206 synchronized (mLock) {
2207 mSandmanScheduled = false;
Jeff Brown26875502014-01-30 21:47:47 -08002208 wakefulness = mWakefulness;
Jeff Brown2175e9c2014-09-12 16:11:07 -07002209 if (mSandmanSummoned && mDisplayReady) {
Jeff Brown05af6ad2014-09-30 20:54:30 -07002210 startDreaming = canDreamLocked() || canDozeLocked();
Jeff Brown26875502014-01-30 21:47:47 -08002211 mSandmanSummoned = false;
2212 } else {
2213 startDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002214 }
2215 }
2216
Jeff Brown96307042012-07-27 15:51:34 -07002217 // Start dreaming if needed.
2218 // We only control the dream on the handler thread, so we don't need to worry about
2219 // concurrent attempts to start or stop the dream.
Jeff Brown26875502014-01-30 21:47:47 -08002220 final boolean isDreaming;
Jeff Brown96307042012-07-27 15:51:34 -07002221 if (mDreamManager != null) {
Jeff Brown26875502014-01-30 21:47:47 -08002222 // Restart the dream whenever the sandman is summoned.
Jeff Brown62c82e42012-09-26 01:30:41 -07002223 if (startDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002224 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown26875502014-01-30 21:47:47 -08002225 mDreamManager.startDream(wakefulness == WAKEFULNESS_DOZING);
Jeff Brown96307042012-07-27 15:51:34 -07002226 }
Jeff Brown62c82e42012-09-26 01:30:41 -07002227 isDreaming = mDreamManager.isDreaming();
Jeff Brown26875502014-01-30 21:47:47 -08002228 } else {
2229 isDreaming = false;
Jeff Brown96307042012-07-27 15:51:34 -07002230 }
2231
2232 // Update dream state.
Jeff Brown96307042012-07-27 15:51:34 -07002233 synchronized (mLock) {
Jeff Brown26875502014-01-30 21:47:47 -08002234 // Remember the initial battery level when the dream started.
2235 if (startDreaming && isDreaming) {
2236 mBatteryLevelWhenDreamStarted = mBatteryLevel;
2237 if (wakefulness == WAKEFULNESS_DOZING) {
2238 Slog.i(TAG, "Dozing...");
2239 } else {
2240 Slog.i(TAG, "Dreaming...");
2241 }
2242 }
2243
2244 // If preconditions changed, wait for the next iteration to determine
2245 // whether the dream should continue (or be restarted).
2246 if (mSandmanSummoned || mWakefulness != wakefulness) {
2247 return; // wait for next cycle
2248 }
2249
2250 // Determine whether the dream should continue.
2251 if (wakefulness == WAKEFULNESS_DREAMING) {
2252 if (isDreaming && canDreamLocked()) {
2253 if (mDreamsBatteryLevelDrainCutoffConfig >= 0
Jeff Brown016ff142012-10-15 16:47:22 -07002254 && mBatteryLevel < mBatteryLevelWhenDreamStarted
Jeff Brown26875502014-01-30 21:47:47 -08002255 - mDreamsBatteryLevelDrainCutoffConfig
2256 && !isBeingKeptAwakeLocked()) {
Jeff Brown016ff142012-10-15 16:47:22 -07002257 // If the user activity timeout expired and the battery appears
2258 // to be draining faster than it is charging then stop dreaming
2259 // and go to sleep.
2260 Slog.i(TAG, "Stopping dream because the battery appears to "
2261 + "be draining faster than it is charging. "
2262 + "Battery level when dream started: "
2263 + mBatteryLevelWhenDreamStarted + "%. "
2264 + "Battery level now: " + mBatteryLevel + "%.");
2265 } else {
Jeff Brown26875502014-01-30 21:47:47 -08002266 return; // continue dreaming
Jeff Brown016ff142012-10-15 16:47:22 -07002267 }
Jeff Brown96307042012-07-27 15:51:34 -07002268 }
Jeff Brown26875502014-01-30 21:47:47 -08002269
2270 // Dream has ended or will be stopped. Update the power state.
2271 if (isItBedTimeYetLocked()) {
2272 goToSleepNoUpdateLocked(SystemClock.uptimeMillis(),
Jeff Brownc12035c2014-08-13 18:52:25 -07002273 PowerManager.GO_TO_SLEEP_REASON_TIMEOUT, 0, Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002274 updatePowerStateLocked();
2275 } else {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07002276 wakeUpNoUpdateLocked(SystemClock.uptimeMillis(), "android.server.power:DREAM",
2277 Process.SYSTEM_UID, mContext.getOpPackageName(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002278 updatePowerStateLocked();
2279 }
2280 } else if (wakefulness == WAKEFULNESS_DOZING) {
2281 if (isDreaming) {
2282 return; // continue dozing
2283 }
2284
2285 // Doze has ended or will be stopped. Update the power state.
Jeff Brownc12035c2014-08-13 18:52:25 -07002286 reallyGoToSleepNoUpdateLocked(SystemClock.uptimeMillis(), Process.SYSTEM_UID);
Jeff Brown26875502014-01-30 21:47:47 -08002287 updatePowerStateLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002288 }
Jeff Brown96307042012-07-27 15:51:34 -07002289 }
2290
Jeff Brown26875502014-01-30 21:47:47 -08002291 // Stop dream.
2292 if (isDreaming) {
Jeff Brownf6d46682014-07-17 22:44:20 -07002293 mDreamManager.stopDream(false /*immediate*/);
Jeff Brown96307042012-07-27 15:51:34 -07002294 }
2295 }
2296
2297 /**
Jeff Brown26875502014-01-30 21:47:47 -08002298 * Returns true if the device is allowed to dream in its current state.
Jeff Brown96307042012-07-27 15:51:34 -07002299 */
2300 private boolean canDreamLocked() {
Jeff Brown26875502014-01-30 21:47:47 -08002301 if (mWakefulness != WAKEFULNESS_DREAMING
2302 || !mDreamsSupportedConfig
2303 || !mDreamsEnabledSetting
Jeff Brown970d4132014-07-19 11:33:47 -07002304 || !mDisplayPowerRequest.isBrightOrDim()
Santos Cordon3107d292016-09-20 15:50:35 -07002305 || mDisplayPowerRequest.isVr()
Jeff Brown05af6ad2014-09-30 20:54:30 -07002306 || (mUserActivitySummary & (USER_ACTIVITY_SCREEN_BRIGHT
2307 | USER_ACTIVITY_SCREEN_DIM | USER_ACTIVITY_SCREEN_DREAM)) == 0
Jeff Brown26875502014-01-30 21:47:47 -08002308 || !mBootCompleted) {
2309 return false;
2310 }
2311 if (!isBeingKeptAwakeLocked()) {
Jeff Brown966604f2014-02-24 16:19:51 -08002312 if (!mIsPowered && !mDreamsEnabledOnBatteryConfig) {
Jeff Brown26875502014-01-30 21:47:47 -08002313 return false;
2314 }
2315 if (!mIsPowered
2316 && mDreamsBatteryLevelMinimumWhenNotPoweredConfig >= 0
2317 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenNotPoweredConfig) {
2318 return false;
2319 }
2320 if (mIsPowered
2321 && mDreamsBatteryLevelMinimumWhenPoweredConfig >= 0
2322 && mBatteryLevel < mDreamsBatteryLevelMinimumWhenPoweredConfig) {
2323 return false;
Jeff Brown96307042012-07-27 15:51:34 -07002324 }
2325 }
Jeff Brown26875502014-01-30 21:47:47 -08002326 return true;
Jeff Brown96307042012-07-27 15:51:34 -07002327 }
2328
Jeff Brown96307042012-07-27 15:51:34 -07002329 /**
Jeff Brown05af6ad2014-09-30 20:54:30 -07002330 * Returns true if the device is allowed to doze in its current state.
2331 */
2332 private boolean canDozeLocked() {
2333 return mWakefulness == WAKEFULNESS_DOZING;
2334 }
2335
2336 /**
Jeff Brown96307042012-07-27 15:51:34 -07002337 * Updates the display power state asynchronously.
2338 * When the update is finished, mDisplayReady will be set to true. The display
2339 * controller posts a message to tell us when the actual display power state
2340 * has been updated so we come back here to double-check and finish up.
2341 *
2342 * This function recalculates the display power state each time.
Jeff Brown2175e9c2014-09-12 16:11:07 -07002343 *
2344 * @return True if the display became ready.
Jeff Brown96307042012-07-27 15:51:34 -07002345 */
Jeff Brown2175e9c2014-09-12 16:11:07 -07002346 private boolean updateDisplayPowerStateLocked(int dirty) {
2347 final boolean oldDisplayReady = mDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002348 if ((dirty & (DIRTY_WAKE_LOCKS | DIRTY_USER_ACTIVITY | DIRTY_WAKEFULNESS
2349 | DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED | DIRTY_BOOT_COMPLETED
Santos Cordon3107d292016-09-20 15:50:35 -07002350 | DIRTY_SETTINGS | DIRTY_SCREEN_BRIGHTNESS_BOOST | DIRTY_VR_MODE_CHANGED |
2351 DIRTY_QUIESCENT)) != 0) {
Jeff Brown970d4132014-07-19 11:33:47 -07002352 mDisplayPowerRequest.policy = getDesiredScreenPolicyLocked();
Jeff Brown96307042012-07-27 15:51:34 -07002353
Jeff Browne333e672014-10-28 13:48:55 -07002354 // Determine appropriate screen brightness and auto-brightness adjustments.
Michael Wrightd8460232018-01-16 18:04:59 +00002355 final boolean autoBrightness;
2356 final int screenBrightnessOverride;
Michael Wright9f818ea2016-07-29 19:59:39 +01002357 if (!mBootCompleted) {
2358 // Keep the brightness steady during boot. This requires the
2359 // bootloader brightness and the default brightness to be identical.
2360 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002361 screenBrightnessOverride = mScreenBrightnessSettingDefault;
Michael Wright9f818ea2016-07-29 19:59:39 +01002362 } else if (isValidBrightness(mScreenBrightnessOverrideFromWindowManager)) {
Jeff Brown96307042012-07-27 15:51:34 -07002363 autoBrightness = false;
Michael Wrightd8460232018-01-16 18:04:59 +00002364 screenBrightnessOverride = mScreenBrightnessOverrideFromWindowManager;
2365 } else {
2366 autoBrightness = (mScreenBrightnessModeSetting ==
2367 Settings.System.SCREEN_BRIGHTNESS_MODE_AUTOMATIC);
2368 screenBrightnessOverride = -1;
Jeff Brown96307042012-07-27 15:51:34 -07002369 }
Jeff Browne333e672014-10-28 13:48:55 -07002370
2371 // Update display power request.
Michael Wrightd8460232018-01-16 18:04:59 +00002372 mDisplayPowerRequest.screenBrightnessOverride = screenBrightnessOverride;
Jeff Brown96307042012-07-27 15:51:34 -07002373 mDisplayPowerRequest.useAutoBrightness = autoBrightness;
Jeff Brown96307042012-07-27 15:51:34 -07002374 mDisplayPowerRequest.useProximitySensor = shouldUseProximitySensorLocked();
Santos Cordon3107d292016-09-20 15:50:35 -07002375 mDisplayPowerRequest.boostScreenBrightness = shouldBoostScreenBrightness();
Ruchi Kandoif974cc82014-05-01 11:25:10 -07002376
jackqdyulei92681e82017-02-28 11:26:28 -08002377 updatePowerRequestFromBatterySaverPolicy(mDisplayPowerRequest);
2378
Jeff Brown970d4132014-07-19 11:33:47 -07002379 if (mDisplayPowerRequest.policy == DisplayPowerRequest.POLICY_DOZE) {
2380 mDisplayPowerRequest.dozeScreenState = mDozeScreenStateOverrideFromDreamManager;
Ivan Podogov56bc6d02018-02-26 16:04:24 +00002381 if ((mWakeLockSummary & WAKE_LOCK_DRAW) != 0
2382 && !mDrawWakeLockOverrideFromSidekick) {
Chris Phoenix10a4a642017-09-25 13:21:00 -07002383 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_DOZE_SUSPEND) {
2384 mDisplayPowerRequest.dozeScreenState = Display.STATE_DOZE;
2385 }
2386 if (mDisplayPowerRequest.dozeScreenState == Display.STATE_ON_SUSPEND) {
2387 mDisplayPowerRequest.dozeScreenState = Display.STATE_ON;
2388 }
Jeff Brownc2932a12014-11-20 18:04:05 -08002389 }
Jeff Brown970d4132014-07-19 11:33:47 -07002390 mDisplayPowerRequest.dozeScreenBrightness =
2391 mDozeScreenBrightnessOverrideFromDreamManager;
2392 } else {
2393 mDisplayPowerRequest.dozeScreenState = Display.STATE_UNKNOWN;
2394 mDisplayPowerRequest.dozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
2395 }
2396
Jeff Brown131206b2014-04-08 17:27:14 -07002397 mDisplayReady = mDisplayManagerInternal.requestPowerState(mDisplayPowerRequest,
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002398 mRequestWaitForNegativeProximity);
Jeff Brown96307042012-07-27 15:51:34 -07002399 mRequestWaitForNegativeProximity = false;
2400
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002401 if ((dirty & DIRTY_QUIESCENT) != 0) {
2402 sQuiescent = false;
2403 }
Jeff Brown96307042012-07-27 15:51:34 -07002404 if (DEBUG_SPEW) {
Jeff Browne333e672014-10-28 13:48:55 -07002405 Slog.d(TAG, "updateDisplayPowerStateLocked: mDisplayReady=" + mDisplayReady
Jeff Brown970d4132014-07-19 11:33:47 -07002406 + ", policy=" + mDisplayPowerRequest.policy
Jeff Brown96307042012-07-27 15:51:34 -07002407 + ", mWakefulness=" + mWakefulness
2408 + ", mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary)
2409 + ", mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary)
Jeff Browne333e672014-10-28 13:48:55 -07002410 + ", mBootCompleted=" + mBootCompleted
Michael Wrightd8460232018-01-16 18:04:59 +00002411 + ", screenBrightnessOverride=" + screenBrightnessOverride
2412 + ", useAutoBrightness=" + autoBrightness
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002413 + ", mScreenBrightnessBoostInProgress=" + mScreenBrightnessBoostInProgress
Santos Cordon3107d292016-09-20 15:50:35 -07002414 + ", mIsVrModeEnabled= " + mIsVrModeEnabled
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002415 + ", sQuiescent=" + sQuiescent);
Jeff Brown96307042012-07-27 15:51:34 -07002416 }
2417 }
Jeff Brown2175e9c2014-09-12 16:11:07 -07002418 return mDisplayReady && !oldDisplayReady;
Jeff Brown96307042012-07-27 15:51:34 -07002419 }
2420
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002421 private void updateScreenBrightnessBoostLocked(int dirty) {
2422 if ((dirty & DIRTY_SCREEN_BRIGHTNESS_BOOST) != 0) {
2423 if (mScreenBrightnessBoostInProgress) {
2424 final long now = SystemClock.uptimeMillis();
2425 mHandler.removeMessages(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2426 if (mLastScreenBrightnessBoostTime > mLastSleepTime) {
2427 final long boostTimeout = mLastScreenBrightnessBoostTime +
2428 SCREEN_BRIGHTNESS_BOOST_TIMEOUT;
2429 if (boostTimeout > now) {
2430 Message msg = mHandler.obtainMessage(MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT);
2431 msg.setAsynchronous(true);
2432 mHandler.sendMessageAtTime(msg, boostTimeout);
2433 return;
2434 }
Jeff Browne333e672014-10-28 13:48:55 -07002435 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002436 mScreenBrightnessBoostInProgress = false;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07002437 mNotifier.onScreenBrightnessBoostChanged();
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002438 userActivityNoUpdateLocked(now,
2439 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
Jeff Browne333e672014-10-28 13:48:55 -07002440 }
Jeff Browne333e672014-10-28 13:48:55 -07002441 }
2442 }
2443
Santos Cordon3107d292016-09-20 15:50:35 -07002444 private boolean shouldBoostScreenBrightness() {
2445 return !mIsVrModeEnabled && mScreenBrightnessBoostInProgress;
2446 }
2447
Jeff Brown96307042012-07-27 15:51:34 -07002448 private static boolean isValidBrightness(int value) {
2449 return value >= 0 && value <= 255;
2450 }
2451
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002452 @VisibleForTesting
2453 int getDesiredScreenPolicyLocked() {
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08002454 if (mWakefulness == WAKEFULNESS_ASLEEP || sQuiescent) {
Jeff Brown970d4132014-07-19 11:33:47 -07002455 return DisplayPowerRequest.POLICY_OFF;
Jeff Brown96307042012-07-27 15:51:34 -07002456 }
2457
Jeff Brown2175e9c2014-09-12 16:11:07 -07002458 if (mWakefulness == WAKEFULNESS_DOZING) {
2459 if ((mWakeLockSummary & WAKE_LOCK_DOZE) != 0) {
2460 return DisplayPowerRequest.POLICY_DOZE;
2461 }
Lucas Dupin16cfe452018-02-08 13:14:50 -08002462 if (mDozeAfterScreenOff) {
Jeff Brown2175e9c2014-09-12 16:11:07 -07002463 return DisplayPowerRequest.POLICY_OFF;
2464 }
2465 // Fall through and preserve the current screen policy if not configured to
2466 // doze after screen off. This causes the screen off transition to be skipped.
Jeff Brown26875502014-01-30 21:47:47 -08002467 }
2468
Santos Cordon21e9f2b2017-09-13 11:59:39 -07002469 // It is important that POLICY_VR check happens after the wakefulness checks above so
2470 // that VR-mode does not prevent displays from transitioning to the correct state when
2471 // dozing or sleeping.
2472 if (mIsVrModeEnabled) {
2473 return DisplayPowerRequest.POLICY_VR;
2474 }
2475
Jeff Brown96307042012-07-27 15:51:34 -07002476 if ((mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0
2477 || (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002478 || !mBootCompleted
2479 || mScreenBrightnessBoostInProgress) {
Jeff Brown970d4132014-07-19 11:33:47 -07002480 return DisplayPowerRequest.POLICY_BRIGHT;
Jeff Brown96307042012-07-27 15:51:34 -07002481 }
2482
Jeff Brown970d4132014-07-19 11:33:47 -07002483 return DisplayPowerRequest.POLICY_DIM;
Jeff Brown96307042012-07-27 15:51:34 -07002484 }
2485
Jeff Brown131206b2014-04-08 17:27:14 -07002486 private final DisplayManagerInternal.DisplayPowerCallbacks mDisplayPowerCallbacks =
2487 new DisplayManagerInternal.DisplayPowerCallbacks() {
Jeff Brown037c33e2014-04-09 00:31:55 -07002488 private int mDisplayState = Display.STATE_UNKNOWN;
Jeff Brown131206b2014-04-08 17:27:14 -07002489
Jeff Brown96307042012-07-27 15:51:34 -07002490 @Override
2491 public void onStateChanged() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002492 synchronized (mLock) {
2493 mDirty |= DIRTY_ACTUAL_DISPLAY_POWER_STATE_UPDATED;
2494 updatePowerStateLocked();
2495 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002496 }
2497
2498 @Override
Jeff Brown93cbbb22012-10-04 13:18:36 -07002499 public void onProximityPositive() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002500 synchronized (mLock) {
2501 mProximityPositive = true;
2502 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2503 updatePowerStateLocked();
2504 }
Jeff Brown93cbbb22012-10-04 13:18:36 -07002505 }
2506
2507 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002508 public void onProximityNegative() {
Jeff Brownd91e4172013-07-16 15:18:19 -07002509 synchronized (mLock) {
2510 mProximityPositive = false;
2511 mDirty |= DIRTY_PROXIMITY_POSITIVE;
2512 userActivityNoUpdateLocked(SystemClock.uptimeMillis(),
2513 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, Process.SYSTEM_UID);
2514 updatePowerStateLocked();
2515 }
Jeff Brown96307042012-07-27 15:51:34 -07002516 }
Jeff Brown131206b2014-04-08 17:27:14 -07002517
2518 @Override
Jeff Brown037c33e2014-04-09 00:31:55 -07002519 public void onDisplayStateChange(int state) {
2520 // This method is only needed to support legacy display blanking behavior
2521 // where the display's power state is coupled to suspend or to the power HAL.
2522 // The order of operations matters here.
2523 synchronized (mLock) {
2524 if (mDisplayState != state) {
2525 mDisplayState = state;
2526 if (state == Display.STATE_OFF) {
2527 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2528 setHalInteractiveModeLocked(false);
2529 }
2530 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2531 setHalAutoSuspendModeLocked(true);
2532 }
2533 } else {
2534 if (!mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2535 setHalAutoSuspendModeLocked(false);
2536 }
2537 if (!mDecoupleHalInteractiveModeFromDisplayConfig) {
2538 setHalInteractiveModeLocked(true);
2539 }
2540 }
2541 }
2542 }
2543 }
2544
2545 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002546 public void acquireSuspendBlocker() {
2547 mDisplaySuspendBlocker.acquire();
2548 }
2549
2550 @Override
2551 public void releaseSuspendBlocker() {
2552 mDisplaySuspendBlocker.release();
2553 }
2554
2555 @Override
Jeff Brown131206b2014-04-08 17:27:14 -07002556 public String toString() {
2557 synchronized (this) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002558 return "state=" + Display.stateToString(mDisplayState);
Jeff Brown131206b2014-04-08 17:27:14 -07002559 }
2560 }
Jeff Brown96307042012-07-27 15:51:34 -07002561 };
Jim Miller92e66dd2012-02-21 18:57:12 -08002562
Jeff Brown96307042012-07-27 15:51:34 -07002563 private boolean shouldUseProximitySensorLocked() {
Santos Cordon3107d292016-09-20 15:50:35 -07002564 return !mIsVrModeEnabled && (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0;
Jeff Brown96307042012-07-27 15:51:34 -07002565 }
Jim Miller92e66dd2012-02-21 18:57:12 -08002566
Jeff Brown96307042012-07-27 15:51:34 -07002567 /**
2568 * Updates the suspend blocker that keeps the CPU alive.
2569 *
2570 * This function must have no other side-effects.
2571 */
2572 private void updateSuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002573 final boolean needWakeLockSuspendBlocker = ((mWakeLockSummary & WAKE_LOCK_CPU) != 0);
Jeff Brown26875502014-01-30 21:47:47 -08002574 final boolean needDisplaySuspendBlocker = needDisplaySuspendBlockerLocked();
2575 final boolean autoSuspend = !needDisplaySuspendBlocker;
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002576 final boolean interactive = mDisplayPowerRequest.isBrightOrDim();
Jeff Brown26875502014-01-30 21:47:47 -08002577
2578 // Disable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002579 // FIXME We should consider just leaving auto-suspend enabled forever since
2580 // we already hold the necessary wakelocks.
2581 if (!autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2582 setHalAutoSuspendModeLocked(false);
Jeff Brown26875502014-01-30 21:47:47 -08002583 }
Jeff Brown27f7a862012-12-12 15:43:31 -08002584
2585 // First acquire suspend blockers if needed.
2586 if (needWakeLockSuspendBlocker && !mHoldingWakeLockSuspendBlocker) {
2587 mWakeLockSuspendBlocker.acquire();
2588 mHoldingWakeLockSuspendBlocker = true;
2589 }
2590 if (needDisplaySuspendBlocker && !mHoldingDisplaySuspendBlocker) {
2591 mDisplaySuspendBlocker.acquire();
2592 mHoldingDisplaySuspendBlocker = true;
2593 }
2594
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002595 // Inform the power HAL about interactive mode.
2596 // Although we could set interactive strictly based on the wakefulness
2597 // as reported by isInteractive(), it is actually more desirable to track
2598 // the display policy state instead so that the interactive state observed
2599 // by the HAL more accurately tracks transitions between AWAKE and DOZING.
2600 // Refer to getDesiredScreenPolicyLocked() for details.
2601 if (mDecoupleHalInteractiveModeFromDisplayConfig) {
2602 // When becoming non-interactive, we want to defer sending this signal
2603 // until the display is actually ready so that all transitions have
2604 // completed. This is probably a good sign that things have gotten
2605 // too tangled over here...
2606 if (interactive || mDisplayReady) {
2607 setHalInteractiveModeLocked(interactive);
2608 }
2609 }
2610
Jeff Brown27f7a862012-12-12 15:43:31 -08002611 // Then release suspend blockers if needed.
2612 if (!needWakeLockSuspendBlocker && mHoldingWakeLockSuspendBlocker) {
2613 mWakeLockSuspendBlocker.release();
2614 mHoldingWakeLockSuspendBlocker = false;
2615 }
2616 if (!needDisplaySuspendBlocker && mHoldingDisplaySuspendBlocker) {
2617 mDisplaySuspendBlocker.release();
2618 mHoldingDisplaySuspendBlocker = false;
2619 }
Jeff Brown26875502014-01-30 21:47:47 -08002620
2621 // Enable auto-suspend if needed.
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002622 if (autoSuspend && mDecoupleHalAutoSuspendModeFromDisplayConfig) {
2623 setHalAutoSuspendModeLocked(true);
Jeff Brown26875502014-01-30 21:47:47 -08002624 }
Jeff Brown96307042012-07-27 15:51:34 -07002625 }
2626
Jeff Brownec083212013-09-11 20:45:25 -07002627 /**
2628 * Return true if we must keep a suspend blocker active on behalf of the display.
2629 * We do so if the screen is on or is in transition between states.
2630 */
Jeff Brown26875502014-01-30 21:47:47 -08002631 private boolean needDisplaySuspendBlockerLocked() {
Jeff Brownec083212013-09-11 20:45:25 -07002632 if (!mDisplayReady) {
2633 return true;
2634 }
Jeff Brown970d4132014-07-19 11:33:47 -07002635 if (mDisplayPowerRequest.isBrightOrDim()) {
Jeff Brownec083212013-09-11 20:45:25 -07002636 // If we asked for the screen to be on but it is off due to the proximity
2637 // sensor then we may suspend but only if the configuration allows it.
2638 // On some hardware it may not be safe to suspend because the proximity
2639 // sensor may not be correctly configured as a wake-up source.
2640 if (!mDisplayPowerRequest.useProximitySensor || !mProximityPositive
2641 || !mSuspendWhenScreenOffDueToProximityConfig) {
2642 return true;
2643 }
2644 }
Jeff Brown7b5be5e2014-11-12 18:45:31 -08002645 if (mScreenBrightnessBoostInProgress) {
2646 return true;
2647 }
Jeff Brown26875502014-01-30 21:47:47 -08002648 // Let the system suspend if the screen is off or dozing.
Jeff Brownec083212013-09-11 20:45:25 -07002649 return false;
2650 }
2651
Jeff Brown037c33e2014-04-09 00:31:55 -07002652 private void setHalAutoSuspendModeLocked(boolean enable) {
2653 if (enable != mHalAutoSuspendModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002654 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002655 Slog.d(TAG, "Setting HAL auto-suspend mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002656 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002657 mHalAutoSuspendModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002658 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalAutoSuspend(" + enable + ")");
2659 try {
2660 nativeSetAutoSuspend(enable);
2661 } finally {
2662 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2663 }
Jeff Brown26875502014-01-30 21:47:47 -08002664 }
2665 }
2666
Jeff Brown037c33e2014-04-09 00:31:55 -07002667 private void setHalInteractiveModeLocked(boolean enable) {
2668 if (enable != mHalInteractiveModeEnabled) {
Jeff Brown26875502014-01-30 21:47:47 -08002669 if (DEBUG) {
Jeff Brown037c33e2014-04-09 00:31:55 -07002670 Slog.d(TAG, "Setting HAL interactive mode to " + enable);
Jeff Brown26875502014-01-30 21:47:47 -08002671 }
Jeff Brown037c33e2014-04-09 00:31:55 -07002672 mHalInteractiveModeEnabled = enable;
Jeff Brown3edf5272014-08-14 19:25:14 -07002673 Trace.traceBegin(Trace.TRACE_TAG_POWER, "setHalInteractive(" + enable + ")");
2674 try {
2675 nativeSetInteractive(enable);
2676 } finally {
2677 Trace.traceEnd(Trace.TRACE_TAG_POWER);
2678 }
Jeff Brown26875502014-01-30 21:47:47 -08002679 }
2680 }
2681
Jeff Brown037c33e2014-04-09 00:31:55 -07002682 private boolean isInteractiveInternal() {
Jeff Brown96307042012-07-27 15:51:34 -07002683 synchronized (mLock) {
Jeff Brownfbe96702014-11-19 18:30:58 -08002684 return PowerManagerInternal.isInteractive(mWakefulness);
Mike Lockwoodb2865412010-02-02 22:40:33 -05002685 }
2686 }
2687
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002688 private boolean setLowPowerModeInternal(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002689 synchronized (mLock) {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002690 if (DEBUG) {
2691 Slog.d(TAG, "setLowPowerModeInternal " + enabled + " mIsPowered=" + mIsPowered);
2692 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002693 if (mIsPowered) {
2694 return false;
2695 }
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002696
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002697 mBatterySaverStateMachine.setBatterySaverEnabledManually(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002698
John Spurlock8d4e6cb2014-09-14 11:10:22 -04002699 return true;
2700 }
2701 }
2702
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002703 boolean isDeviceIdleModeInternal() {
Dianne Hackborn88e98df2015-03-23 13:29:14 -07002704 synchronized (mLock) {
2705 return mDeviceIdleMode;
2706 }
2707 }
2708
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002709 boolean isLightDeviceIdleModeInternal() {
2710 synchronized (mLock) {
2711 return mLightDeviceIdleMode;
2712 }
2713 }
2714
Jeff Brown96307042012-07-27 15:51:34 -07002715 private void handleBatteryStateChangedLocked() {
2716 mDirty |= DIRTY_BATTERY_STATE;
2717 updatePowerStateLocked();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04002718 }
2719
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002720 private void shutdownOrRebootInternal(final @HaltMode int haltMode, final boolean confirm,
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002721 final String reason, boolean wait) {
Jeff Brown96307042012-07-27 15:51:34 -07002722 if (mHandler == null || !mSystemReady) {
Jeff Sharkeyfe6f85c2017-01-20 10:42:57 -07002723 if (RescueParty.isAttemptingFactoryReset()) {
2724 // If we're stuck in a really low-level reboot loop, and a
2725 // rescue party is trying to prompt the user for a factory data
2726 // reset, we must GET TO DA CHOPPA!
2727 PowerManagerService.lowLevelReboot(reason);
2728 } else {
2729 throw new IllegalStateException("Too early to call shutdown() or reboot()");
2730 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002731 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002732
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002733 Runnable runnable = new Runnable() {
Jeff Brownab887a02012-10-15 16:00:40 -07002734 @Override
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002735 public void run() {
2736 synchronized (this) {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002737 if (haltMode == HALT_MODE_REBOOT_SAFE_MODE) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002738 ShutdownThread.rebootSafeMode(getUiContext(), confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002739 } else if (haltMode == HALT_MODE_REBOOT) {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002740 ShutdownThread.reboot(getUiContext(), reason, confirm);
Tony Mantlerb8009fd2016-03-14 15:55:35 -07002741 } else {
Adam Lesinskia82b6262017-03-21 16:56:17 -07002742 ShutdownThread.shutdown(getUiContext(), reason, confirm);
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002743 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002744 }
San Mehat1e512792010-01-07 10:40:29 -08002745 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002746 };
Jeff Brown96307042012-07-27 15:51:34 -07002747
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002748 // ShutdownThread must run on a looper capable of displaying the UI.
Michael Wright64c820d2017-03-21 12:36:55 +00002749 Message msg = Message.obtain(UiThread.getHandler(), runnable);
Jeff Brown96307042012-07-27 15:51:34 -07002750 msg.setAsynchronous(true);
Michael Wright64c820d2017-03-21 12:36:55 +00002751 UiThread.getHandler().sendMessage(msg);
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002752
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002753 // PowerManager.reboot() is documented not to return so just wait for the inevitable.
Dianne Hackbornc428aae2012-10-03 16:38:22 -07002754 if (wait) {
2755 synchronized (runnable) {
2756 while (true) {
2757 try {
2758 runnable.wait();
2759 } catch (InterruptedException e) {
2760 }
Mike Lockwoodb62f9592010-03-12 07:55:23 -05002761 }
Suchi Amalapurapu6ffce2e2010-03-08 14:48:40 -08002762 }
Doug Zongker50a21f42009-11-19 12:49:53 -08002763 }
2764 }
2765
Jeff Brown96307042012-07-27 15:51:34 -07002766 private void crashInternal(final String message) {
Dan Egnor60d87622009-12-16 16:32:58 -08002767 Thread t = new Thread("PowerManagerService.crash()") {
Jeff Brownab887a02012-10-15 16:00:40 -07002768 @Override
Jeff Brown96307042012-07-27 15:51:34 -07002769 public void run() {
2770 throw new RuntimeException(message);
2771 }
Dan Egnor60d87622009-12-16 16:32:58 -08002772 };
2773 try {
2774 t.start();
2775 t.join();
2776 } catch (InterruptedException e) {
Dianne Hackborn8d051722014-10-01 14:59:58 -07002777 Slog.wtf(TAG, e);
Dan Egnor60d87622009-12-16 16:32:58 -08002778 }
2779 }
2780
jackqdyulei92681e82017-02-28 11:26:28 -08002781 @VisibleForTesting
2782 void updatePowerRequestFromBatterySaverPolicy(DisplayPowerRequest displayPowerRequest) {
2783 PowerSaveState state = mBatterySaverPolicy.
Makoto Onukia3cd7b92018-03-19 14:47:05 -07002784 getBatterySaverPolicy(ServiceType.SCREEN_BRIGHTNESS,
2785 mBatterySaverController.isEnabled());
jackqdyulei92681e82017-02-28 11:26:28 -08002786 displayPowerRequest.lowPowerMode = state.batterySaverEnabled;
2787 displayPowerRequest.screenLowPowerBrightnessFactor = state.brightnessFactor;
2788 }
2789
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002790 void setStayOnSettingInternal(int val) {
Christopher Tatead735322012-09-07 14:19:43 -07002791 Settings.Global.putInt(mContext.getContentResolver(),
2792 Settings.Global.STAY_ON_WHILE_PLUGGED_IN, val);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002793 }
2794
Pavel Grafov28939982017-10-03 15:11:52 +01002795 void setMaximumScreenOffTimeoutFromDeviceAdminInternal(@UserIdInt int userId, long timeMs) {
2796 if (userId < 0) {
2797 Slog.wtf(TAG, "Attempt to set screen off timeout for invalid user: " + userId);
2798 return;
2799 }
Jeff Brown96307042012-07-27 15:51:34 -07002800 synchronized (mLock) {
Pavel Grafov28939982017-10-03 15:11:52 +01002801 // System-wide timeout
2802 if (userId == UserHandle.USER_SYSTEM) {
2803 mMaximumScreenOffTimeoutFromDeviceAdmin = timeMs;
2804 } else if (timeMs == Long.MAX_VALUE || timeMs == 0) {
2805 mProfilePowerState.delete(userId);
2806 } else {
2807 final ProfilePowerState profile = mProfilePowerState.get(userId);
2808 if (profile != null) {
2809 profile.mScreenOffTimeout = timeMs;
2810 } else {
2811 mProfilePowerState.put(userId, new ProfilePowerState(userId, timeMs));
2812 // We need to recalculate wake locks for the new profile state.
2813 mDirty |= DIRTY_WAKE_LOCKS;
2814 }
2815 }
Jeff Brown96307042012-07-27 15:51:34 -07002816 mDirty |= DIRTY_SETTINGS;
2817 updatePowerStateLocked();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818 }
2819 }
2820
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002821 boolean setDeviceIdleModeInternal(boolean enabled) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002822 synchronized (mLock) {
Felipe Lemeea014392016-09-06 13:59:54 -07002823 if (mDeviceIdleMode == enabled) {
2824 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002825 }
Felipe Lemeea014392016-09-06 13:59:54 -07002826 mDeviceIdleMode = enabled;
2827 updateWakeLockDisabledStatesLocked();
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002828 }
Felipe Lemeea014392016-09-06 13:59:54 -07002829 if (enabled) {
2830 EventLogTags.writeDeviceIdleOnPhase("power");
2831 } else {
2832 EventLogTags.writeDeviceIdleOffPhase("power");
2833 }
2834 return true;
Dianne Hackborn08c47a52015-10-15 12:38:14 -07002835 }
2836
2837 boolean setLightDeviceIdleModeInternal(boolean enabled) {
2838 synchronized (mLock) {
2839 if (mLightDeviceIdleMode != enabled) {
2840 mLightDeviceIdleMode = enabled;
2841 return true;
2842 }
2843 return false;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002844 }
2845 }
2846
2847 void setDeviceIdleWhitelistInternal(int[] appids) {
2848 synchronized (mLock) {
2849 mDeviceIdleWhitelist = appids;
2850 if (mDeviceIdleMode) {
2851 updateWakeLockDisabledStatesLocked();
2852 }
2853 }
2854 }
2855
Amith Yamasaniaf575b92015-05-29 15:35:26 -07002856 void setDeviceIdleTempWhitelistInternal(int[] appids) {
2857 synchronized (mLock) {
2858 mDeviceIdleTempWhitelist = appids;
2859 if (mDeviceIdleMode) {
2860 updateWakeLockDisabledStatesLocked();
2861 }
2862 }
2863 }
2864
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002865 void startUidChangesInternal() {
2866 synchronized (mLock) {
2867 mUidsChanging = true;
2868 }
2869 }
2870
2871 void finishUidChangesInternal() {
2872 synchronized (mLock) {
2873 mUidsChanging = false;
2874 if (mUidsChanged) {
2875 updateWakeLockDisabledStatesLocked();
2876 mUidsChanged = false;
2877 }
2878 }
2879 }
2880
2881 private void handleUidStateChangeLocked() {
2882 if (mUidsChanging) {
2883 mUidsChanged = true;
2884 } else {
2885 updateWakeLockDisabledStatesLocked();
2886 }
2887 }
2888
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002889 void updateUidProcStateInternal(int uid, int procState) {
2890 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002891 UidState state = mUidState.get(uid);
2892 if (state == null) {
2893 state = new UidState(uid);
2894 mUidState.put(uid, state);
2895 }
Dianne Hackborn951ea692016-11-02 10:41:53 -07002896 final boolean oldShouldAllow = state.mProcState
2897 <= ActivityManager.PROCESS_STATE_RECEIVER;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002898 state.mProcState = procState;
Dianne Hackborn951ea692016-11-02 10:41:53 -07002899 if (state.mNumWakeLocks > 0) {
2900 if (mDeviceIdleMode) {
2901 handleUidStateChangeLocked();
2902 } else if (!state.mActive && oldShouldAllow !=
2903 (procState <= ActivityManager.PROCESS_STATE_RECEIVER)) {
2904 // If this uid is not active, but the process state has changed such
2905 // that we may still want to allow it to hold a wake lock, then take care of it.
2906 handleUidStateChangeLocked();
2907 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002908 }
2909 }
2910 }
2911
2912 void uidGoneInternal(int uid) {
2913 synchronized (mLock) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002914 final int index = mUidState.indexOfKey(uid);
2915 if (index >= 0) {
2916 UidState state = mUidState.valueAt(index);
2917 state.mProcState = ActivityManager.PROCESS_STATE_NONEXISTENT;
2918 state.mActive = false;
2919 mUidState.removeAt(index);
2920 if (mDeviceIdleMode && state.mNumWakeLocks > 0) {
2921 handleUidStateChangeLocked();
2922 }
2923 }
2924 }
2925 }
2926
2927 void uidActiveInternal(int uid) {
2928 synchronized (mLock) {
2929 UidState state = mUidState.get(uid);
2930 if (state == null) {
2931 state = new UidState(uid);
2932 state.mProcState = ActivityManager.PROCESS_STATE_CACHED_EMPTY;
2933 mUidState.put(uid, state);
2934 }
2935 state.mActive = true;
2936 if (state.mNumWakeLocks > 0) {
2937 handleUidStateChangeLocked();
2938 }
2939 }
2940 }
2941
2942 void uidIdleInternal(int uid) {
2943 synchronized (mLock) {
2944 UidState state = mUidState.get(uid);
2945 if (state != null) {
2946 state.mActive = false;
2947 if (state.mNumWakeLocks > 0) {
2948 handleUidStateChangeLocked();
2949 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07002950 }
2951 }
2952 }
2953
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002954 private void updateWakeLockDisabledStatesLocked() {
2955 boolean changed = false;
2956 final int numWakeLocks = mWakeLocks.size();
2957 for (int i = 0; i < numWakeLocks; i++) {
2958 final WakeLock wakeLock = mWakeLocks.get(i);
2959 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07002960 == PowerManager.PARTIAL_WAKE_LOCK) {
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07002961 if (setWakeLockDisabledStateLocked(wakeLock)) {
2962 changed = true;
2963 if (wakeLock.mDisabled) {
2964 // This wake lock is no longer being respected.
2965 notifyWakeLockReleasedLocked(wakeLock);
2966 } else {
2967 notifyWakeLockAcquiredLocked(wakeLock);
2968 }
2969 }
2970 }
2971 }
2972 if (changed) {
2973 mDirty |= DIRTY_WAKE_LOCKS;
2974 updatePowerStateLocked();
2975 }
2976 }
2977
2978 private boolean setWakeLockDisabledStateLocked(WakeLock wakeLock) {
2979 if ((wakeLock.mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK)
2980 == PowerManager.PARTIAL_WAKE_LOCK) {
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07002981 boolean disabled = false;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002982 final int appid = UserHandle.getAppId(wakeLock.mOwnerUid);
2983 if (appid >= Process.FIRST_APPLICATION_UID) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002984 // Cached inactive processes are never allowed to hold wake locks.
2985 if (mConstants.NO_CACHED_WAKE_LOCKS) {
2986 disabled = !wakeLock.mUidState.mActive &&
2987 wakeLock.mUidState.mProcState
2988 != ActivityManager.PROCESS_STATE_NONEXISTENT &&
2989 wakeLock.mUidState.mProcState > ActivityManager.PROCESS_STATE_RECEIVER;
2990 }
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002991 if (mDeviceIdleMode) {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07002992 // If we are in idle mode, we will also ignore all partial wake locks that are
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07002993 // for application uids that are not whitelisted.
2994 final UidState state = wakeLock.mUidState;
2995 if (Arrays.binarySearch(mDeviceIdleWhitelist, appid) < 0 &&
2996 Arrays.binarySearch(mDeviceIdleTempWhitelist, appid) < 0 &&
2997 state.mProcState != ActivityManager.PROCESS_STATE_NONEXISTENT &&
Dianne Hackborn10fc4fd2017-12-19 17:23:13 -08002998 state.mProcState >
2999 ActivityManager.PROCESS_STATE_BOUND_FOREGROUND_SERVICE) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003000 disabled = true;
3001 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003002 }
3003 }
Ruchi Kandoi9c36c022016-04-20 13:42:01 -07003004 if (wakeLock.mDisabled != disabled) {
3005 wakeLock.mDisabled = disabled;
3006 return true;
3007 }
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003008 }
3009 return false;
3010 }
3011
Jeff Brown96307042012-07-27 15:51:34 -07003012 private boolean isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() {
3013 return mMaximumScreenOffTimeoutFromDeviceAdmin >= 0
Pavel Grafov28939982017-10-03 15:11:52 +01003014 && mMaximumScreenOffTimeoutFromDeviceAdmin < Long.MAX_VALUE;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003015 }
Doug Zongkerab5c49c2009-12-04 10:31:43 -08003016
Jeff Brown96307042012-07-27 15:51:34 -07003017 private void setAttentionLightInternal(boolean on, int color) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003018 Light light;
Jeff Brown96307042012-07-27 15:51:34 -07003019 synchronized (mLock) {
3020 if (!mSystemReady) {
3021 return;
3022 }
3023 light = mAttentionLight;
Mike Lockwood36fc3022009-08-25 16:49:06 -07003024 }
Jeff Brown96307042012-07-27 15:51:34 -07003025
3026 // Control light outside of lock.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003027 light.setFlashing(color, Light.LIGHT_FLASH_HARDWARE, (on ? 3 : 0), 0);
Jeff Brown96307042012-07-27 15:51:34 -07003028 }
3029
Lucas Dupin16cfe452018-02-08 13:14:50 -08003030 private void setDozeAfterScreenOffInternal(boolean on) {
3031 synchronized (mLock) {
3032 mDozeAfterScreenOff = on;
3033 }
3034 }
3035
Jeff Browne333e672014-10-28 13:48:55 -07003036 private void boostScreenBrightnessInternal(long eventTime, int uid) {
3037 synchronized (mLock) {
3038 if (!mSystemReady || mWakefulness == WAKEFULNESS_ASLEEP
3039 || eventTime < mLastScreenBrightnessBoostTime) {
3040 return;
3041 }
3042
3043 Slog.i(TAG, "Brightness boost activated (uid " + uid +")...");
3044 mLastScreenBrightnessBoostTime = eventTime;
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003045 if (!mScreenBrightnessBoostInProgress) {
3046 mScreenBrightnessBoostInProgress = true;
3047 mNotifier.onScreenBrightnessBoostChanged();
3048 }
Jeff Browne333e672014-10-28 13:48:55 -07003049 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3050
3051 userActivityNoUpdateLocked(eventTime,
3052 PowerManager.USER_ACTIVITY_EVENT_OTHER, 0, uid);
3053 updatePowerStateLocked();
3054 }
3055 }
3056
Bryce Lee84d6c0f2015-03-17 10:43:08 -07003057 private boolean isScreenBrightnessBoostedInternal() {
3058 synchronized (mLock) {
3059 return mScreenBrightnessBoostInProgress;
3060 }
3061 }
3062
Jeff Browne333e672014-10-28 13:48:55 -07003063 /**
3064 * Called when a screen brightness boost timeout has occurred.
3065 *
3066 * This function must have no other side-effects besides setting the dirty
3067 * bit and calling update power state.
3068 */
3069 private void handleScreenBrightnessBoostTimeout() { // runs on handler thread
3070 synchronized (mLock) {
3071 if (DEBUG_SPEW) {
3072 Slog.d(TAG, "handleScreenBrightnessBoostTimeout");
3073 }
3074
3075 mDirty |= DIRTY_SCREEN_BRIGHTNESS_BOOST;
3076 updatePowerStateLocked();
3077 }
3078 }
3079
Jeff Brown96307042012-07-27 15:51:34 -07003080 private void setScreenBrightnessOverrideFromWindowManagerInternal(int brightness) {
3081 synchronized (mLock) {
3082 if (mScreenBrightnessOverrideFromWindowManager != brightness) {
3083 mScreenBrightnessOverrideFromWindowManager = brightness;
3084 mDirty |= DIRTY_SETTINGS;
3085 updatePowerStateLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003086 }
Mike Lockwood809ad0f2009-10-26 22:10:33 -04003087 }
Mike Lockwoodbc706a02009-07-27 13:50:57 -07003088 }
3089
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003090 private void setUserInactiveOverrideFromWindowManagerInternal() {
3091 synchronized (mLock) {
3092 mUserInactiveOverrideFromWindowManager = true;
3093 mDirty |= DIRTY_USER_ACTIVITY;
3094 updatePowerStateLocked();
3095 }
3096 }
3097
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003098 private void setUserActivityTimeoutOverrideFromWindowManagerInternal(long timeoutMillis) {
3099 synchronized (mLock) {
3100 if (mUserActivityTimeoutOverrideFromWindowManager != timeoutMillis) {
3101 mUserActivityTimeoutOverrideFromWindowManager = timeoutMillis;
Michael Wrightb55e3a12018-03-06 15:14:06 +00003102 EventLogTags.writeUserActivityTimeoutOverride(timeoutMillis);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003103 mDirty |= DIRTY_SETTINGS;
3104 updatePowerStateLocked();
3105 }
3106 }
3107 }
3108
Jeff Brown970d4132014-07-19 11:33:47 -07003109 private void setDozeOverrideFromDreamManagerInternal(
3110 int screenState, int screenBrightness) {
3111 synchronized (mLock) {
3112 if (mDozeScreenStateOverrideFromDreamManager != screenState
3113 || mDozeScreenBrightnessOverrideFromDreamManager != screenBrightness) {
3114 mDozeScreenStateOverrideFromDreamManager = screenState;
3115 mDozeScreenBrightnessOverrideFromDreamManager = screenBrightness;
3116 mDirty |= DIRTY_SETTINGS;
3117 updatePowerStateLocked();
3118 }
3119 }
3120 }
3121
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003122 private void setDrawWakeLockOverrideFromSidekickInternal(boolean keepState) {
3123 synchronized (mLock) {
3124 if (mDrawWakeLockOverrideFromSidekick != keepState) {
3125 mDrawWakeLockOverrideFromSidekick = keepState;
3126 mDirty |= DIRTY_SETTINGS;
3127 updatePowerStateLocked();
3128 }
3129 }
3130 }
3131
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003132 @VisibleForTesting
3133 void setVrModeEnabled(boolean enabled) {
3134 mIsVrModeEnabled = enabled;
3135 }
3136
Makoto Onukia7d8c4d2017-11-20 15:20:16 -08003137 private void powerHintInternal(int hintId, int data) {
3138 // Maybe filter the event.
3139 switch (hintId) {
3140 case PowerHint.LAUNCH: // 1: activate launch boost 0: deactivate.
3141 if (data == 1 && mBatterySaverController.isLaunchBoostDisabled()) {
3142 return;
3143 }
3144 break;
3145 }
3146
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07003147 nativeSendPowerHint(hintId, data);
3148 }
3149
Jeff Brown96307042012-07-27 15:51:34 -07003150 /**
3151 * Low-level function turn the device off immediately, without trying
3152 * to be clean. Most people should use {@link ShutdownThread} for a clean shutdown.
Yusuke Sato705ffd12015-07-21 15:52:11 -07003153 *
3154 * @param reason code to pass to android_reboot() (e.g. "userrequested"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003155 */
Yusuke Sato705ffd12015-07-21 15:52:11 -07003156 public static void lowLevelShutdown(String reason) {
3157 if (reason == null) {
3158 reason = "";
3159 }
3160 SystemProperties.set("sys.powerctl", "shutdown," + reason);
Jeff Brown96307042012-07-27 15:51:34 -07003161 }
3162
3163 /**
Doug Zongker3b0218b2014-01-14 12:29:06 -08003164 * Low-level function to reboot the device. On success, this
3165 * function doesn't return. If more than 20 seconds passes from
Tao Bao90237f72015-05-21 16:25:19 -07003166 * the time a reboot is requested, this method returns.
Jeff Brown96307042012-07-27 15:51:34 -07003167 *
3168 * @param reason code to pass to the kernel (e.g. "recovery"), or null.
Jeff Brown96307042012-07-27 15:51:34 -07003169 */
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003170 public static void lowLevelReboot(String reason) {
3171 if (reason == null) {
3172 reason = "";
3173 }
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003174
3175 // If the reason is "quiescent", it means that the boot process should proceed
3176 // without turning on the screen/lights.
3177 // The "quiescent" property is sticky, meaning that any number
3178 // of subsequent reboots should honor the property until it is reset.
3179 if (reason.equals(PowerManager.REBOOT_QUIESCENT)) {
3180 sQuiescent = true;
3181 reason = "";
Dmitri Plotnikov690c6bd2017-05-10 16:26:38 -07003182 } else if (reason.endsWith("," + PowerManager.REBOOT_QUIESCENT)) {
3183 sQuiescent = true;
3184 reason = reason.substring(0,
3185 reason.length() - PowerManager.REBOOT_QUIESCENT.length() - 1);
3186 }
3187
3188 if (reason.equals(PowerManager.REBOOT_RECOVERY)
3189 || reason.equals(PowerManager.REBOOT_RECOVERY_UPDATE)) {
3190 reason = "recovery";
Dmitri Plotnikova8d2c642016-12-08 10:49:24 -08003191 }
3192
3193 if (sQuiescent) {
3194 // Pass the optional "quiescent" argument to the bootloader to let it know
3195 // that it should not turn the screen/lights on.
3196 reason = reason + ",quiescent";
3197 }
3198
3199 SystemProperties.set("sys.powerctl", "reboot," + reason);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003200 try {
Tao Bao90237f72015-05-21 16:25:19 -07003201 Thread.sleep(20 * 1000L);
Nick Kralevichdbcf2d72013-04-18 14:41:40 -07003202 } catch (InterruptedException e) {
3203 Thread.currentThread().interrupt();
3204 }
Tao Bao90237f72015-05-21 16:25:19 -07003205 Slog.wtf(TAG, "Unexpected return from lowLevelReboot!");
Jeff Brown96307042012-07-27 15:51:34 -07003206 }
3207
3208 @Override // Watchdog.Monitor implementation
3209 public void monitor() {
3210 // Grab and release lock for watchdog monitor to detect deadlocks.
3211 synchronized (mLock) {
Mike Lockwood20f87d72009-11-05 16:08:51 -05003212 }
Jeff Brown96307042012-07-27 15:51:34 -07003213 }
3214
Jeff Brown6f357d32014-01-15 20:40:55 -08003215 private void dumpInternal(PrintWriter pw) {
Jeff Brown96307042012-07-27 15:51:34 -07003216 pw.println("POWER MANAGER (dumpsys power)\n");
3217
Jeff Brown3b971592013-01-09 18:46:37 -08003218 final WirelessChargerDetector wcd;
Jeff Brown96307042012-07-27 15:51:34 -07003219 synchronized (mLock) {
3220 pw.println("Power Manager State:");
Dianne Hackborn0ef403e2017-01-24 18:22:15 -08003221 mConstants.dump(pw);
Jeff Brown96307042012-07-27 15:51:34 -07003222 pw.println(" mDirty=0x" + Integer.toHexString(mDirty));
Jeff Brownfbe96702014-11-19 18:30:58 -08003223 pw.println(" mWakefulness=" + PowerManagerInternal.wakefulnessToString(mWakefulness));
3224 pw.println(" mWakefulnessChanging=" + mWakefulnessChanging);
Jeff Brown96307042012-07-27 15:51:34 -07003225 pw.println(" mIsPowered=" + mIsPowered);
Jeff Brownf3fb8952012-10-02 20:57:05 -07003226 pw.println(" mPlugType=" + mPlugType);
Jeff Brown016ff142012-10-15 16:47:22 -07003227 pw.println(" mBatteryLevel=" + mBatteryLevel);
3228 pw.println(" mBatteryLevelWhenDreamStarted=" + mBatteryLevelWhenDreamStarted);
Jeff Brownec6aa592012-10-17 20:30:25 -07003229 pw.println(" mDockState=" + mDockState);
Jeff Brown96307042012-07-27 15:51:34 -07003230 pw.println(" mStayOn=" + mStayOn);
Jeff Brown93cbbb22012-10-04 13:18:36 -07003231 pw.println(" mProximityPositive=" + mProximityPositive);
Jeff Brown96307042012-07-27 15:51:34 -07003232 pw.println(" mBootCompleted=" + mBootCompleted);
3233 pw.println(" mSystemReady=" + mSystemReady);
Jeff Brown037c33e2014-04-09 00:31:55 -07003234 pw.println(" mHalAutoSuspendModeEnabled=" + mHalAutoSuspendModeEnabled);
3235 pw.println(" mHalInteractiveModeEnabled=" + mHalInteractiveModeEnabled);
Jeff Brown96307042012-07-27 15:51:34 -07003236 pw.println(" mWakeLockSummary=0x" + Integer.toHexString(mWakeLockSummary));
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003237 pw.print(" mNotifyLongScheduled=");
3238 if (mNotifyLongScheduled == 0) {
3239 pw.print("(none)");
3240 } else {
3241 TimeUtils.formatDuration(mNotifyLongScheduled, SystemClock.uptimeMillis(), pw);
3242 }
3243 pw.println();
3244 pw.print(" mNotifyLongDispatched=");
3245 if (mNotifyLongDispatched == 0) {
3246 pw.print("(none)");
3247 } else {
3248 TimeUtils.formatDuration(mNotifyLongDispatched, SystemClock.uptimeMillis(), pw);
3249 }
3250 pw.println();
3251 pw.print(" mNotifyLongNextCheck=");
3252 if (mNotifyLongNextCheck == 0) {
3253 pw.print("(none)");
3254 } else {
3255 TimeUtils.formatDuration(mNotifyLongNextCheck, SystemClock.uptimeMillis(), pw);
3256 }
3257 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003258 pw.println(" mUserActivitySummary=0x" + Integer.toHexString(mUserActivitySummary));
3259 pw.println(" mRequestWaitForNegativeProximity=" + mRequestWaitForNegativeProximity);
3260 pw.println(" mSandmanScheduled=" + mSandmanScheduled);
Jeff Brown26875502014-01-30 21:47:47 -08003261 pw.println(" mSandmanSummoned=" + mSandmanSummoned);
Dianne Hackborn14272302014-06-10 23:13:02 -07003262 pw.println(" mBatteryLevelLow=" + mBatteryLevelLow);
Dianne Hackborn08c47a52015-10-15 12:38:14 -07003263 pw.println(" mLightDeviceIdleMode=" + mLightDeviceIdleMode);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003264 pw.println(" mDeviceIdleMode=" + mDeviceIdleMode);
3265 pw.println(" mDeviceIdleWhitelist=" + Arrays.toString(mDeviceIdleWhitelist));
Amith Yamasaniaf575b92015-05-29 15:35:26 -07003266 pw.println(" mDeviceIdleTempWhitelist=" + Arrays.toString(mDeviceIdleTempWhitelist));
Jeff Brown96307042012-07-27 15:51:34 -07003267 pw.println(" mLastWakeTime=" + TimeUtils.formatUptime(mLastWakeTime));
3268 pw.println(" mLastSleepTime=" + TimeUtils.formatUptime(mLastSleepTime));
Jeff Brown96307042012-07-27 15:51:34 -07003269 pw.println(" mLastUserActivityTime=" + TimeUtils.formatUptime(mLastUserActivityTime));
3270 pw.println(" mLastUserActivityTimeNoChangeLights="
3271 + TimeUtils.formatUptime(mLastUserActivityTimeNoChangeLights));
Jeff Brown0a571122014-08-21 21:50:43 -07003272 pw.println(" mLastInteractivePowerHintTime="
3273 + TimeUtils.formatUptime(mLastInteractivePowerHintTime));
Jeff Browne333e672014-10-28 13:48:55 -07003274 pw.println(" mLastScreenBrightnessBoostTime="
3275 + TimeUtils.formatUptime(mLastScreenBrightnessBoostTime));
3276 pw.println(" mScreenBrightnessBoostInProgress="
3277 + mScreenBrightnessBoostInProgress);
Jeff Brown96307042012-07-27 15:51:34 -07003278 pw.println(" mDisplayReady=" + mDisplayReady);
3279 pw.println(" mHoldingWakeLockSuspendBlocker=" + mHoldingWakeLockSuspendBlocker);
Jeff Brown27f7a862012-12-12 15:43:31 -08003280 pw.println(" mHoldingDisplaySuspendBlocker=" + mHoldingDisplaySuspendBlocker);
Jeff Brown96307042012-07-27 15:51:34 -07003281
3282 pw.println();
3283 pw.println("Settings and Configuration:");
Jeff Brown037c33e2014-04-09 00:31:55 -07003284 pw.println(" mDecoupleHalAutoSuspendModeFromDisplayConfig="
3285 + mDecoupleHalAutoSuspendModeFromDisplayConfig);
3286 pw.println(" mDecoupleHalInteractiveModeFromDisplayConfig="
3287 + mDecoupleHalInteractiveModeFromDisplayConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003288 pw.println(" mWakeUpWhenPluggedOrUnpluggedConfig="
3289 + mWakeUpWhenPluggedOrUnpluggedConfig);
Bryce Lee584a4452014-10-21 15:55:55 -07003290 pw.println(" mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig="
3291 + mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3292 pw.println(" mTheaterModeEnabled="
3293 + mTheaterModeEnabled);
Jeff Brownec083212013-09-11 20:45:25 -07003294 pw.println(" mSuspendWhenScreenOffDueToProximityConfig="
3295 + mSuspendWhenScreenOffDueToProximityConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003296 pw.println(" mDreamsSupportedConfig=" + mDreamsSupportedConfig);
Jeff Brownec083212013-09-11 20:45:25 -07003297 pw.println(" mDreamsEnabledByDefaultConfig=" + mDreamsEnabledByDefaultConfig);
3298 pw.println(" mDreamsActivatedOnSleepByDefaultConfig="
3299 + mDreamsActivatedOnSleepByDefaultConfig);
3300 pw.println(" mDreamsActivatedOnDockByDefaultConfig="
3301 + mDreamsActivatedOnDockByDefaultConfig);
Jeff Brown26875502014-01-30 21:47:47 -08003302 pw.println(" mDreamsEnabledOnBatteryConfig="
3303 + mDreamsEnabledOnBatteryConfig);
3304 pw.println(" mDreamsBatteryLevelMinimumWhenPoweredConfig="
3305 + mDreamsBatteryLevelMinimumWhenPoweredConfig);
3306 pw.println(" mDreamsBatteryLevelMinimumWhenNotPoweredConfig="
3307 + mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3308 pw.println(" mDreamsBatteryLevelDrainCutoffConfig="
3309 + mDreamsBatteryLevelDrainCutoffConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003310 pw.println(" mDreamsEnabledSetting=" + mDreamsEnabledSetting);
John Spurlock1a868b72012-08-22 09:56:51 -04003311 pw.println(" mDreamsActivateOnSleepSetting=" + mDreamsActivateOnSleepSetting);
Jeff Brownec6aa592012-10-17 20:30:25 -07003312 pw.println(" mDreamsActivateOnDockSetting=" + mDreamsActivateOnDockSetting);
Lucas Dupin16cfe452018-02-08 13:14:50 -08003313 pw.println(" mDozeAfterScreenOff=" + mDozeAfterScreenOff);
Jeff Brown27736f52014-05-20 17:17:10 -07003314 pw.println(" mMinimumScreenOffTimeoutConfig=" + mMinimumScreenOffTimeoutConfig);
3315 pw.println(" mMaximumScreenDimDurationConfig=" + mMaximumScreenDimDurationConfig);
3316 pw.println(" mMaximumScreenDimRatioConfig=" + mMaximumScreenDimRatioConfig);
Jeff Brown96307042012-07-27 15:51:34 -07003317 pw.println(" mScreenOffTimeoutSetting=" + mScreenOffTimeoutSetting);
Jeff Brown05af6ad2014-09-30 20:54:30 -07003318 pw.println(" mSleepTimeoutSetting=" + mSleepTimeoutSetting);
Jeff Brown96307042012-07-27 15:51:34 -07003319 pw.println(" mMaximumScreenOffTimeoutFromDeviceAdmin="
3320 + mMaximumScreenOffTimeoutFromDeviceAdmin + " (enforced="
3321 + isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked() + ")");
3322 pw.println(" mStayOnWhilePluggedInSetting=" + mStayOnWhilePluggedInSetting);
3323 pw.println(" mScreenBrightnessSetting=" + mScreenBrightnessSetting);
3324 pw.println(" mScreenBrightnessModeSetting=" + mScreenBrightnessModeSetting);
3325 pw.println(" mScreenBrightnessOverrideFromWindowManager="
3326 + mScreenBrightnessOverrideFromWindowManager);
Jeff Brown1e3b98d2012-09-30 18:58:59 -07003327 pw.println(" mUserActivityTimeoutOverrideFromWindowManager="
3328 + mUserActivityTimeoutOverrideFromWindowManager);
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07003329 pw.println(" mUserInactiveOverrideFromWindowManager="
3330 + mUserInactiveOverrideFromWindowManager);
Jeff Brown970d4132014-07-19 11:33:47 -07003331 pw.println(" mDozeScreenStateOverrideFromDreamManager="
3332 + mDozeScreenStateOverrideFromDreamManager);
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003333 pw.println(" mDrawWakeLockOverrideFromSidekick=" + mDrawWakeLockOverrideFromSidekick);
Jeff Brown970d4132014-07-19 11:33:47 -07003334 pw.println(" mDozeScreenBrightnessOverrideFromDreamManager="
3335 + mDozeScreenBrightnessOverrideFromDreamManager);
Jeff Brown96307042012-07-27 15:51:34 -07003336 pw.println(" mScreenBrightnessSettingMinimum=" + mScreenBrightnessSettingMinimum);
3337 pw.println(" mScreenBrightnessSettingMaximum=" + mScreenBrightnessSettingMaximum);
3338 pw.println(" mScreenBrightnessSettingDefault=" + mScreenBrightnessSettingDefault);
Jason Monk27bbb2d2015-03-31 16:46:39 -04003339 pw.println(" mDoubleTapWakeEnabled=" + mDoubleTapWakeEnabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003340 pw.println(" mIsVrModeEnabled=" + mIsVrModeEnabled);
Pavel Grafov28939982017-10-03 15:11:52 +01003341 pw.println(" mForegroundProfile=" + mForegroundProfile);
Jeff Brown96307042012-07-27 15:51:34 -07003342
Pavel Grafov28939982017-10-03 15:11:52 +01003343 final long sleepTimeout = getSleepTimeoutLocked();
3344 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3345 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Jeff Brownff532542012-10-02 21:18:04 -07003346 pw.println();
Jeff Brown05af6ad2014-09-30 20:54:30 -07003347 pw.println("Sleep timeout: " + sleepTimeout + " ms");
Jeff Brownff532542012-10-02 21:18:04 -07003348 pw.println("Screen off timeout: " + screenOffTimeout + " ms");
3349 pw.println("Screen dim duration: " + screenDimDuration + " ms");
3350
Jeff Brown96307042012-07-27 15:51:34 -07003351 pw.println();
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003352 pw.print("UID states (changing=");
3353 pw.print(mUidsChanging);
3354 pw.print(" changed=");
3355 pw.print(mUidsChanged);
3356 pw.println("):");
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003357 for (int i=0; i<mUidState.size(); i++) {
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003358 final UidState state = mUidState.valueAt(i);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003359 pw.print(" UID "); UserHandle.formatUid(pw, mUidState.keyAt(i));
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003360 pw.print(": ");
3361 if (state.mActive) pw.print(" ACTIVE ");
3362 else pw.print("INACTIVE ");
3363 pw.print(" count=");
3364 pw.print(state.mNumWakeLocks);
3365 pw.print(" state=");
3366 pw.println(state.mProcState);
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07003367 }
3368
3369 pw.println();
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003370 pw.println("Looper state:");
3371 mHandler.getLooper().dump(new PrintWriterPrinter(pw), " ");
3372
3373 pw.println();
Jeff Brown96307042012-07-27 15:51:34 -07003374 pw.println("Wake Locks: size=" + mWakeLocks.size());
3375 for (WakeLock wl : mWakeLocks) {
3376 pw.println(" " + wl);
Joe Onorato8274a0e2010-10-05 17:38:09 -04003377 }
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003378
Jeff Brown96307042012-07-27 15:51:34 -07003379 pw.println();
3380 pw.println("Suspend Blockers: size=" + mSuspendBlockers.size());
3381 for (SuspendBlocker sb : mSuspendBlockers) {
3382 pw.println(" " + sb);
3383 }
3384
Jeff Brownc38c9be2012-10-04 13:16:19 -07003385 pw.println();
Jeff Brown131206b2014-04-08 17:27:14 -07003386 pw.println("Display Power: " + mDisplayPowerCallbacks);
Jeff Brown9e316a12012-10-08 19:17:06 -07003387
jackqdyulei455e90a2017-02-09 15:29:16 -08003388 mBatterySaverPolicy.dump(pw);
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003389 mBatterySaverStateMachine.dump(pw);
jackqdyulei455e90a2017-02-09 15:29:16 -08003390
Pavel Grafov28939982017-10-03 15:11:52 +01003391 pw.println();
3392 final int numProfiles = mProfilePowerState.size();
3393 pw.println("Profile power states: size=" + numProfiles);
3394 for (int i = 0; i < numProfiles; i++) {
3395 final ProfilePowerState profile = mProfilePowerState.valueAt(i);
3396 pw.print(" mUserId=");
3397 pw.print(profile.mUserId);
3398 pw.print(" mScreenOffTimeout=");
3399 pw.print(profile.mScreenOffTimeout);
3400 pw.print(" mWakeLockSummary=");
3401 pw.print(profile.mWakeLockSummary);
3402 pw.print(" mLastUserActivityTime=");
3403 pw.print(profile.mLastUserActivityTime);
3404 pw.print(" mLockingNotified=");
3405 pw.println(profile.mLockingNotified);
3406 }
3407
Jeff Brown3b971592013-01-09 18:46:37 -08003408 wcd = mWirelessChargerDetector;
Jeff Brown96307042012-07-27 15:51:34 -07003409 }
3410
Jeff Brown3b971592013-01-09 18:46:37 -08003411 if (wcd != null) {
3412 wcd.dump(pw);
3413 }
Jeff Brown96307042012-07-27 15:51:34 -07003414 }
3415
Netta P958d0a52017-02-07 11:20:55 -08003416 private void dumpProto(FileDescriptor fd) {
3417 final WirelessChargerDetector wcd;
3418 final ProtoOutputStream proto = new ProtoOutputStream(fd);
3419
3420 synchronized (mLock) {
3421 mConstants.dumpProto(proto);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003422 proto.write(PowerManagerServiceDumpProto.DIRTY, mDirty);
3423 proto.write(PowerManagerServiceDumpProto.WAKEFULNESS, mWakefulness);
3424 proto.write(PowerManagerServiceDumpProto.IS_WAKEFULNESS_CHANGING, mWakefulnessChanging);
3425 proto.write(PowerManagerServiceDumpProto.IS_POWERED, mIsPowered);
3426 proto.write(PowerManagerServiceDumpProto.PLUG_TYPE, mPlugType);
3427 proto.write(PowerManagerServiceDumpProto.BATTERY_LEVEL, mBatteryLevel);
Netta P958d0a52017-02-07 11:20:55 -08003428 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003429 PowerManagerServiceDumpProto.BATTERY_LEVEL_WHEN_DREAM_STARTED,
Netta P958d0a52017-02-07 11:20:55 -08003430 mBatteryLevelWhenDreamStarted);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003431 proto.write(PowerManagerServiceDumpProto.DOCK_STATE, mDockState);
3432 proto.write(PowerManagerServiceDumpProto.IS_STAY_ON, mStayOn);
3433 proto.write(PowerManagerServiceDumpProto.IS_PROXIMITY_POSITIVE, mProximityPositive);
3434 proto.write(PowerManagerServiceDumpProto.IS_BOOT_COMPLETED, mBootCompleted);
3435 proto.write(PowerManagerServiceDumpProto.IS_SYSTEM_READY, mSystemReady);
Netta P958d0a52017-02-07 11:20:55 -08003436 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003437 PowerManagerServiceDumpProto.IS_HAL_AUTO_SUSPEND_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003438 mHalAutoSuspendModeEnabled);
3439 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003440 PowerManagerServiceDumpProto.IS_HAL_AUTO_INTERACTIVE_MODE_ENABLED,
Netta P958d0a52017-02-07 11:20:55 -08003441 mHalInteractiveModeEnabled);
3442
Kweku Adamse6b00c22017-10-23 16:46:45 -07003443 final long activeWakeLocksToken = proto.start(PowerManagerServiceDumpProto.ACTIVE_WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003444 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003445 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_CPU,
Netta P958d0a52017-02-07 11:20:55 -08003446 (mWakeLockSummary & WAKE_LOCK_CPU) != 0);
3447 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003448 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003449 (mWakeLockSummary & WAKE_LOCK_SCREEN_BRIGHT) != 0);
3450 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003451 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003452 (mWakeLockSummary & WAKE_LOCK_SCREEN_DIM) != 0);
3453 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003454 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_BUTTON_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003455 (mWakeLockSummary & WAKE_LOCK_BUTTON_BRIGHT) != 0);
3456 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003457 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_PROXIMITY_SCREEN_OFF,
Netta P958d0a52017-02-07 11:20:55 -08003458 (mWakeLockSummary & WAKE_LOCK_PROXIMITY_SCREEN_OFF) != 0);
3459 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003460 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_STAY_AWAKE,
Netta P958d0a52017-02-07 11:20:55 -08003461 (mWakeLockSummary & WAKE_LOCK_STAY_AWAKE) != 0);
3462 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003463 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DOZE,
Netta P958d0a52017-02-07 11:20:55 -08003464 (mWakeLockSummary & WAKE_LOCK_DOZE) != 0);
3465 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003466 PowerManagerServiceDumpProto.ActiveWakeLocksProto.IS_DRAW,
Netta P958d0a52017-02-07 11:20:55 -08003467 (mWakeLockSummary & WAKE_LOCK_DRAW) != 0);
3468 proto.end(activeWakeLocksToken);
3469
Kweku Adamse6b00c22017-10-23 16:46:45 -07003470 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_SCHEDULED_MS, mNotifyLongScheduled);
3471 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_DISPATCHED_MS, mNotifyLongDispatched);
3472 proto.write(PowerManagerServiceDumpProto.NOTIFY_LONG_NEXT_CHECK_MS, mNotifyLongNextCheck);
Netta P958d0a52017-02-07 11:20:55 -08003473
Kweku Adamse6b00c22017-10-23 16:46:45 -07003474 final long userActivityToken = proto.start(PowerManagerServiceDumpProto.USER_ACTIVITY);
Netta P958d0a52017-02-07 11:20:55 -08003475 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003476 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_BRIGHT,
Netta P958d0a52017-02-07 11:20:55 -08003477 (mUserActivitySummary & USER_ACTIVITY_SCREEN_BRIGHT) != 0);
3478 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003479 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DIM,
Netta P958d0a52017-02-07 11:20:55 -08003480 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DIM) != 0);
3481 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003482 PowerManagerServiceDumpProto.UserActivityProto.IS_SCREEN_DREAM,
Netta P958d0a52017-02-07 11:20:55 -08003483 (mUserActivitySummary & USER_ACTIVITY_SCREEN_DREAM) != 0);
3484 proto.end(userActivityToken);
3485
3486 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003487 PowerManagerServiceDumpProto.IS_REQUEST_WAIT_FOR_NEGATIVE_PROXIMITY,
Netta P958d0a52017-02-07 11:20:55 -08003488 mRequestWaitForNegativeProximity);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003489 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SCHEDULED, mSandmanScheduled);
3490 proto.write(PowerManagerServiceDumpProto.IS_SANDMAN_SUMMONED, mSandmanSummoned);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003491 proto.write(PowerManagerServiceDumpProto.IS_BATTERY_LEVEL_LOW, mBatteryLevelLow);
3492 proto.write(PowerManagerServiceDumpProto.IS_LIGHT_DEVICE_IDLE_MODE, mLightDeviceIdleMode);
3493 proto.write(PowerManagerServiceDumpProto.IS_DEVICE_IDLE_MODE, mDeviceIdleMode);
Netta P958d0a52017-02-07 11:20:55 -08003494
3495 for (int id : mDeviceIdleWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003496 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003497 }
3498 for (int id : mDeviceIdleTempWhitelist) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003499 proto.write(PowerManagerServiceDumpProto.DEVICE_IDLE_TEMP_WHITELIST, id);
Netta P958d0a52017-02-07 11:20:55 -08003500 }
3501
Kweku Adamse6b00c22017-10-23 16:46:45 -07003502 proto.write(PowerManagerServiceDumpProto.LAST_WAKE_TIME_MS, mLastWakeTime);
3503 proto.write(PowerManagerServiceDumpProto.LAST_SLEEP_TIME_MS, mLastSleepTime);
3504 proto.write(PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_MS, mLastUserActivityTime);
Netta P958d0a52017-02-07 11:20:55 -08003505 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003506 PowerManagerServiceDumpProto.LAST_USER_ACTIVITY_TIME_NO_CHANGE_LIGHTS_MS,
Netta P958d0a52017-02-07 11:20:55 -08003507 mLastUserActivityTimeNoChangeLights);
3508 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003509 PowerManagerServiceDumpProto.LAST_INTERACTIVE_POWER_HINT_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003510 mLastInteractivePowerHintTime);
3511 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003512 PowerManagerServiceDumpProto.LAST_SCREEN_BRIGHTNESS_BOOST_TIME_MS,
Netta P958d0a52017-02-07 11:20:55 -08003513 mLastScreenBrightnessBoostTime);
3514 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003515 PowerManagerServiceDumpProto.IS_SCREEN_BRIGHTNESS_BOOST_IN_PROGRESS,
Netta P958d0a52017-02-07 11:20:55 -08003516 mScreenBrightnessBoostInProgress);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003517 proto.write(PowerManagerServiceDumpProto.IS_DISPLAY_READY, mDisplayReady);
Netta P958d0a52017-02-07 11:20:55 -08003518 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003519 PowerManagerServiceDumpProto.IS_HOLDING_WAKE_LOCK_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003520 mHoldingWakeLockSuspendBlocker);
3521 proto.write(
Kweku Adamse6b00c22017-10-23 16:46:45 -07003522 PowerManagerServiceDumpProto.IS_HOLDING_DISPLAY_SUSPEND_BLOCKER,
Netta P958d0a52017-02-07 11:20:55 -08003523 mHoldingDisplaySuspendBlocker);
3524
3525 final long settingsAndConfigurationToken =
Kweku Adamse6b00c22017-10-23 16:46:45 -07003526 proto.start(PowerManagerServiceDumpProto.SETTINGS_AND_CONFIGURATION);
Netta P958d0a52017-02-07 11:20:55 -08003527 proto.write(
3528 PowerServiceSettingsAndConfigurationDumpProto
3529 .IS_DECOUPLE_HAL_AUTO_SUSPEND_MODE_FROM_DISPLAY_CONFIG,
3530 mDecoupleHalAutoSuspendModeFromDisplayConfig);
3531 proto.write(
3532 PowerServiceSettingsAndConfigurationDumpProto
3533 .IS_DECOUPLE_HAL_INTERACTIVE_MODE_FROM_DISPLAY_CONFIG,
3534 mDecoupleHalInteractiveModeFromDisplayConfig);
3535 proto.write(
3536 PowerServiceSettingsAndConfigurationDumpProto
3537 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_CONFIG,
3538 mWakeUpWhenPluggedOrUnpluggedConfig);
3539 proto.write(
3540 PowerServiceSettingsAndConfigurationDumpProto
3541 .IS_WAKE_UP_WHEN_PLUGGED_OR_UNPLUGGED_IN_THEATER_MODE_CONFIG,
3542 mWakeUpWhenPluggedOrUnpluggedInTheaterModeConfig);
3543 proto.write(
3544 PowerServiceSettingsAndConfigurationDumpProto.IS_THEATER_MODE_ENABLED,
3545 mTheaterModeEnabled);
3546 proto.write(
3547 PowerServiceSettingsAndConfigurationDumpProto
3548 .IS_SUSPEND_WHEN_SCREEN_OFF_DUE_TO_PROXIMITY_CONFIG,
3549 mSuspendWhenScreenOffDueToProximityConfig);
3550 proto.write(
3551 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_SUPPORTED_CONFIG,
3552 mDreamsSupportedConfig);
3553 proto.write(
3554 PowerServiceSettingsAndConfigurationDumpProto
3555 .ARE_DREAMS_ENABLED_BY_DEFAULT_CONFIG,
3556 mDreamsEnabledByDefaultConfig);
3557 proto.write(
3558 PowerServiceSettingsAndConfigurationDumpProto
3559 .ARE_DREAMS_ACTIVATED_ON_SLEEP_BY_DEFAULT_CONFIG,
3560 mDreamsActivatedOnSleepByDefaultConfig);
3561 proto.write(
3562 PowerServiceSettingsAndConfigurationDumpProto
3563 .ARE_DREAMS_ACTIVATED_ON_DOCK_BY_DEFAULT_CONFIG,
3564 mDreamsActivatedOnDockByDefaultConfig);
3565 proto.write(
3566 PowerServiceSettingsAndConfigurationDumpProto
3567 .ARE_DREAMS_ENABLED_ON_BATTERY_CONFIG,
3568 mDreamsEnabledOnBatteryConfig);
3569 proto.write(
3570 PowerServiceSettingsAndConfigurationDumpProto
3571 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_POWERED_CONFIG,
3572 mDreamsBatteryLevelMinimumWhenPoweredConfig);
3573 proto.write(
3574 PowerServiceSettingsAndConfigurationDumpProto
3575 .DREAMS_BATTERY_LEVEL_MINIMUM_WHEN_NOT_POWERED_CONFIG,
3576 mDreamsBatteryLevelMinimumWhenNotPoweredConfig);
3577 proto.write(
3578 PowerServiceSettingsAndConfigurationDumpProto
3579 .DREAMS_BATTERY_LEVEL_DRAIN_CUTOFF_CONFIG,
3580 mDreamsBatteryLevelDrainCutoffConfig);
3581 proto.write(
3582 PowerServiceSettingsAndConfigurationDumpProto.ARE_DREAMS_ENABLED_SETTING,
3583 mDreamsEnabledSetting);
3584 proto.write(
3585 PowerServiceSettingsAndConfigurationDumpProto
3586 .ARE_DREAMS_ACTIVATE_ON_SLEEP_SETTING,
3587 mDreamsActivateOnSleepSetting);
3588 proto.write(
3589 PowerServiceSettingsAndConfigurationDumpProto
3590 .ARE_DREAMS_ACTIVATE_ON_DOCK_SETTING,
3591 mDreamsActivateOnDockSetting);
3592 proto.write(
3593 PowerServiceSettingsAndConfigurationDumpProto.IS_DOZE_AFTER_SCREEN_OFF_CONFIG,
Lucas Dupin16cfe452018-02-08 13:14:50 -08003594 mDozeAfterScreenOff);
Netta P958d0a52017-02-07 11:20:55 -08003595 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003596 PowerServiceSettingsAndConfigurationDumpProto
3597 .MINIMUM_SCREEN_OFF_TIMEOUT_CONFIG_MS,
3598 mMinimumScreenOffTimeoutConfig);
3599 proto.write(
3600 PowerServiceSettingsAndConfigurationDumpProto
3601 .MAXIMUM_SCREEN_DIM_DURATION_CONFIG_MS,
3602 mMaximumScreenDimDurationConfig);
3603 proto.write(
3604 PowerServiceSettingsAndConfigurationDumpProto.MAXIMUM_SCREEN_DIM_RATIO_CONFIG,
3605 mMaximumScreenDimRatioConfig);
3606 proto.write(
3607 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_OFF_TIMEOUT_SETTING_MS,
3608 mScreenOffTimeoutSetting);
3609 proto.write(
3610 PowerServiceSettingsAndConfigurationDumpProto.SLEEP_TIMEOUT_SETTING_MS,
3611 mSleepTimeoutSetting);
3612 proto.write(
3613 PowerServiceSettingsAndConfigurationDumpProto
3614 .MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_MS,
Pavel Grafov28939982017-10-03 15:11:52 +01003615 // Clamp to int32
3616 Math.min(mMaximumScreenOffTimeoutFromDeviceAdmin, Integer.MAX_VALUE));
Netta P958d0a52017-02-07 11:20:55 -08003617 proto.write(
3618 PowerServiceSettingsAndConfigurationDumpProto
3619 .IS_MAXIMUM_SCREEN_OFF_TIMEOUT_FROM_DEVICE_ADMIN_ENFORCED_LOCKED,
3620 isMaximumScreenOffTimeoutFromDeviceAdminEnforcedLocked());
3621
3622 final long stayOnWhilePluggedInToken =
3623 proto.start(
3624 PowerServiceSettingsAndConfigurationDumpProto.STAY_ON_WHILE_PLUGGED_IN);
3625 proto.write(
3626 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3627 .IS_STAY_ON_WHILE_PLUGGED_IN_AC,
3628 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_AC) != 0));
3629 proto.write(
3630 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3631 .IS_STAY_ON_WHILE_PLUGGED_IN_USB,
3632 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_USB) != 0));
3633 proto.write(
3634 PowerServiceSettingsAndConfigurationDumpProto.StayOnWhilePluggedInProto
3635 .IS_STAY_ON_WHILE_PLUGGED_IN_WIRELESS,
3636 ((mStayOnWhilePluggedInSetting & BatteryManager.BATTERY_PLUGGED_WIRELESS)
3637 != 0));
3638 proto.end(stayOnWhilePluggedInToken);
3639
3640 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003641 PowerServiceSettingsAndConfigurationDumpProto.SCREEN_BRIGHTNESS_MODE_SETTING,
3642 mScreenBrightnessModeSetting);
3643 proto.write(
3644 PowerServiceSettingsAndConfigurationDumpProto
3645 .SCREEN_BRIGHTNESS_OVERRIDE_FROM_WINDOW_MANAGER,
3646 mScreenBrightnessOverrideFromWindowManager);
3647 proto.write(
3648 PowerServiceSettingsAndConfigurationDumpProto
3649 .USER_ACTIVITY_TIMEOUT_OVERRIDE_FROM_WINDOW_MANAGER_MS,
3650 mUserActivityTimeoutOverrideFromWindowManager);
3651 proto.write(
3652 PowerServiceSettingsAndConfigurationDumpProto
3653 .IS_USER_INACTIVE_OVERRIDE_FROM_WINDOW_MANAGER,
3654 mUserInactiveOverrideFromWindowManager);
3655 proto.write(
3656 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003657 .DOZE_SCREEN_STATE_OVERRIDE_FROM_DREAM_MANAGER,
3658 mDozeScreenStateOverrideFromDreamManager);
3659 proto.write(
3660 PowerServiceSettingsAndConfigurationDumpProto
Ivan Podogov56bc6d02018-02-26 16:04:24 +00003661 .DRAW_WAKE_LOCK_OVERRIDE_FROM_SIDEKICK,
3662 mDrawWakeLockOverrideFromSidekick);
3663 proto.write(
3664 PowerServiceSettingsAndConfigurationDumpProto
Netta P958d0a52017-02-07 11:20:55 -08003665 .DOZED_SCREEN_BRIGHTNESS_OVERRIDE_FROM_DREAM_MANAGER,
3666 mDozeScreenBrightnessOverrideFromDreamManager);
3667
3668 final long screenBrightnessSettingLimitsToken =
3669 proto.start(
3670 PowerServiceSettingsAndConfigurationDumpProto
3671 .SCREEN_BRIGHTNESS_SETTING_LIMITS);
3672 proto.write(
3673 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3674 .SETTING_MINIMUM,
3675 mScreenBrightnessSettingMinimum);
3676 proto.write(
3677 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3678 .SETTING_MAXIMUM,
3679 mScreenBrightnessSettingMaximum);
3680 proto.write(
3681 PowerServiceSettingsAndConfigurationDumpProto.ScreenBrightnessSettingLimitsProto
3682 .SETTING_DEFAULT,
3683 mScreenBrightnessSettingDefault);
Netta P958d0a52017-02-07 11:20:55 -08003684 proto.end(screenBrightnessSettingLimitsToken);
3685
3686 proto.write(
Netta P958d0a52017-02-07 11:20:55 -08003687 PowerServiceSettingsAndConfigurationDumpProto.IS_DOUBLE_TAP_WAKE_ENABLED,
3688 mDoubleTapWakeEnabled);
3689 proto.write(
3690 PowerServiceSettingsAndConfigurationDumpProto.IS_VR_MODE_ENABLED,
3691 mIsVrModeEnabled);
3692 proto.end(settingsAndConfigurationToken);
3693
Pavel Grafov28939982017-10-03 15:11:52 +01003694 final long sleepTimeout = getSleepTimeoutLocked();
3695 final long screenOffTimeout = getScreenOffTimeoutLocked(sleepTimeout);
3696 final long screenDimDuration = getScreenDimDurationLocked(screenOffTimeout);
Kweku Adamse6b00c22017-10-23 16:46:45 -07003697 proto.write(PowerManagerServiceDumpProto.SLEEP_TIMEOUT_MS, sleepTimeout);
3698 proto.write(PowerManagerServiceDumpProto.SCREEN_OFF_TIMEOUT_MS, screenOffTimeout);
3699 proto.write(PowerManagerServiceDumpProto.SCREEN_DIM_DURATION_MS, screenDimDuration);
3700 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGING, mUidsChanging);
3701 proto.write(PowerManagerServiceDumpProto.ARE_UIDS_CHANGED, mUidsChanged);
Netta P958d0a52017-02-07 11:20:55 -08003702
3703 for (int i = 0; i < mUidState.size(); i++) {
3704 final UidState state = mUidState.valueAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003705 final long uIDToken = proto.start(PowerManagerServiceDumpProto.UID_STATES);
Netta P958d0a52017-02-07 11:20:55 -08003706 final int uid = mUidState.keyAt(i);
Kweku Adams32198522017-10-25 15:12:34 -07003707 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID, uid);
3708 proto.write(PowerManagerServiceDumpProto.UidStateProto.UID_STRING, UserHandle.formatUid(uid));
3709 proto.write(PowerManagerServiceDumpProto.UidStateProto.IS_ACTIVE, state.mActive);
3710 proto.write(PowerManagerServiceDumpProto.UidStateProto.NUM_WAKE_LOCKS, state.mNumWakeLocks);
Bookatzdb026a22018-01-10 19:01:56 -08003711 proto.write(PowerManagerServiceDumpProto.UidStateProto.PROCESS_STATE,
3712 ActivityManager.processStateAmToProto(state.mProcState));
Netta P958d0a52017-02-07 11:20:55 -08003713 proto.end(uIDToken);
3714 }
3715
Makoto Onukia3cd7b92018-03-19 14:47:05 -07003716 mBatterySaverStateMachine.dumpProto(proto,
3717 PowerManagerServiceDumpProto.BATTERY_SAVER_STATE_MACHINE);
3718
Kweku Adamse6b00c22017-10-23 16:46:45 -07003719 mHandler.getLooper().writeToProto(proto, PowerManagerServiceDumpProto.LOOPER);
Netta P958d0a52017-02-07 11:20:55 -08003720
3721 for (WakeLock wl : mWakeLocks) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003722 wl.writeToProto(proto, PowerManagerServiceDumpProto.WAKE_LOCKS);
Netta P958d0a52017-02-07 11:20:55 -08003723 }
3724
3725 for (SuspendBlocker sb : mSuspendBlockers) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003726 sb.writeToProto(proto, PowerManagerServiceDumpProto.SUSPEND_BLOCKERS);
Netta P958d0a52017-02-07 11:20:55 -08003727 }
3728 wcd = mWirelessChargerDetector;
3729 }
3730
3731 if (wcd != null) {
Kweku Adamse6b00c22017-10-23 16:46:45 -07003732 wcd.writeToProto(proto, PowerManagerServiceDumpProto.WIRELESS_CHARGER_DETECTOR);
Netta P958d0a52017-02-07 11:20:55 -08003733 }
3734 proto.flush();
3735 }
3736
Jeff Brown96307042012-07-27 15:51:34 -07003737 private SuspendBlocker createSuspendBlockerLocked(String name) {
3738 SuspendBlocker suspendBlocker = new SuspendBlockerImpl(name);
3739 mSuspendBlockers.add(suspendBlocker);
3740 return suspendBlocker;
3741 }
3742
Daichi Hirono82ab9802016-03-02 13:23:29 +09003743 private void incrementBootCount() {
3744 synchronized (mLock) {
3745 int count;
3746 try {
3747 count = Settings.Global.getInt(
3748 getContext().getContentResolver(), Settings.Global.BOOT_COUNT);
3749 } catch (SettingNotFoundException e) {
3750 count = 0;
3751 }
3752 Settings.Global.putInt(
3753 getContext().getContentResolver(), Settings.Global.BOOT_COUNT, count + 1);
3754 }
3755 }
3756
Jeff Brown96307042012-07-27 15:51:34 -07003757 private static WorkSource copyWorkSource(WorkSource workSource) {
3758 return workSource != null ? new WorkSource(workSource) : null;
3759 }
3760
3761 private final class BatteryReceiver extends BroadcastReceiver {
3762 @Override
3763 public void onReceive(Context context, Intent intent) {
3764 synchronized (mLock) {
3765 handleBatteryStateChangedLocked();
Mike Lockwoodee2b0942009-11-09 14:09:02 -05003766 }
Mike Lockwood20f87d72009-11-05 16:08:51 -05003767 }
3768 }
3769
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003770 private final class DreamReceiver extends BroadcastReceiver {
3771 @Override
3772 public void onReceive(Context context, Intent intent) {
3773 synchronized (mLock) {
Jeff Brown62c82e42012-09-26 01:30:41 -07003774 scheduleSandmanLocked();
John Spurlockf4f6b4c2012-08-25 12:08:03 -04003775 }
3776 }
3777 }
3778
Jeff Brownd4935962012-09-25 13:27:20 -07003779 private final class UserSwitchedReceiver extends BroadcastReceiver {
3780 @Override
3781 public void onReceive(Context context, Intent intent) {
3782 synchronized (mLock) {
3783 handleSettingsChangedLocked();
3784 }
3785 }
3786 }
3787
Jeff Brownec6aa592012-10-17 20:30:25 -07003788 private final class DockReceiver extends BroadcastReceiver {
3789 @Override
3790 public void onReceive(Context context, Intent intent) {
3791 synchronized (mLock) {
3792 int dockState = intent.getIntExtra(Intent.EXTRA_DOCK_STATE,
3793 Intent.EXTRA_DOCK_STATE_UNDOCKED);
3794 if (mDockState != dockState) {
3795 mDockState = dockState;
3796 mDirty |= DIRTY_DOCK_STATE;
3797 updatePowerStateLocked();
3798 }
3799 }
3800 }
3801 }
3802
Jeff Brown96307042012-07-27 15:51:34 -07003803 private final class SettingsObserver extends ContentObserver {
3804 public SettingsObserver(Handler handler) {
3805 super(handler);
3806 }
3807
3808 @Override
3809 public void onChange(boolean selfChange, Uri uri) {
3810 synchronized (mLock) {
3811 handleSettingsChangedLocked();
3812 }
3813 }
3814 }
3815
Ruben Brunkc7be3be2016-04-01 17:07:51 -07003816 private final IVrStateCallbacks mVrStateCallbacks = new IVrStateCallbacks.Stub() {
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003817 @Override
3818 public void onVrStateChanged(boolean enabled) {
Ruchi Kandoi0d434042016-10-03 09:12:02 -07003819 powerHintInternal(PowerHint.VR_MODE, enabled ? 1 : 0);
Santos Cordon3107d292016-09-20 15:50:35 -07003820
3821 synchronized (mLock) {
3822 if (mIsVrModeEnabled != enabled) {
Santos Cordon21e9f2b2017-09-13 11:59:39 -07003823 setVrModeEnabled(enabled);
Santos Cordon3107d292016-09-20 15:50:35 -07003824 mDirty |= DIRTY_VR_MODE_CHANGED;
3825 updatePowerStateLocked();
3826 }
3827 }
Ruchi Kandoi03a04282016-03-14 17:09:17 -07003828 }
3829 };
3830
Jeff Brown96307042012-07-27 15:51:34 -07003831 /**
3832 * Handler for asynchronous operations performed by the power manager.
3833 */
3834 private final class PowerManagerHandler extends Handler {
3835 public PowerManagerHandler(Looper looper) {
Jeff Browna2910d02012-08-25 12:29:46 -07003836 super(looper, null, true /*async*/);
Jeff Brown96307042012-07-27 15:51:34 -07003837 }
3838
3839 @Override
3840 public void handleMessage(Message msg) {
3841 switch (msg.what) {
3842 case MSG_USER_ACTIVITY_TIMEOUT:
3843 handleUserActivityTimeout();
3844 break;
3845 case MSG_SANDMAN:
3846 handleSandman();
3847 break;
Jeff Browne333e672014-10-28 13:48:55 -07003848 case MSG_SCREEN_BRIGHTNESS_BOOST_TIMEOUT:
3849 handleScreenBrightnessBoostTimeout();
3850 break;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003851 case MSG_CHECK_FOR_LONG_WAKELOCKS:
3852 checkForLongWakeLocks();
3853 break;
Jeff Brown96307042012-07-27 15:51:34 -07003854 }
3855 }
3856 }
3857
3858 /**
3859 * Represents a wake lock that has been acquired by an application.
3860 */
3861 private final class WakeLock implements IBinder.DeathRecipient {
3862 public final IBinder mLock;
3863 public int mFlags;
3864 public String mTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003865 public final String mPackageName;
Jeff Brown96307042012-07-27 15:51:34 -07003866 public WorkSource mWorkSource;
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003867 public String mHistoryTag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003868 public final int mOwnerUid;
3869 public final int mOwnerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003870 public final UidState mUidState;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003871 public long mAcquireTime;
Dianne Hackborn713df152013-05-17 11:27:57 -07003872 public boolean mNotifiedAcquired;
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003873 public boolean mNotifiedLong;
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07003874 public boolean mDisabled;
Jeff Brown96307042012-07-27 15:51:34 -07003875
Dianne Hackborn713df152013-05-17 11:27:57 -07003876 public WakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003877 WorkSource workSource, String historyTag, int ownerUid, int ownerPid,
3878 UidState uidState) {
Jeff Brown96307042012-07-27 15:51:34 -07003879 mLock = lock;
3880 mFlags = flags;
3881 mTag = tag;
Dianne Hackborn713df152013-05-17 11:27:57 -07003882 mPackageName = packageName;
Jeff Brown96307042012-07-27 15:51:34 -07003883 mWorkSource = copyWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003884 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003885 mOwnerUid = ownerUid;
3886 mOwnerPid = ownerPid;
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07003887 mUidState = uidState;
Jeff Brown96307042012-07-27 15:51:34 -07003888 }
3889
3890 @Override
3891 public void binderDied() {
3892 PowerManagerService.this.handleWakeLockDeath(this);
3893 }
3894
3895 public boolean hasSameProperties(int flags, String tag, WorkSource workSource,
3896 int ownerUid, int ownerPid) {
3897 return mFlags == flags
3898 && mTag.equals(tag)
3899 && hasSameWorkSource(workSource)
3900 && mOwnerUid == ownerUid
3901 && mOwnerPid == ownerPid;
3902 }
3903
Dianne Hackborn713df152013-05-17 11:27:57 -07003904 public void updateProperties(int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003905 WorkSource workSource, String historyTag, int ownerUid, int ownerPid) {
Dianne Hackborn713df152013-05-17 11:27:57 -07003906 if (!mPackageName.equals(packageName)) {
3907 throw new IllegalStateException("Existing wake lock package name changed: "
3908 + mPackageName + " to " + packageName);
3909 }
3910 if (mOwnerUid != ownerUid) {
3911 throw new IllegalStateException("Existing wake lock uid changed: "
3912 + mOwnerUid + " to " + ownerUid);
3913 }
3914 if (mOwnerPid != ownerPid) {
3915 throw new IllegalStateException("Existing wake lock pid changed: "
3916 + mOwnerPid + " to " + ownerPid);
3917 }
Jeff Brown96307042012-07-27 15:51:34 -07003918 mFlags = flags;
3919 mTag = tag;
3920 updateWorkSource(workSource);
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08003921 mHistoryTag = historyTag;
Jeff Brown96307042012-07-27 15:51:34 -07003922 }
3923
3924 public boolean hasSameWorkSource(WorkSource workSource) {
Narayan Kamath607223f2018-02-19 14:09:02 +00003925 return Objects.equals(mWorkSource, workSource);
Jeff Brown96307042012-07-27 15:51:34 -07003926 }
3927
3928 public void updateWorkSource(WorkSource workSource) {
3929 mWorkSource = copyWorkSource(workSource);
3930 }
3931
3932 @Override
3933 public String toString() {
Dianne Hackbornd0db6f02016-07-18 14:14:20 -07003934 StringBuilder sb = new StringBuilder();
3935 sb.append(getLockLevelString());
3936 sb.append(" '");
3937 sb.append(mTag);
3938 sb.append("'");
3939 sb.append(getLockFlagsString());
3940 if (mDisabled) {
3941 sb.append(" DISABLED");
3942 }
3943 if (mNotifiedAcquired) {
3944 sb.append(" ACQ=");
3945 TimeUtils.formatDuration(mAcquireTime-SystemClock.uptimeMillis(), sb);
3946 }
3947 if (mNotifiedLong) {
3948 sb.append(" LONG");
3949 }
3950 sb.append(" (uid=");
3951 sb.append(mOwnerUid);
3952 if (mOwnerPid != 0) {
3953 sb.append(" pid=");
3954 sb.append(mOwnerPid);
3955 }
3956 if (mWorkSource != null) {
3957 sb.append(" ws=");
3958 sb.append(mWorkSource);
3959 }
3960 sb.append(")");
3961 return sb.toString();
Jeff Brown96307042012-07-27 15:51:34 -07003962 }
3963
Netta P958d0a52017-02-07 11:20:55 -08003964 public void writeToProto(ProtoOutputStream proto, long fieldId) {
3965 final long wakeLockToken = proto.start(fieldId);
3966 proto.write(WakeLockProto.LOCK_LEVEL, (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK));
3967 proto.write(WakeLockProto.TAG, mTag);
3968
3969 final long wakeLockFlagsToken = proto.start(WakeLockProto.FLAGS);
3970 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ACQUIRE_CAUSES_WAKEUP,
3971 (mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP)!=0);
3972 proto.write(WakeLockProto.WakeLockFlagsProto.IS_ON_AFTER_RELEASE,
3973 (mFlags & PowerManager.ON_AFTER_RELEASE)!=0);
3974 proto.end(wakeLockFlagsToken);
3975
3976 proto.write(WakeLockProto.IS_DISABLED, mDisabled);
3977 if (mNotifiedAcquired) {
3978 proto.write(WakeLockProto.ACQ_MS, mAcquireTime);
3979 }
3980 proto.write(WakeLockProto.IS_NOTIFIED_LONG, mNotifiedLong);
3981 proto.write(WakeLockProto.UID, mOwnerUid);
3982 proto.write(WakeLockProto.PID, mOwnerPid);
3983
3984 if (mWorkSource != null) {
3985 mWorkSource.writeToProto(proto, WakeLockProto.WORK_SOURCE);
3986 }
3987 proto.end(wakeLockToken);
3988 }
3989
Jeff Brown26875502014-01-30 21:47:47 -08003990 @SuppressWarnings("deprecation")
Jeff Brown96307042012-07-27 15:51:34 -07003991 private String getLockLevelString() {
3992 switch (mFlags & PowerManager.WAKE_LOCK_LEVEL_MASK) {
3993 case PowerManager.FULL_WAKE_LOCK:
3994 return "FULL_WAKE_LOCK ";
3995 case PowerManager.SCREEN_BRIGHT_WAKE_LOCK:
3996 return "SCREEN_BRIGHT_WAKE_LOCK ";
3997 case PowerManager.SCREEN_DIM_WAKE_LOCK:
3998 return "SCREEN_DIM_WAKE_LOCK ";
3999 case PowerManager.PARTIAL_WAKE_LOCK:
4000 return "PARTIAL_WAKE_LOCK ";
4001 case PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK:
4002 return "PROXIMITY_SCREEN_OFF_WAKE_LOCK";
Jeff Brown26875502014-01-30 21:47:47 -08004003 case PowerManager.DOZE_WAKE_LOCK:
4004 return "DOZE_WAKE_LOCK ";
Jeff Brownc2932a12014-11-20 18:04:05 -08004005 case PowerManager.DRAW_WAKE_LOCK:
4006 return "DRAW_WAKE_LOCK ";
Jeff Brown96307042012-07-27 15:51:34 -07004007 default:
4008 return "??? ";
4009 }
4010 }
4011
4012 private String getLockFlagsString() {
4013 String result = "";
4014 if ((mFlags & PowerManager.ACQUIRE_CAUSES_WAKEUP) != 0) {
4015 result += " ACQUIRE_CAUSES_WAKEUP";
4016 }
4017 if ((mFlags & PowerManager.ON_AFTER_RELEASE) != 0) {
4018 result += " ON_AFTER_RELEASE";
4019 }
4020 return result;
4021 }
4022 }
4023
4024 private final class SuspendBlockerImpl implements SuspendBlocker {
4025 private final String mName;
Jeff Brown3edf5272014-08-14 19:25:14 -07004026 private final String mTraceName;
Jeff Brown96307042012-07-27 15:51:34 -07004027 private int mReferenceCount;
4028
4029 public SuspendBlockerImpl(String name) {
4030 mName = name;
Jeff Brown3edf5272014-08-14 19:25:14 -07004031 mTraceName = "SuspendBlocker (" + name + ")";
Jeff Brown96307042012-07-27 15:51:34 -07004032 }
4033
4034 @Override
4035 protected void finalize() throws Throwable {
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004036 try {
Jeff Brown96307042012-07-27 15:51:34 -07004037 if (mReferenceCount != 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004038 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004039 + "\" was finalized without being released!");
4040 mReferenceCount = 0;
4041 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004042 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Mike Lockwood809ad0f2009-10-26 22:10:33 -04004043 }
4044 } finally {
Jeff Brown96307042012-07-27 15:51:34 -07004045 super.finalize();
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004046 }
4047 }
4048
Craig Mautner75fc9de2012-06-18 16:53:27 -07004049 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004050 public void acquire() {
4051 synchronized (this) {
4052 mReferenceCount += 1;
4053 if (mReferenceCount == 1) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004054 if (DEBUG_SPEW) {
4055 Slog.d(TAG, "Acquiring suspend blocker \"" + mName + "\".");
4056 }
Jeff Brown3edf5272014-08-14 19:25:14 -07004057 Trace.asyncTraceBegin(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004058 nativeAcquireSuspendBlocker(mName);
Craig Mautner37933682012-06-06 14:13:39 -07004059 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004060 }
4061 }
4062
Craig Mautner75fc9de2012-06-18 16:53:27 -07004063 @Override
Jeff Brown96307042012-07-27 15:51:34 -07004064 public void release() {
4065 synchronized (this) {
4066 mReferenceCount -= 1;
4067 if (mReferenceCount == 0) {
Jeff Brown27f7a862012-12-12 15:43:31 -08004068 if (DEBUG_SPEW) {
4069 Slog.d(TAG, "Releasing suspend blocker \"" + mName + "\".");
4070 }
Jeff Brown96307042012-07-27 15:51:34 -07004071 nativeReleaseSuspendBlocker(mName);
Jeff Brown3edf5272014-08-14 19:25:14 -07004072 Trace.asyncTraceEnd(Trace.TRACE_TAG_POWER, mTraceName, 0);
Jeff Brown96307042012-07-27 15:51:34 -07004073 } else if (mReferenceCount < 0) {
Jeff Brown3edf5272014-08-14 19:25:14 -07004074 Slog.wtf(TAG, "Suspend blocker \"" + mName
Jeff Brown96307042012-07-27 15:51:34 -07004075 + "\" was released without being acquired!", new Throwable());
4076 mReferenceCount = 0;
4077 }
4078 }
Mike Lockwood8738e0c2009-10-04 08:44:47 -04004079 }
Jeff Brown96307042012-07-27 15:51:34 -07004080
4081 @Override
4082 public String toString() {
4083 synchronized (this) {
4084 return mName + ": ref count=" + mReferenceCount;
4085 }
4086 }
Netta P958d0a52017-02-07 11:20:55 -08004087
4088 public void writeToProto(ProtoOutputStream proto, long fieldId) {
4089 final long sbToken = proto.start(fieldId);
4090 synchronized (this) {
4091 proto.write(SuspendBlockerProto.NAME, mName);
4092 proto.write(SuspendBlockerProto.REFERENCE_COUNT, mReferenceCount);
4093 }
4094 proto.end(sbToken);
4095 }
Jeff Brown96307042012-07-27 15:51:34 -07004096 }
Jeff Brownc38c9be2012-10-04 13:16:19 -07004097
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004098 static final class UidState {
4099 final int mUid;
4100 int mNumWakeLocks;
4101 int mProcState;
4102 boolean mActive;
4103
4104 UidState(int uid) {
4105 mUid = uid;
4106 }
4107 }
4108
Jeff Brown6f357d32014-01-15 20:40:55 -08004109 private final class BinderService extends IPowerManager.Stub {
Jocelyn Dangf2c38c12017-03-31 14:03:37 -07004110 @Override
4111 public void onShellCommand(FileDescriptor in, FileDescriptor out,
4112 FileDescriptor err, String[] args, ShellCallback callback,
4113 ResultReceiver resultReceiver) {
4114 (new PowerManagerShellCommand(this)).exec(
4115 this, in, out, err, args, callback, resultReceiver);
4116 }
4117
Jeff Brown6f357d32014-01-15 20:40:55 -08004118 @Override // Binder call
4119 public void acquireWakeLockWithUid(IBinder lock, int flags, String tag,
4120 String packageName, int uid) {
Dianne Hackbornef640cd2014-03-25 14:41:05 -07004121 if (uid < 0) {
4122 uid = Binder.getCallingUid();
4123 }
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004124 acquireWakeLock(lock, flags, tag, packageName, new WorkSource(uid), null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004125 }
4126
4127 @Override // Binder call
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004128 public void powerHint(int hintId, int data) {
Dianne Hackbornddef7e72014-07-09 16:39:14 -07004129 if (!mSystemReady) {
4130 // Service not ready yet, so who the heck cares about power hints, bah.
4131 return;
4132 }
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004133 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER, null);
Ruchi Kandoi15aedf52014-05-09 19:57:51 -07004134 powerHintInternal(hintId, data);
Ruchi Kandoif20a5eb2014-04-01 17:39:20 -07004135 }
4136
4137 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004138 public void acquireWakeLock(IBinder lock, int flags, String tag, String packageName,
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004139 WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004140 if (lock == null) {
4141 throw new IllegalArgumentException("lock must not be null");
4142 }
4143 if (packageName == null) {
4144 throw new IllegalArgumentException("packageName must not be null");
4145 }
4146 PowerManager.validateWakeLockParameters(flags, tag);
4147
4148 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Jeff Brown72671fb2014-08-21 21:41:09 -07004149 if ((flags & PowerManager.DOZE_WAKE_LOCK) != 0) {
4150 mContext.enforceCallingOrSelfPermission(
4151 android.Manifest.permission.DEVICE_POWER, null);
4152 }
Narayan Kamath81822022017-12-08 11:56:01 +00004153 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004154 mContext.enforceCallingOrSelfPermission(
4155 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4156 } else {
4157 ws = null;
4158 }
4159
4160 final int uid = Binder.getCallingUid();
4161 final int pid = Binder.getCallingPid();
4162 final long ident = Binder.clearCallingIdentity();
4163 try {
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08004164 acquireWakeLockInternal(lock, flags, tag, packageName, ws, historyTag, uid, pid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004165 } finally {
4166 Binder.restoreCallingIdentity(ident);
4167 }
4168 }
4169
4170 @Override // Binder call
4171 public void releaseWakeLock(IBinder lock, int flags) {
4172 if (lock == null) {
4173 throw new IllegalArgumentException("lock must not be null");
4174 }
4175
4176 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
4177
4178 final long ident = Binder.clearCallingIdentity();
4179 try {
4180 releaseWakeLockInternal(lock, flags);
4181 } finally {
4182 Binder.restoreCallingIdentity(ident);
4183 }
4184 }
4185
4186 @Override // Binder call
4187 public void updateWakeLockUids(IBinder lock, int[] uids) {
4188 WorkSource ws = null;
4189
4190 if (uids != null) {
4191 ws = new WorkSource();
4192 // XXX should WorkSource have a way to set uids as an int[] instead of adding them
4193 // one at a time?
4194 for (int i = 0; i < uids.length; i++) {
4195 ws.add(uids[i]);
4196 }
4197 }
Dianne Hackborn4590e522014-03-24 13:36:46 -07004198 updateWakeLockWorkSource(lock, ws, null);
Jeff Brown6f357d32014-01-15 20:40:55 -08004199 }
4200
4201 @Override // Binder call
Dianne Hackborn4590e522014-03-24 13:36:46 -07004202 public void updateWakeLockWorkSource(IBinder lock, WorkSource ws, String historyTag) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004203 if (lock == null) {
4204 throw new IllegalArgumentException("lock must not be null");
4205 }
4206
4207 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WAKE_LOCK, null);
Narayan Kamath81822022017-12-08 11:56:01 +00004208 if (ws != null && !ws.isEmpty()) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004209 mContext.enforceCallingOrSelfPermission(
4210 android.Manifest.permission.UPDATE_DEVICE_STATS, null);
4211 } else {
4212 ws = null;
4213 }
4214
Dianne Hackbornd953c532014-08-16 18:17:38 -07004215 final int callingUid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004216 final long ident = Binder.clearCallingIdentity();
4217 try {
Dianne Hackbornd953c532014-08-16 18:17:38 -07004218 updateWakeLockWorkSourceInternal(lock, ws, historyTag, callingUid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004219 } finally {
4220 Binder.restoreCallingIdentity(ident);
4221 }
4222 }
4223
4224 @Override // Binder call
4225 public boolean isWakeLockLevelSupported(int level) {
4226 final long ident = Binder.clearCallingIdentity();
4227 try {
4228 return isWakeLockLevelSupportedInternal(level);
4229 } finally {
4230 Binder.restoreCallingIdentity(ident);
4231 }
4232 }
4233
4234 @Override // Binder call
4235 public void userActivity(long eventTime, int event, int flags) {
4236 final long now = SystemClock.uptimeMillis();
4237 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DEVICE_POWER)
Jeff Brown0a571122014-08-21 21:50:43 -07004238 != PackageManager.PERMISSION_GRANTED
4239 && mContext.checkCallingOrSelfPermission(
4240 android.Manifest.permission.USER_ACTIVITY)
4241 != PackageManager.PERMISSION_GRANTED) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004242 // Once upon a time applications could call userActivity().
4243 // Now we require the DEVICE_POWER permission. Log a warning and ignore the
4244 // request instead of throwing a SecurityException so we don't break old apps.
4245 synchronized (mLock) {
4246 if (now >= mLastWarningAboutUserActivityPermission + (5 * 60 * 1000)) {
4247 mLastWarningAboutUserActivityPermission = now;
4248 Slog.w(TAG, "Ignoring call to PowerManager.userActivity() because the "
Jeff Brown0a571122014-08-21 21:50:43 -07004249 + "caller does not have DEVICE_POWER or USER_ACTIVITY "
4250 + "permission. Please fix your app! "
Jeff Brown6f357d32014-01-15 20:40:55 -08004251 + " pid=" + Binder.getCallingPid()
4252 + " uid=" + Binder.getCallingUid());
4253 }
4254 }
4255 return;
4256 }
4257
Jim Millerdca15d22015-06-16 20:55:13 -07004258 if (eventTime > now) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004259 throw new IllegalArgumentException("event time must not be in the future");
4260 }
4261
4262 final int uid = Binder.getCallingUid();
4263 final long ident = Binder.clearCallingIdentity();
4264 try {
4265 userActivityInternal(eventTime, event, flags, uid);
4266 } finally {
4267 Binder.restoreCallingIdentity(ident);
4268 }
4269 }
4270
4271 @Override // Binder call
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004272 public void wakeUp(long eventTime, String reason, String opPackageName) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004273 if (eventTime > SystemClock.uptimeMillis()) {
4274 throw new IllegalArgumentException("event time must not be in the future");
4275 }
4276
4277 mContext.enforceCallingOrSelfPermission(
4278 android.Manifest.permission.DEVICE_POWER, null);
4279
Jeff Brownc12035c2014-08-13 18:52:25 -07004280 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004281 final long ident = Binder.clearCallingIdentity();
4282 try {
Dianne Hackborn280a64e2015-07-13 14:48:08 -07004283 wakeUpInternal(eventTime, reason, uid, opPackageName, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004284 } finally {
4285 Binder.restoreCallingIdentity(ident);
4286 }
4287 }
4288
4289 @Override // Binder call
Jeff Brown6d8fd272014-05-20 21:24:38 -07004290 public void goToSleep(long eventTime, int reason, int flags) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004291 if (eventTime > SystemClock.uptimeMillis()) {
4292 throw new IllegalArgumentException("event time must not be in the future");
4293 }
4294
4295 mContext.enforceCallingOrSelfPermission(
4296 android.Manifest.permission.DEVICE_POWER, null);
4297
Jeff Brownc12035c2014-08-13 18:52:25 -07004298 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004299 final long ident = Binder.clearCallingIdentity();
4300 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004301 goToSleepInternal(eventTime, reason, flags, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004302 } finally {
4303 Binder.restoreCallingIdentity(ident);
4304 }
4305 }
4306
4307 @Override // Binder call
4308 public void nap(long eventTime) {
4309 if (eventTime > SystemClock.uptimeMillis()) {
4310 throw new IllegalArgumentException("event time must not be in the future");
4311 }
4312
4313 mContext.enforceCallingOrSelfPermission(
4314 android.Manifest.permission.DEVICE_POWER, null);
4315
Jeff Brownc12035c2014-08-13 18:52:25 -07004316 final int uid = Binder.getCallingUid();
Jeff Brown6f357d32014-01-15 20:40:55 -08004317 final long ident = Binder.clearCallingIdentity();
4318 try {
Jeff Brownc12035c2014-08-13 18:52:25 -07004319 napInternal(eventTime, uid);
Jeff Brown6f357d32014-01-15 20:40:55 -08004320 } finally {
4321 Binder.restoreCallingIdentity(ident);
4322 }
4323 }
4324
4325 @Override // Binder call
Jeff Brown037c33e2014-04-09 00:31:55 -07004326 public boolean isInteractive() {
Jeff Brown6f357d32014-01-15 20:40:55 -08004327 final long ident = Binder.clearCallingIdentity();
4328 try {
Jeff Brown037c33e2014-04-09 00:31:55 -07004329 return isInteractiveInternal();
Jeff Brown6f357d32014-01-15 20:40:55 -08004330 } finally {
4331 Binder.restoreCallingIdentity(ident);
4332 }
4333 }
4334
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004335 @Override // Binder call
4336 public boolean isPowerSaveMode() {
4337 final long ident = Binder.clearCallingIdentity();
4338 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004339 return mBatterySaverController.isEnabled();
Dianne Hackborneb94fa72014-06-03 17:48:12 -07004340 } finally {
4341 Binder.restoreCallingIdentity(ident);
4342 }
4343 }
4344
jackqdyulei455e90a2017-02-09 15:29:16 -08004345 // Binder call
4346 public PowerSaveState getPowerSaveState(@ServiceType int serviceType) {
4347 final long ident = Binder.clearCallingIdentity();
4348 try {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004349 return mBatterySaverPolicy.getBatterySaverPolicy(
4350 serviceType, mBatterySaverController.isEnabled());
jackqdyulei455e90a2017-02-09 15:29:16 -08004351 } finally {
4352 Binder.restoreCallingIdentity(ident);
4353 }
4354 }
4355
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004356 @Override // Binder call
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004357 public boolean setPowerSaveMode(boolean enabled) {
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004358 mContext.enforceCallingOrSelfPermission(
4359 android.Manifest.permission.DEVICE_POWER, null);
4360 final long ident = Binder.clearCallingIdentity();
4361 try {
Makoto Onukia3cd7b92018-03-19 14:47:05 -07004362 return setLowPowerModeInternal(enabled);
John Spurlock8d4e6cb2014-09-14 11:10:22 -04004363 } finally {
4364 Binder.restoreCallingIdentity(ident);
4365 }
4366 }
4367
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004368 @Override // Binder call
4369 public boolean isDeviceIdleMode() {
4370 final long ident = Binder.clearCallingIdentity();
4371 try {
4372 return isDeviceIdleModeInternal();
4373 } finally {
4374 Binder.restoreCallingIdentity(ident);
4375 }
4376 }
4377
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004378 @Override // Binder call
4379 public boolean isLightDeviceIdleMode() {
4380 final long ident = Binder.clearCallingIdentity();
4381 try {
4382 return isLightDeviceIdleModeInternal();
4383 } finally {
4384 Binder.restoreCallingIdentity(ident);
4385 }
4386 }
4387
Jeff Brown6f357d32014-01-15 20:40:55 -08004388 /**
Salvador Martineza6f7b252017-04-10 10:46:15 -07004389 * Gets the reason for the last time the phone had to reboot.
4390 *
4391 * @return The reason the phone last shut down as an int or
Makoto Onuki66a78122017-11-14 15:03:21 -08004392 * {@link PowerManager#SHUTDOWN_REASON_UNKNOWN} if the file could not be opened.
Salvador Martineza6f7b252017-04-10 10:46:15 -07004393 */
4394 @Override // Binder call
4395 public int getLastShutdownReason() {
4396 mContext.enforceCallingOrSelfPermission(
4397 android.Manifest.permission.DEVICE_POWER, null);
4398
4399 final long ident = Binder.clearCallingIdentity();
4400 try {
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004401 return getLastShutdownReasonInternal(LAST_REBOOT_PROPERTY);
Salvador Martineza6f7b252017-04-10 10:46:15 -07004402 } finally {
4403 Binder.restoreCallingIdentity(ident);
4404 }
4405 }
4406
4407 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004408 * Reboots the device.
4409 *
4410 * @param confirm If true, shows a reboot confirmation dialog.
4411 * @param reason The reason for the reboot, or null if none.
4412 * @param wait If true, this call waits for the reboot to complete and does not return.
4413 */
4414 @Override // Binder call
4415 public void reboot(boolean confirm, String reason, boolean wait) {
4416 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
Tao Baoe8a403d2015-12-31 07:44:55 -08004417 if (PowerManager.REBOOT_RECOVERY.equals(reason)
4418 || PowerManager.REBOOT_RECOVERY_UPDATE.equals(reason)) {
Doug Zongker3b0218b2014-01-14 12:29:06 -08004419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.RECOVERY, null);
4420 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004421
4422 final long ident = Binder.clearCallingIdentity();
4423 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004424 shutdownOrRebootInternal(HALT_MODE_REBOOT, confirm, reason, wait);
4425 } finally {
4426 Binder.restoreCallingIdentity(ident);
4427 }
4428 }
4429
4430 /**
4431 * Reboots the device into safe mode
4432 *
4433 * @param confirm If true, shows a reboot confirmation dialog.
4434 * @param wait If true, this call waits for the reboot to complete and does not return.
4435 */
4436 @Override // Binder call
4437 public void rebootSafeMode(boolean confirm, boolean wait) {
4438 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4439
4440 final long ident = Binder.clearCallingIdentity();
4441 try {
4442 shutdownOrRebootInternal(HALT_MODE_REBOOT_SAFE_MODE, confirm,
4443 PowerManager.REBOOT_SAFE_MODE, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004444 } finally {
4445 Binder.restoreCallingIdentity(ident);
4446 }
4447 }
4448
4449 /**
4450 * Shuts down the device.
4451 *
4452 * @param confirm If true, shows a shutdown confirmation dialog.
4453 * @param wait If true, this call waits for the shutdown to complete and does not return.
4454 */
4455 @Override // Binder call
Yusuke Sato705ffd12015-07-21 15:52:11 -07004456 public void shutdown(boolean confirm, String reason, boolean wait) {
Jeff Brown6f357d32014-01-15 20:40:55 -08004457 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4458
4459 final long ident = Binder.clearCallingIdentity();
4460 try {
Tony Mantlerb8009fd2016-03-14 15:55:35 -07004461 shutdownOrRebootInternal(HALT_MODE_SHUTDOWN, confirm, reason, wait);
Jeff Brown6f357d32014-01-15 20:40:55 -08004462 } finally {
4463 Binder.restoreCallingIdentity(ident);
4464 }
4465 }
4466
4467 /**
4468 * Crash the runtime (causing a complete restart of the Android framework).
4469 * Requires REBOOT permission. Mostly for testing. Should not return.
4470 */
4471 @Override // Binder call
4472 public void crash(String message) {
4473 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.REBOOT, null);
4474
4475 final long ident = Binder.clearCallingIdentity();
4476 try {
4477 crashInternal(message);
4478 } finally {
4479 Binder.restoreCallingIdentity(ident);
4480 }
4481 }
4482
4483 /**
4484 * Set the setting that determines whether the device stays on when plugged in.
4485 * The argument is a bit string, with each bit specifying a power source that,
4486 * when the device is connected to that source, causes the device to stay on.
4487 * See {@link android.os.BatteryManager} for the list of power sources that
4488 * can be specified. Current values include
4489 * {@link android.os.BatteryManager#BATTERY_PLUGGED_AC}
4490 * and {@link android.os.BatteryManager#BATTERY_PLUGGED_USB}
4491 *
4492 * Used by "adb shell svc power stayon ..."
4493 *
4494 * @param val an {@code int} containing the bits that specify which power sources
4495 * should cause the device to stay on.
4496 */
4497 @Override // Binder call
4498 public void setStayOnSetting(int val) {
Billy Lau6ad2d662015-07-18 00:26:58 +01004499 int uid = Binder.getCallingUid();
4500 // if uid is of root's, we permit this operation straight away
4501 if (uid != Process.ROOT_UID) {
4502 if (!Settings.checkAndNoteWriteSettingsOperation(mContext, uid,
4503 Settings.getPackageNameForUid(mContext, uid), true)) {
4504 return;
4505 }
4506 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004507
4508 final long ident = Binder.clearCallingIdentity();
4509 try {
4510 setStayOnSettingInternal(val);
4511 } finally {
4512 Binder.restoreCallingIdentity(ident);
4513 }
4514 }
4515
4516 /**
Jeff Brown6f357d32014-01-15 20:40:55 -08004517 * Used by the phone application to make the attention LED flash when ringing.
4518 */
4519 @Override // Binder call
4520 public void setAttentionLight(boolean on, int color) {
4521 mContext.enforceCallingOrSelfPermission(
4522 android.Manifest.permission.DEVICE_POWER, null);
4523
4524 final long ident = Binder.clearCallingIdentity();
4525 try {
4526 setAttentionLightInternal(on, color);
4527 } finally {
4528 Binder.restoreCallingIdentity(ident);
4529 }
4530 }
4531
4532 @Override // Binder call
Lucas Dupin16cfe452018-02-08 13:14:50 -08004533 public void setDozeAfterScreenOff(boolean on) {
4534 mContext.enforceCallingOrSelfPermission(
4535 android.Manifest.permission.DEVICE_POWER, null);
4536
4537 final long ident = Binder.clearCallingIdentity();
4538 try {
4539 setDozeAfterScreenOffInternal(on);
4540 } finally {
4541 Binder.restoreCallingIdentity(ident);
4542 }
4543 }
4544
4545 @Override // Binder call
Jeff Browne333e672014-10-28 13:48:55 -07004546 public void boostScreenBrightness(long eventTime) {
4547 if (eventTime > SystemClock.uptimeMillis()) {
4548 throw new IllegalArgumentException("event time must not be in the future");
4549 }
4550
4551 mContext.enforceCallingOrSelfPermission(
4552 android.Manifest.permission.DEVICE_POWER, null);
4553
4554 final int uid = Binder.getCallingUid();
4555 final long ident = Binder.clearCallingIdentity();
4556 try {
4557 boostScreenBrightnessInternal(eventTime, uid);
4558 } finally {
4559 Binder.restoreCallingIdentity(ident);
4560 }
4561 }
4562
4563 @Override // Binder call
Bryce Lee84d6c0f2015-03-17 10:43:08 -07004564 public boolean isScreenBrightnessBoosted() {
4565 final long ident = Binder.clearCallingIdentity();
4566 try {
4567 return isScreenBrightnessBoostedInternal();
4568 } finally {
4569 Binder.restoreCallingIdentity(ident);
4570 }
4571 }
4572
4573 @Override // Binder call
Jeff Brown6f357d32014-01-15 20:40:55 -08004574 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06004575 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Brown6f357d32014-01-15 20:40:55 -08004576
4577 final long ident = Binder.clearCallingIdentity();
Netta P958d0a52017-02-07 11:20:55 -08004578
4579 boolean isDumpProto = false;
4580 for (String arg : args) {
4581 if (arg.equals("--proto")) {
4582 isDumpProto = true;
4583 }
4584 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004585 try {
Netta P958d0a52017-02-07 11:20:55 -08004586 if (isDumpProto) {
4587 dumpProto(fd);
4588 } else {
4589 dumpInternal(pw);
4590 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004591 } finally {
4592 Binder.restoreCallingIdentity(ident);
4593 }
4594 }
4595 }
4596
Salvador Martineza6f7b252017-04-10 10:46:15 -07004597 @VisibleForTesting
Mark Salyzyne65c0c62017-08-15 07:53:47 -07004598 // lastRebootReasonProperty argument to permit testing
4599 int getLastShutdownReasonInternal(String lastRebootReasonProperty) {
4600 String line = SystemProperties.get(lastRebootReasonProperty);
Michael Wright9199d0c2017-05-10 21:35:13 +01004601 if (line == null) {
4602 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4603 }
Salvador Martineza6f7b252017-04-10 10:46:15 -07004604 switch (line) {
4605 case REASON_SHUTDOWN:
4606 return PowerManager.SHUTDOWN_REASON_SHUTDOWN;
4607 case REASON_REBOOT:
4608 return PowerManager.SHUTDOWN_REASON_REBOOT;
4609 case REASON_USERREQUESTED:
4610 return PowerManager.SHUTDOWN_REASON_USER_REQUESTED;
4611 case REASON_THERMAL_SHUTDOWN:
4612 return PowerManager.SHUTDOWN_REASON_THERMAL_SHUTDOWN;
Sudheer Shanka292637f2017-09-25 10:36:23 -07004613 case REASON_LOW_BATTERY:
4614 return PowerManager.SHUTDOWN_REASON_LOW_BATTERY;
4615 case REASON_BATTERY_THERMAL_STATE:
4616 return PowerManager.SHUTDOWN_REASON_BATTERY_THERMAL;
Salvador Martineza6f7b252017-04-10 10:46:15 -07004617 default:
4618 return PowerManager.SHUTDOWN_REASON_UNKNOWN;
4619 }
4620 }
4621
Jeff Brown4ccb8232014-01-16 22:16:42 -08004622 private final class LocalService extends PowerManagerInternal {
Jeff Brown6f357d32014-01-15 20:40:55 -08004623 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004624 public void setScreenBrightnessOverrideFromWindowManager(int screenBrightness) {
4625 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4626 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4627 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
Jeff Brown6f357d32014-01-15 20:40:55 -08004628 }
Jeff Brown970d4132014-07-19 11:33:47 -07004629 setScreenBrightnessOverrideFromWindowManagerInternal(screenBrightness);
Jeff Brown6f357d32014-01-15 20:40:55 -08004630 }
4631
Jeff Brown6f357d32014-01-15 20:40:55 -08004632 @Override
Jeff Brown970d4132014-07-19 11:33:47 -07004633 public void setDozeOverrideFromDreamManager(int screenState, int screenBrightness) {
4634 switch (screenState) {
4635 case Display.STATE_UNKNOWN:
4636 case Display.STATE_OFF:
4637 case Display.STATE_DOZE:
4638 case Display.STATE_DOZE_SUSPEND:
Chris Phoenix10a4a642017-09-25 13:21:00 -07004639 case Display.STATE_ON_SUSPEND:
Jeff Brown970d4132014-07-19 11:33:47 -07004640 case Display.STATE_ON:
Santos Cordon3107d292016-09-20 15:50:35 -07004641 case Display.STATE_VR:
Jeff Brown970d4132014-07-19 11:33:47 -07004642 break;
4643 default:
4644 screenState = Display.STATE_UNKNOWN;
4645 break;
4646 }
4647 if (screenBrightness < PowerManager.BRIGHTNESS_DEFAULT
4648 || screenBrightness > PowerManager.BRIGHTNESS_ON) {
4649 screenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
4650 }
4651 setDozeOverrideFromDreamManagerInternal(screenState, screenBrightness);
4652 }
4653
Jeff Brown6f357d32014-01-15 20:40:55 -08004654 @Override
Nick Armstrong-Crews56ecfcc2015-09-07 21:46:50 -07004655 public void setUserInactiveOverrideFromWindowManager() {
4656 setUserInactiveOverrideFromWindowManagerInternal();
4657 }
4658
4659 @Override
Jeff Brown6f357d32014-01-15 20:40:55 -08004660 public void setUserActivityTimeoutOverrideFromWindowManager(long timeoutMillis) {
Jeff Brown970d4132014-07-19 11:33:47 -07004661 setUserActivityTimeoutOverrideFromWindowManagerInternal(timeoutMillis);
Jeff Brown6f357d32014-01-15 20:40:55 -08004662 }
4663
4664 @Override
Ivan Podogov56bc6d02018-02-26 16:04:24 +00004665 public void setDrawWakeLockOverrideFromSidekick(boolean keepState) {
4666 setDrawWakeLockOverrideFromSidekickInternal(keepState);
4667 }
4668
4669 @Override
Pavel Grafov28939982017-10-03 15:11:52 +01004670 public void setMaximumScreenOffTimeoutFromDeviceAdmin(@UserIdInt int userId, long timeMs) {
4671 setMaximumScreenOffTimeoutFromDeviceAdminInternal(userId, timeMs);
Jeff Brown5ce1cb22014-11-06 19:05:33 -08004672 }
4673
4674 @Override
jackqdyulei455e90a2017-02-09 15:29:16 -08004675 public PowerSaveState getLowPowerState(@ServiceType int serviceType) {
Makoto Onukibd7a6252018-05-10 13:41:39 -07004676 return mBatterySaverPolicy.getBatterySaverPolicy(serviceType,
4677 mBatterySaverController.isEnabled());
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004678 }
4679
4680 @Override
4681 public void registerLowPowerModeObserver(LowPowerModeListener listener) {
Makoto Onuki66a78122017-11-14 15:03:21 -08004682 mBatterySaverController.addListener(listener);
Dianne Hackborncbefd8d2014-05-14 11:42:00 -07004683 }
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004684
4685 @Override
Dianne Hackborn08c47a52015-10-15 12:38:14 -07004686 public boolean setDeviceIdleMode(boolean enabled) {
4687 return setDeviceIdleModeInternal(enabled);
4688 }
4689
4690 @Override
4691 public boolean setLightDeviceIdleMode(boolean enabled) {
4692 return setLightDeviceIdleModeInternal(enabled);
Dianne Hackborn8d66b3f2015-05-08 17:21:48 -07004693 }
4694
4695 @Override
4696 public void setDeviceIdleWhitelist(int[] appids) {
4697 setDeviceIdleWhitelistInternal(appids);
Dianne Hackborn88e98df2015-03-23 13:29:14 -07004698 }
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004699
4700 @Override
Amith Yamasaniaf575b92015-05-29 15:35:26 -07004701 public void setDeviceIdleTempWhitelist(int[] appids) {
4702 setDeviceIdleTempWhitelistInternal(appids);
4703 }
4704
4705 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004706 public void startUidChanges() {
4707 startUidChangesInternal();
4708 }
4709
4710 @Override
4711 public void finishUidChanges() {
4712 finishUidChangesInternal();
4713 }
4714
4715 @Override
Dianne Hackbornd23e0d62015-05-15 16:36:12 -07004716 public void updateUidProcState(int uid, int procState) {
4717 updateUidProcStateInternal(uid, procState);
4718 }
4719
4720 @Override
4721 public void uidGone(int uid) {
4722 uidGoneInternal(uid);
4723 }
Michael Wrighta4d22d72015-09-16 23:19:26 +01004724
4725 @Override
Dianne Hackbornd33c7cd2016-10-25 17:13:24 -07004726 public void uidActive(int uid) {
4727 uidActiveInternal(uid);
4728 }
4729
4730 @Override
4731 public void uidIdle(int uid) {
4732 uidIdleInternal(uid);
4733 }
4734
4735 @Override
Michael Wrighta4d22d72015-09-16 23:19:26 +01004736 public void powerHint(int hintId, int data) {
4737 powerHintInternal(hintId, data);
4738 }
Jeff Brown6f357d32014-01-15 20:40:55 -08004739 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004740}