blob: 93faa629b30772a4998c53ce02345ecda131a57c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
17package com.android.server;
18
Jeff Sharkey9911a282018-02-14 22:29:11 -070019import static android.app.AlarmManager.ELAPSED_REALTIME;
20import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
21import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
22import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
23import static android.app.AlarmManager.RTC;
24import static android.app.AlarmManager.RTC_WAKEUP;
25
Suprabh Shukla75edab12018-01-29 14:09:06 -080026import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080027import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020028import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070029import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070030import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070031import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070032import android.app.IAlarmCompleteListener;
33import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070035import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080037import android.app.usage.UsageStatsManager;
38import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070040import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070044import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070046import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
50import android.os.Binder;
51import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070052import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080054import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070056import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070058import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070059import android.os.RemoteException;
mswest463f4c99d2018-02-01 10:13:10 -080060import android.os.ResultReceiver;
61import android.os.ShellCallback;
62import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.SystemClock;
64import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080065import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070066import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070067import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020068import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080069import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020071import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080072import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080073import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080074import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070075import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020076import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070077import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080078import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080079import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080080import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020081import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070082import android.util.SparseLongArray;
Bookatz7948c872018-09-04 12:58:33 -070083import android.util.StatsLog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070084import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070085import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
Jeff Sharkey9911a282018-02-14 22:29:11 -070087import com.android.internal.annotations.GuardedBy;
88import com.android.internal.annotations.VisibleForTesting;
89import com.android.internal.util.ArrayUtils;
90import com.android.internal.util.DumpUtils;
91import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070092import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070093import com.android.server.AppStateTracker.Listener;
94
Christopher Tate4cb338d2013-07-26 13:11:31 -070095import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import java.io.FileDescriptor;
97import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070098import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -070099import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800101import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import java.util.Calendar;
103import java.util.Collections;
104import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500105import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700106import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700107import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200108import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700109import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400111import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800112import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Makoto Onuki2206af32017-11-21 16:25:35 -0800114/**
115 * Alarm manager implementaion.
116 *
117 * Unit test:
118 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
119 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700121 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
122 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700124 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 static final int TIME_CHANGED_MASK = 1 << 16;
126 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800127
Christopher Tatee0a22b32013-07-11 14:43:13 -0700128 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800130
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 static final boolean localLOGV = false;
133 static final boolean DEBUG_BATCH = localLOGV || false;
134 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200135 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700136 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800137 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700138 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800139 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700140 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700141 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 static final int ALARM_EVENT = 1;
143 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200144
Christopher Tatef2159712018-03-27 16:04:14 -0700145 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
146 static final int ACTIVE_INDEX = 0;
147 static final int WORKING_INDEX = 1;
148 static final int FREQUENT_INDEX = 2;
149 static final int RARE_INDEX = 3;
150 static final int NEVER_INDEX = 4;
151
Christopher Tate14a7bb02015-10-01 10:24:31 -0700152 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700155
Adam Lesinski182f73f2013-12-05 16:48:06 -0800156 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700157
Christopher Tate24cd46f2016-02-02 14:28:01 -0800158 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
159 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700160 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
161 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200162
Adam Lesinski182f73f2013-12-05 16:48:06 -0800163 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800164
Christopher Tate14a7bb02015-10-01 10:24:31 -0700165 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800166 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800167 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700168
Adam Lesinski182f73f2013-12-05 16:48:06 -0800169 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800170
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700171 // List of alarms per uid deferred due to user applied background restrictions on the source app
172 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800173 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800174 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700175 private long mNextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -0700176 private long mNextWakeUpSetAt;
177 private long mNextNonWakeUpSetAt;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700178 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800179 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800180 private long mLastTickSet;
181 private long mLastTickIssued; // elapsed
182 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800183 private long mLastTickAdded;
184 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800185 int mBroadcastRefCount = 0;
186 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700187 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700188 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
189 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800190 final AlarmHandler mHandler = new AlarmHandler();
191 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700192 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700194 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800195 PendingIntent mTimeTickSender;
196 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700197 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700198 boolean mInteractive = true;
199 long mNonInteractiveStartTime;
200 long mNonInteractiveTime;
201 long mLastAlarmDeliveryTime;
202 long mStartCurrentDelayTime;
203 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700204 long mLastTimeChangeClockTime;
205 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700206 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800207
Christopher Tatebb9cce52017-04-18 14:19:43 -0700208 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
209
210 /**
211 * This permission must be defined by the canonical System UI package,
212 * with protection level "signature".
213 */
214 private static final String SYSTEM_UI_SELF_PERMISSION =
215 "android.permission.systemui.IDENTITY";
216
217 /**
218 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
219 */
220 int mSystemUiUid;
221
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700222 /**
223 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700224 * used to determine the earliest we can dispatch the next such alarm. Times are in the
225 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700226 */
227 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
228
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800229 /**
230 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
231 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
232 */
233 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
234
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700235 final static class IdleDispatchEntry {
236 int uid;
237 String pkg;
238 String tag;
239 String op;
240 long elapsedRealtime;
241 long argRealtime;
242 }
243 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
244
Suprabh Shukla75edab12018-01-29 14:09:06 -0800245 interface Stats {
246 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800247 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800248 }
249
250 private final StatLogger mStatLogger = new StatLogger(new String[] {
251 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800252 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800253 });
254
Dianne Hackborna750a632015-06-16 17:18:23 -0700255 /**
256 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
257 */
258 Bundle mIdleOptions;
259
Jose Lima235510e2014-08-13 12:50:01 -0700260 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
261 new SparseArray<>();
262 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
263 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200264 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
265 new SparseBooleanArray();
266 private boolean mNextAlarmClockMayChange;
267
268 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700269 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
270 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200271
Makoto Onukie4918212018-02-06 11:30:15 -0800272 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800273 private boolean mAppStandbyParole;
274 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800275
Dianne Hackborna750a632015-06-16 17:18:23 -0700276 /**
277 * All times are in milliseconds. These constants are kept synchronized with the system
278 * global Settings. Any access to this class or its fields should be done while
279 * holding the AlarmManagerService.mLock lock.
280 */
281 private final class Constants extends ContentObserver {
282 // Key names stored in the settings value.
283 private static final String KEY_MIN_FUTURITY = "min_futurity";
284 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800285 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700286 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
287 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
288 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
289 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700290 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700291
Suprabh Shukla75edab12018-01-29 14:09:06 -0800292 // Keys for specifying throttling delay based on app standby bucketing
293 private final String[] KEYS_APP_STANDBY_DELAY = {
294 "standby_active_delay",
295 "standby_working_delay",
296 "standby_frequent_delay",
297 "standby_rare_delay",
298 "standby_never_delay",
299 };
300
Dianne Hackborna750a632015-06-16 17:18:23 -0700301 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
302 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800303 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700304 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700305 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700306 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700307 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800308 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
309 0, // Active
310 6 * 60_000, // Working
311 30 * 60_000, // Frequent
312 2 * 60 * 60_000, // Rare
313 10 * 24 * 60 * 60_000 // Never
314 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700315
Dianne Hackborna750a632015-06-16 17:18:23 -0700316 // Minimum futurity of a new alarm
317 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
318
319 // Minimum alarm recurrence interval
320 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
321
Christopher Tate22e919d2018-02-16 16:16:50 -0800322 // Maximum alarm recurrence interval
323 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
324
Dianne Hackborna750a632015-06-16 17:18:23 -0700325 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
326 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
327
328 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
329 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
330
331 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
332 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
333 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
334
Christopher Tate14a7bb02015-10-01 10:24:31 -0700335 // Direct alarm listener callback timeout
336 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
337
Suprabh Shukla75edab12018-01-29 14:09:06 -0800338 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
339
Dianne Hackborna750a632015-06-16 17:18:23 -0700340 private ContentResolver mResolver;
341 private final KeyValueListParser mParser = new KeyValueListParser(',');
342 private long mLastAllowWhileIdleWhitelistDuration = -1;
343
344 public Constants(Handler handler) {
345 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700346 updateAllowWhileIdleWhitelistDurationLocked();
347 }
348
349 public void start(ContentResolver resolver) {
350 mResolver = resolver;
351 mResolver.registerContentObserver(Settings.Global.getUriFor(
352 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
353 updateConstants();
354 }
355
Dianne Hackborna750a632015-06-16 17:18:23 -0700356 public void updateAllowWhileIdleWhitelistDurationLocked() {
357 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
358 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
359 BroadcastOptions opts = BroadcastOptions.makeBasic();
360 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
361 mIdleOptions = opts.toBundle();
362 }
363 }
364
365 @Override
366 public void onChange(boolean selfChange, Uri uri) {
367 updateConstants();
368 }
369
370 private void updateConstants() {
371 synchronized (mLock) {
372 try {
373 mParser.setString(Settings.Global.getString(mResolver,
374 Settings.Global.ALARM_MANAGER_CONSTANTS));
375 } catch (IllegalArgumentException e) {
376 // Failed to parse the settings string, log this and move on
377 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800378 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700379 }
380
381 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
382 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800383 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700384 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
385 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
386 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
387 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
388 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
389 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
390 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700391 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
392 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700393 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
394 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
395 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
396 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800397 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
398 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
399 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700400 updateAllowWhileIdleWhitelistDurationLocked();
401 }
402 }
403
404 void dump(PrintWriter pw) {
405 pw.println(" Settings:");
406
407 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
408 TimeUtils.formatDuration(MIN_FUTURITY, pw);
409 pw.println();
410
411 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
412 TimeUtils.formatDuration(MIN_INTERVAL, pw);
413 pw.println();
414
Christopher Tate22e919d2018-02-16 16:16:50 -0800415 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
416 TimeUtils.formatDuration(MAX_INTERVAL, pw);
417 pw.println();
418
Christopher Tate14a7bb02015-10-01 10:24:31 -0700419 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
420 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
421 pw.println();
422
Dianne Hackborna750a632015-06-16 17:18:23 -0700423 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
424 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
425 pw.println();
426
427 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
428 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
429 pw.println();
430
431 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
432 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
433 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800434
435 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
436 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
437 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
438 pw.println();
439 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700440 }
Kweku Adams61e03292017-10-19 14:27:12 -0700441
442 void dumpProto(ProtoOutputStream proto, long fieldId) {
443 final long token = proto.start(fieldId);
444
445 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
446 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800447 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700448 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
449 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
450 ALLOW_WHILE_IDLE_SHORT_TIME);
451 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
452 ALLOW_WHILE_IDLE_LONG_TIME);
453 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
454 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
455
456 proto.end(token);
457 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700458 }
459
460 final Constants mConstants;
461
Christopher Tate1590f1e2014-10-02 17:27:57 -0700462 // Alarm delivery ordering bookkeeping
463 static final int PRIO_TICK = 0;
464 static final int PRIO_WAKEUP = 1;
465 static final int PRIO_NORMAL = 2;
466
Dianne Hackborna750a632015-06-16 17:18:23 -0700467 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700468 int seq;
469 int priority;
470
471 PriorityClass() {
472 seq = mCurrentSeq - 1;
473 priority = PRIO_NORMAL;
474 }
475 }
476
Dianne Hackborna750a632015-06-16 17:18:23 -0700477 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700478 int mCurrentSeq = 0;
479
Dianne Hackborna750a632015-06-16 17:18:23 -0700480 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700481 public long when;
482 public int uid;
483 public String action;
484
485 public WakeupEvent(long theTime, int theUid, String theAction) {
486 when = theTime;
487 uid = theUid;
488 action = theAction;
489 }
490 }
491
Adam Lesinski182f73f2013-12-05 16:48:06 -0800492 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
493 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700494
Adrian Roosc42a1e12014-07-07 23:35:53 +0200495 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700496 long start; // These endpoints are always in ELAPSED
497 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700498 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700499
500 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
501
502 Batch() {
503 start = 0;
504 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700505 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700506 }
507
508 Batch(Alarm seed) {
509 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800510 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700511 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700512 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800513 if (seed.operation == mTimeTickSender) {
514 mLastTickAdded = System.currentTimeMillis();
515 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700516 }
517
518 int size() {
519 return alarms.size();
520 }
521
522 Alarm get(int index) {
523 return alarms.get(index);
524 }
525
526 boolean canHold(long whenElapsed, long maxWhen) {
527 return (end >= whenElapsed) && (start <= maxWhen);
528 }
529
530 boolean add(Alarm alarm) {
531 boolean newStart = false;
532 // narrows the batch if necessary; presumes that canHold(alarm) is true
533 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
534 if (index < 0) {
535 index = 0 - index - 1;
536 }
537 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800538 if (alarm.operation == mTimeTickSender) {
539 mLastTickAdded = System.currentTimeMillis();
540 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 if (DEBUG_BATCH) {
542 Slog.v(TAG, "Adding " + alarm + " to " + this);
543 }
544 if (alarm.whenElapsed > start) {
545 start = alarm.whenElapsed;
546 newStart = true;
547 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700548 if (alarm.maxWhenElapsed < end) {
549 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700551 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700552
553 if (DEBUG_BATCH) {
554 Slog.v(TAG, " => now " + this);
555 }
556 return newStart;
557 }
558
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800559 boolean remove(Alarm alarm) {
560 return remove(a -> (a == alarm));
561 }
562
Christopher Tate1d99c392017-12-07 16:54:04 -0800563 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 boolean didRemove = false;
565 long newStart = 0; // recalculate endpoints as we go
566 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700567 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700568 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800570 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700571 alarms.remove(i);
572 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200573 if (alarm.alarmClock != null) {
574 mNextAlarmClockMayChange = true;
575 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800576 if (alarm.operation == mTimeTickSender) {
577 mLastTickRemoved = System.currentTimeMillis();
578 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700579 } else {
580 if (alarm.whenElapsed > newStart) {
581 newStart = alarm.whenElapsed;
582 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700583 if (alarm.maxWhenElapsed < newEnd) {
584 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700586 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700587 i++;
588 }
589 }
590 if (didRemove) {
591 // commit the new batch bounds
592 start = newStart;
593 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700594 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700595 }
596 return didRemove;
597 }
598
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 boolean hasPackage(final String packageName) {
600 final int N = alarms.size();
601 for (int i = 0; i < N; i++) {
602 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700603 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700604 return true;
605 }
606 }
607 return false;
608 }
609
610 boolean hasWakeups() {
611 final int N = alarms.size();
612 for (int i = 0; i < N; i++) {
613 Alarm a = alarms.get(i);
614 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
615 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
616 return true;
617 }
618 }
619 return false;
620 }
621
622 @Override
623 public String toString() {
624 StringBuilder b = new StringBuilder(40);
625 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
626 b.append(" num="); b.append(size());
627 b.append(" start="); b.append(start);
628 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700629 if (flags != 0) {
630 b.append(" flgs=0x");
631 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700632 }
633 b.append('}');
634 return b.toString();
635 }
Kweku Adams61e03292017-10-19 14:27:12 -0700636
637 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
638 long nowRTC) {
639 final long token = proto.start(fieldId);
640
641 proto.write(BatchProto.START_REALTIME, start);
642 proto.write(BatchProto.END_REALTIME, end);
643 proto.write(BatchProto.FLAGS, flags);
644 for (Alarm a : alarms) {
645 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
646 }
647
648 proto.end(token);
649 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700650 }
651
652 static class BatchTimeOrder implements Comparator<Batch> {
653 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800654 long when1 = b1.start;
655 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800656 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700657 return 1;
658 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800659 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700660 return -1;
661 }
662 return 0;
663 }
664 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800665
666 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
667 @Override
668 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700669 // priority class trumps everything. TICK < WAKEUP < NORMAL
670 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
671 return -1;
672 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
673 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800674 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700675
676 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800677 if (lhs.whenElapsed < rhs.whenElapsed) {
678 return -1;
679 } else if (lhs.whenElapsed > rhs.whenElapsed) {
680 return 1;
681 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700682
683 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800684 return 0;
685 }
686 };
687
Christopher Tate1590f1e2014-10-02 17:27:57 -0700688 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
689 final int N = alarms.size();
690 for (int i = 0; i < N; i++) {
691 Alarm a = alarms.get(i);
692
693 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700694 if (a.operation != null
695 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700696 alarmPrio = PRIO_TICK;
697 } else if (a.wakeup) {
698 alarmPrio = PRIO_WAKEUP;
699 } else {
700 alarmPrio = PRIO_NORMAL;
701 }
702
703 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800704 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700705 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700706 if (packagePrio == null) {
707 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700708 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700709 }
710 a.priorityClass = packagePrio;
711
712 if (packagePrio.seq != mCurrentSeq) {
713 // first alarm we've seen in the current delivery generation from this package
714 packagePrio.priority = alarmPrio;
715 packagePrio.seq = mCurrentSeq;
716 } else {
717 // Multiple alarms from this package being delivered in this generation;
718 // bump the package's delivery class if it's warranted.
719 // TICK < WAKEUP < NORMAL
720 if (alarmPrio < packagePrio.priority) {
721 packagePrio.priority = alarmPrio;
722 }
723 }
724 }
725 }
726
Christopher Tatee0a22b32013-07-11 14:43:13 -0700727 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800728 static final long MIN_FUZZABLE_INTERVAL = 10000;
729 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700730 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
731
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700732 // set to non-null if in idle mode; while in this mode, any alarms we don't want
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700733 // to run during this time are placed in mPendingWhileIdleAlarms
734 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700735 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700736 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700737
Jeff Brownb880d882014-02-10 19:47:07 -0800738 public AlarmManagerService(Context context) {
739 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700740 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800741
Christopher Tate1d99c392017-12-07 16:54:04 -0800742 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800743 }
744
Christopher Tatee0a22b32013-07-11 14:43:13 -0700745 static long convertToElapsed(long when, int type) {
746 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
747 if (isRtc) {
748 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
749 }
750 return when;
751 }
752
753 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
754 // calculate the end of our nominal delivery window for the alarm.
755 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
756 // Current heuristic: batchable window is 75% of either the recurrence interval
757 // [for a periodic alarm] or of the time from now to the desired delivery time,
758 // with a minimum delay/interval of 10 seconds, under which we will simply not
759 // defer the alarm.
760 long futurity = (interval == 0)
761 ? (triggerAtTime - now)
762 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700763 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700764 futurity = 0;
765 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800766 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700767 }
768
769 // returns true if the batch was added at the head
770 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
771 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
772 if (index < 0) {
773 index = 0 - index - 1;
774 }
775 list.add(index, newBatch);
776 return (index == 0);
777 }
778
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800779 private void insertAndBatchAlarmLocked(Alarm alarm) {
780 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
781 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
782
783 if (whichBatch < 0) {
784 addBatchLocked(mAlarmBatches, new Batch(alarm));
785 } else {
786 final Batch batch = mAlarmBatches.get(whichBatch);
787 if (batch.add(alarm)) {
788 // The start time of this batch advanced, so batch ordering may
789 // have just been broken. Move it to where it now belongs.
790 mAlarmBatches.remove(whichBatch);
791 addBatchLocked(mAlarmBatches, batch);
792 }
793 }
794 }
795
Christopher Tate385e4982013-07-23 18:22:29 -0700796 // Return the index of the matching batch, or -1 if none found.
797 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700798 final int N = mAlarmBatches.size();
799 for (int i = 0; i < N; i++) {
800 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700801 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700802 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700803 }
804 }
Christopher Tate385e4982013-07-23 18:22:29 -0700805 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700806 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800807 /** @return total count of the alarms in a set of alarm batches. */
808 static int getAlarmCount(ArrayList<Batch> batches) {
809 int ret = 0;
810
811 final int size = batches.size();
812 for (int i = 0; i < size; i++) {
813 ret += batches.get(i).size();
814 }
815 return ret;
816 }
817
818 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
819 if (alarms.size() == 0) {
820 return false;
821 }
822 final int batchSize = alarms.size();
823 for (int j = 0; j < batchSize; j++) {
824 if (alarms.get(j).operation == mTimeTickSender) {
825 return true;
826 }
827 }
828 return false;
829 }
830
831 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
832 final int numBatches = batches.size();
833 for (int i = 0; i < numBatches; i++) {
834 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
835 return true;
836 }
837 }
838 return false;
839 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700840
841 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
842 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700843 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700844 rebatchAllAlarmsLocked(true);
845 }
846 }
847
848 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800849 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800850 final int oldCount =
851 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
852 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
853 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
854
Christopher Tate4cb338d2013-07-26 13:11:31 -0700855 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
856 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700857 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700858 final long nowElapsed = SystemClock.elapsedRealtime();
859 final int oldBatches = oldSet.size();
860 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
861 Batch batch = oldSet.get(batchNum);
862 final int N = batch.size();
863 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700864 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700865 }
866 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700867 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
868 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
869 + " to " + mPendingIdleUntil);
870 if (mPendingIdleUntil == null) {
871 // Somehow we lost this... we need to restore all of the pending alarms.
872 restorePendingWhileIdleAlarmsLocked();
873 }
874 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800875 final int newCount =
876 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
877 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
878 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
879
880 if (oldCount != newCount) {
881 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
882 }
883 if (oldHasTick != newHasTick) {
884 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
885 }
886
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700887 rescheduleKernelAlarmsLocked();
888 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800889 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700890 }
891
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800892 /**
893 * Re-orders the alarm batches based on newly evaluated send times based on the current
894 * app-standby buckets
895 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
896 * null indicates all
897 * @return True if there was any reordering done to the current list.
898 */
899 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
900 final long start = mStatLogger.getTime();
901 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
902
903 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
904 final Batch batch = mAlarmBatches.get(batchIndex);
905 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
906 final Alarm alarm = batch.get(alarmIndex);
907 final Pair<String, Integer> packageUser =
908 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
909 if (targetPackages != null && !targetPackages.contains(packageUser)) {
910 continue;
911 }
912 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
913 batch.remove(alarm);
914 rescheduledAlarms.add(alarm);
915 }
916 }
917 if (batch.size() == 0) {
918 mAlarmBatches.remove(batchIndex);
919 }
920 }
921 for (int i = 0; i < rescheduledAlarms.size(); i++) {
922 final Alarm a = rescheduledAlarms.get(i);
923 insertAndBatchAlarmLocked(a);
924 }
925
926 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
927 return rescheduledAlarms.size() > 0;
928 }
929
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700930 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
931 a.when = a.origWhen;
932 long whenElapsed = convertToElapsed(a.when, a.type);
933 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700934 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700935 // Exact
936 maxElapsed = whenElapsed;
937 } else {
938 // Not exact. Preserve any explicit window, otherwise recalculate
939 // the window based on the alarm's new futurity. Note that this
940 // reflects a policy of preferring timely to deferred delivery.
941 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800942 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700943 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
944 }
945 a.whenElapsed = whenElapsed;
946 a.maxWhenElapsed = maxElapsed;
947 setImplLocked(a, true, doValidate);
948 }
949
Christopher Tate22e919d2018-02-16 16:16:50 -0800950 static long clampPositive(long val) {
951 return (val >= 0) ? val : Long.MAX_VALUE;
952 }
953
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700954 /**
955 * Sends alarms that were blocked due to user applied background restrictions - either because
956 * the user lifted those or the uid came to foreground.
957 *
958 * @param uid uid to filter on
959 * @param packageName package to filter on, or null for all packages in uid
960 */
961 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
962 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
963 if (alarmsForUid == null || alarmsForUid.size() == 0) {
964 return;
965 }
966 final ArrayList<Alarm> alarmsToDeliver;
967 if (packageName != null) {
968 if (DEBUG_BG_LIMIT) {
969 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
970 }
971 alarmsToDeliver = new ArrayList<>();
972 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
973 final Alarm a = alarmsForUid.get(i);
974 if (a.matches(packageName)) {
975 alarmsToDeliver.add(alarmsForUid.remove(i));
976 }
977 }
978 if (alarmsForUid.size() == 0) {
979 mPendingBackgroundAlarms.remove(uid);
980 }
981 } else {
982 if (DEBUG_BG_LIMIT) {
983 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
984 }
985 alarmsToDeliver = alarmsForUid;
986 mPendingBackgroundAlarms.remove(uid);
987 }
988 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
989 }
990
Makoto Onuki2206af32017-11-21 16:25:35 -0800991 /**
992 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
993 * restricted.
994 *
995 * This is only called when the global "force all apps-standby" flag changes or when the
996 * power save whitelist changes, so it's okay to be slow.
997 */
998 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700999 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001000
1001 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1002 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1003
1004 if (alarmsToDeliver.size() > 0) {
1005 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
1006 }
1007 }
1008
1009 @VisibleForTesting
1010 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1011 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1012 Predicate<Alarm> isBackgroundRestricted) {
1013
1014 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1015 final int uid = pendingAlarms.keyAt(uidIndex);
1016 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1017
1018 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1019 final Alarm alarm = alarmsForUid.get(alarmIndex);
1020
1021 if (isBackgroundRestricted.test(alarm)) {
1022 continue;
1023 }
1024
1025 unrestrictedAlarms.add(alarm);
1026 alarmsForUid.remove(alarmIndex);
1027 }
1028
1029 if (alarmsForUid.size() == 0) {
1030 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001031 }
1032 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001033 }
1034
1035 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1036 final int N = alarms.size();
1037 boolean hasWakeup = false;
1038 for (int i = 0; i < N; i++) {
1039 final Alarm alarm = alarms.get(i);
1040 if (alarm.wakeup) {
1041 hasWakeup = true;
1042 }
1043 alarm.count = 1;
1044 // Recurring alarms may have passed several alarm intervals while the
1045 // alarm was kept pending. Send the appropriate trigger count.
1046 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001047 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001048 // Also schedule its next recurrence
1049 final long delta = alarm.count * alarm.repeatInterval;
1050 final long nextElapsed = alarm.whenElapsed + delta;
1051 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1052 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1053 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1054 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1055 // Kernel alarms will be rescheduled as needed in setImplLocked
1056 }
1057 }
1058 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1059 // No need to wakeup for non wakeup alarms
1060 if (mPendingNonWakeupAlarms.size() == 0) {
1061 mStartCurrentDelayTime = nowELAPSED;
1062 mNextNonWakeupDeliveryTime = nowELAPSED
1063 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1064 }
1065 mPendingNonWakeupAlarms.addAll(alarms);
1066 mNumDelayedAlarms += alarms.size();
1067 } else {
1068 if (DEBUG_BG_LIMIT) {
1069 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1070 }
1071 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1072 if (mPendingNonWakeupAlarms.size() > 0) {
1073 alarms.addAll(mPendingNonWakeupAlarms);
1074 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1075 mTotalDelayTime += thisDelayTime;
1076 if (mMaxDelayTime < thisDelayTime) {
1077 mMaxDelayTime = thisDelayTime;
1078 }
1079 mPendingNonWakeupAlarms.clear();
1080 }
1081 calculateDeliveryPriorities(alarms);
1082 Collections.sort(alarms, mAlarmDispatchComparator);
1083 deliverAlarmsLocked(alarms, nowELAPSED);
1084 }
1085 }
1086
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001087 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001088 if (RECORD_DEVICE_IDLE_ALARMS) {
1089 IdleDispatchEntry ent = new IdleDispatchEntry();
1090 ent.uid = 0;
1091 ent.pkg = "FINISH IDLE";
1092 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1093 mAllowWhileIdleDispatches.add(ent);
1094 }
1095
Dianne Hackborn35d54032015-04-23 10:30:43 -07001096 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001097 if (mPendingWhileIdleAlarms.size() > 0) {
1098 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1099 mPendingWhileIdleAlarms = new ArrayList<>();
1100 final long nowElapsed = SystemClock.elapsedRealtime();
1101 for (int i=alarms.size() - 1; i >= 0; i--) {
1102 Alarm a = alarms.get(i);
1103 reAddAlarmLocked(a, nowElapsed, false);
1104 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001105 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001106
1107 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001108 rescheduleKernelAlarmsLocked();
1109 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001110
1111 // And send a TIME_TICK right now, since it is important to get the UI updated.
1112 try {
1113 mTimeTickSender.send();
1114 } catch (PendingIntent.CanceledException e) {
1115 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001116 }
1117
Christopher Tate14a7bb02015-10-01 10:24:31 -07001118 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001119 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001120 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001121 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001122 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001123 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001124 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001125 final BroadcastStats mBroadcastStats;
1126 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001127 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001128
Christopher Tate14a7bb02015-10-01 10:24:31 -07001129 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1130 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1131 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001132 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001133 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001134 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001135 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001136 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001137 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001138 mBroadcastStats = (pendingIntent != null)
1139 ? service.getStatsLocked(pendingIntent)
1140 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001141 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001142 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001143 fs = new FilterStats(mBroadcastStats, mTag);
1144 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001145 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001146 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001147 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001148 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001149 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001150
1151 @Override
1152 public String toString() {
1153 return "InFlight{"
1154 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001155 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001156 + ", workSource=" + mWorkSource
1157 + ", uid=" + mUid
1158 + ", tag=" + mTag
1159 + ", broadcastStats=" + mBroadcastStats
1160 + ", filterStats=" + mFilterStats
1161 + ", alarmType=" + mAlarmType
1162 + "}";
1163 }
Kweku Adams61e03292017-10-19 14:27:12 -07001164
1165 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1166 final long token = proto.start(fieldId);
1167
1168 proto.write(InFlightProto.UID, mUid);
1169 proto.write(InFlightProto.TAG, mTag);
1170 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1171 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1172 if (mPendingIntent != null) {
1173 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1174 }
1175 if (mBroadcastStats != null) {
1176 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1177 }
1178 if (mFilterStats != null) {
1179 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1180 }
1181 if (mWorkSource != null) {
1182 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1183 }
1184
1185 proto.end(token);
1186 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001187 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001188
Adam Lesinski182f73f2013-12-05 16:48:06 -08001189 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001190 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001191 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001192
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001193 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001195 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001196 int numWakeup;
1197 long startTime;
1198 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001199
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001200 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001201 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001202 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001203 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001204
1205 @Override
1206 public String toString() {
1207 return "FilterStats{"
1208 + "tag=" + mTag
1209 + ", lastTime=" + lastTime
1210 + ", aggregateTime=" + aggregateTime
1211 + ", count=" + count
1212 + ", numWakeup=" + numWakeup
1213 + ", startTime=" + startTime
1214 + ", nesting=" + nesting
1215 + "}";
1216 }
Kweku Adams61e03292017-10-19 14:27:12 -07001217
1218 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1219 final long token = proto.start(fieldId);
1220
1221 proto.write(FilterStatsProto.TAG, mTag);
1222 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1223 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1224 proto.write(FilterStatsProto.COUNT, count);
1225 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1226 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1227 proto.write(FilterStatsProto.NESTING, nesting);
1228
1229 proto.end(token);
1230 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001231 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001232
Adam Lesinski182f73f2013-12-05 16:48:06 -08001233 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001234 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001235 final String mPackageName;
1236
1237 long aggregateTime;
1238 int count;
1239 int numWakeup;
1240 long startTime;
1241 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001242 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001243
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001244 BroadcastStats(int uid, String packageName) {
1245 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001246 mPackageName = packageName;
1247 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001248
1249 @Override
1250 public String toString() {
1251 return "BroadcastStats{"
1252 + "uid=" + mUid
1253 + ", packageName=" + mPackageName
1254 + ", aggregateTime=" + aggregateTime
1255 + ", count=" + count
1256 + ", numWakeup=" + numWakeup
1257 + ", startTime=" + startTime
1258 + ", nesting=" + nesting
1259 + "}";
1260 }
Kweku Adams61e03292017-10-19 14:27:12 -07001261
1262 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1263 final long token = proto.start(fieldId);
1264
1265 proto.write(BroadcastStatsProto.UID, mUid);
1266 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1267 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1268 proto.write(BroadcastStatsProto.COUNT, count);
1269 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1270 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1271 proto.write(BroadcastStatsProto.NESTING, nesting);
1272
1273 proto.end(token);
1274 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001276
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001277 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1278 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001279
1280 int mNumDelayedAlarms = 0;
1281 long mTotalDelayTime = 0;
1282 long mMaxDelayTime = 0;
1283
Adam Lesinski182f73f2013-12-05 16:48:06 -08001284 @Override
1285 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001286 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001287 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001288
1289 // We have to set current TimeZone info to kernel
1290 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001291 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001292
Christopher Tate247571462017-04-10 11:45:05 -07001293 // Also sure that we're booting with a halfway sensible current time
1294 if (mNativeData != 0) {
1295 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1296 if (System.currentTimeMillis() < systemBuildTime) {
1297 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1298 + ", advancing to build time " + systemBuildTime);
1299 setKernelTime(mNativeData, systemBuildTime);
1300 }
1301 }
1302
Christopher Tatebb9cce52017-04-18 14:19:43 -07001303 // Determine SysUI's uid
1304 final PackageManager packMan = getContext().getPackageManager();
1305 try {
1306 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1307 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1308 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1309 mSystemUiUid = sysUi.uid;
1310 } else {
1311 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1312 + " defined by non-privileged app " + sysUi.packageName
1313 + " - ignoring");
1314 }
1315 } catch (NameNotFoundException e) {
1316 }
1317
1318 if (mSystemUiUid <= 0) {
1319 Slog.wtf(TAG, "SysUI package not found!");
1320 }
1321
Adam Lesinski182f73f2013-12-05 16:48:06 -08001322 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001323 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001324
Adam Lesinski182f73f2013-12-05 16:48:06 -08001325 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001327 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001328 | Intent.FLAG_RECEIVER_FOREGROUND
1329 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001330 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001331 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001332 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1333 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001334 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001335 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001338 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 mClockReceiver.scheduleTimeTickEvent();
1340 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001341 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001343
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001344 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 AlarmThread waitThread = new AlarmThread();
1346 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001348 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001350
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001351 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001352 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001353 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1354 | ActivityManager.UID_OBSERVER_ACTIVE,
1355 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001356 } catch (RemoteException e) {
1357 // ignored; both services live in system_server
1358 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001359 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001361
1362 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001363 public void onBootPhase(int phase) {
1364 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1365 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001366 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001367 mLocalDeviceIdleController
1368 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001369 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1370 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001371
1372 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1373 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001374 }
1375 }
1376
1377 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 protected void finalize() throws Throwable {
1379 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001380 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 } finally {
1382 super.finalize();
1383 }
1384 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001385
mswest463f4c99d2018-02-01 10:13:10 -08001386 boolean setTimeImpl(long millis) {
1387 if (mNativeData == 0) {
1388 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1389 return false;
1390 }
1391
1392 synchronized (mLock) {
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001393 final long currentTimeMillis = System.currentTimeMillis();
1394 setKernelTime(mNativeData, millis);
1395 final TimeZone timeZone = TimeZone.getDefault();
1396 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1397 final int newTzOffset = timeZone.getOffset(millis);
1398 if (currentTzOffset != newTzOffset) {
1399 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
1400 setKernelTimezone(mNativeData, -(newTzOffset / 60000));
1401 }
1402 // The native implementation of setKernelTime can return -1 even when the kernel
1403 // time was set correctly, so assume setting kernel time was successful and always
1404 // return true.
1405 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001406 }
1407 }
1408
Adam Lesinski182f73f2013-12-05 16:48:06 -08001409 void setTimeZoneImpl(String tz) {
1410 if (TextUtils.isEmpty(tz)) {
1411 return;
David Christieebe51fc2013-07-26 13:23:29 -07001412 }
1413
Adam Lesinski182f73f2013-12-05 16:48:06 -08001414 TimeZone zone = TimeZone.getTimeZone(tz);
1415 // Prevent reentrant calls from stepping on each other when writing
1416 // the time zone property
1417 boolean timeZoneWasChanged = false;
1418 synchronized (this) {
1419 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1420 if (current == null || !current.equals(zone.getID())) {
1421 if (localLOGV) {
1422 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1423 }
1424 timeZoneWasChanged = true;
1425 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1426 }
1427
1428 // Update the kernel timezone information
1429 // Kernel tracks time offsets as 'minutes west of GMT'
1430 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001431 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001432 }
1433
1434 TimeZone.setDefault(null);
1435
1436 if (timeZoneWasChanged) {
1437 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001438 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001439 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001440 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001441 intent.putExtra("time-zone", zone.getID());
1442 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1443 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001445
Adam Lesinski182f73f2013-12-05 16:48:06 -08001446 void removeImpl(PendingIntent operation) {
1447 if (operation == null) {
1448 return;
1449 }
1450 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001451 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001452 }
1453 }
1454
1455 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001456 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1457 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1458 int callingUid, String callingPackage) {
1459 // must be *either* PendingIntent or AlarmReceiver, but not both
1460 if ((operation == null && directReceiver == null)
1461 || (operation != null && directReceiver != null)) {
1462 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1463 // NB: previous releases failed silently here, so we are continuing to do the same
1464 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 return;
1466 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001467
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001468 // Sanity check the window length. This will catch people mistakenly
1469 // trying to pass an end-of-window timestamp rather than a duration.
1470 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1471 Slog.w(TAG, "Window length " + windowLength
1472 + "ms suspiciously long; limiting to 1 hour");
1473 windowLength = AlarmManager.INTERVAL_HOUR;
1474 }
1475
Christopher Tate498c6cb2014-11-17 16:09:27 -08001476 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001477 // seconds when the API expects milliseconds, or apps trying shenanigans
1478 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001479 final long minInterval = mConstants.MIN_INTERVAL;
1480 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001481 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001482 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001483 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001484 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001485 } else if (interval > mConstants.MAX_INTERVAL) {
1486 Slog.w(TAG, "Suspiciously long interval " + interval
1487 + " millis; clamping");
1488 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001489 }
1490
Christopher Tatee0a22b32013-07-11 14:43:13 -07001491 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1492 throw new IllegalArgumentException("Invalid alarm type " + type);
1493 }
1494
Christopher Tate5f221e82013-07-30 17:13:15 -07001495 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001496 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001497 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001498 + " pid=" + what);
1499 triggerAtTime = 0;
1500 }
1501
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001502 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001503 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1504 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001505 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001506 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1507
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001508 final long maxElapsed;
1509 if (windowLength == AlarmManager.WINDOW_EXACT) {
1510 maxElapsed = triggerElapsed;
1511 } else if (windowLength < 0) {
1512 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001513 // Fix this window in place, so that as time approaches we don't collapse it.
1514 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001515 } else {
1516 maxElapsed = triggerElapsed + windowLength;
1517 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001519 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001520 if (DEBUG_BATCH) {
1521 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001522 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001523 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001524 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001525 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001526 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001527 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1528 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529 }
1530 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001531
Christopher Tate3e04b472013-10-21 17:51:31 -07001532 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001533 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1534 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1535 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001536 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001537 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1538 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001539 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001540 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001541 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1542 + " -- package not allowed to start");
1543 return;
1544 }
1545 } catch (RemoteException e) {
1546 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001547 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001548 setImplLocked(a, false, doValidate);
1549 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001550
Christopher Tatef2159712018-03-27 16:04:14 -07001551 /**
1552 * Return the minimum time that should elapse before an app in the specified bucket
1553 * can receive alarms again
1554 */
Suprabh Shukla75edab12018-01-29 14:09:06 -08001555 private long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001556 // UsageStats bucket values are treated as floors of their behavioral range.
1557 // In other words, a bucket value between WORKING and ACTIVE is treated as
1558 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1559 // values.
1560 final int index;
1561
1562 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1563 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1564 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1565 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1566 else index = ACTIVE_INDEX;
1567
1568 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001569 }
1570
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001571 /**
1572 * Adjusts the alarm delivery time based on the current app standby bucket.
1573 * @param alarm The alarm to adjust
1574 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001575 */
1576 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001577 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001578 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001579 }
1580 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001581 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001582 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001583 alarm.whenElapsed = alarm.expectedWhenElapsed;
1584 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1585 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001586 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001587 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001588 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001589 final long oldWhenElapsed = alarm.whenElapsed;
1590 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1591
Suprabh Shukla75edab12018-01-29 14:09:06 -08001592 final String sourcePackage = alarm.sourcePackage;
1593 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1594 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1595 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1596
1597 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1598 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1599 if (lastElapsed > 0) {
1600 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001601 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001602 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001603 } else {
1604 // app is now eligible to run alarms at the originally requested window.
1605 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001606 alarm.whenElapsed = alarm.expectedWhenElapsed;
1607 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001608 }
1609 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001610 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001611 }
1612
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001613 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1614 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001615 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001616 // The caller has given the time they want this to happen at, however we need
1617 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001618 // bring us out of idle at an earlier time.
1619 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001620 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001621 }
1622 // Add fuzz to make the alarm go off some time before the actual desired time.
1623 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001624 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001625 if (fuzz > 0) {
1626 if (mRandom == null) {
1627 mRandom = new Random();
1628 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001629 final int delta = mRandom.nextInt(fuzz);
1630 a.whenElapsed -= delta;
1631 if (false) {
1632 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1633 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1634 Slog.d(TAG, "Applied fuzz: " + fuzz);
1635 Slog.d(TAG, "Final delta: " + delta);
1636 Slog.d(TAG, "Final when: " + a.whenElapsed);
1637 }
1638 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001639 }
1640
1641 } else if (mPendingIdleUntil != null) {
1642 // We currently have an idle until alarm scheduled; if the new alarm has
1643 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001644 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1645 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1646 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001647 == 0) {
1648 mPendingWhileIdleAlarms.add(a);
1649 return;
1650 }
1651 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001652 if (RECORD_DEVICE_IDLE_ALARMS) {
1653 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1654 IdleDispatchEntry ent = new IdleDispatchEntry();
1655 ent.uid = a.uid;
1656 ent.pkg = a.operation.getCreatorPackage();
1657 ent.tag = a.operation.getTag("");
1658 ent.op = "SET";
1659 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1660 ent.argRealtime = a.whenElapsed;
1661 mAllowWhileIdleDispatches.add(ent);
1662 }
1663 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001664 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001665 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001667 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001668 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001669 }
1670
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001671 boolean needRebatch = false;
1672
1673 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001674 if (RECORD_DEVICE_IDLE_ALARMS) {
1675 if (mPendingIdleUntil == null) {
1676 IdleDispatchEntry ent = new IdleDispatchEntry();
1677 ent.uid = 0;
1678 ent.pkg = "START IDLE";
1679 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1680 mAllowWhileIdleDispatches.add(ent);
1681 }
1682 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001683 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1684 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1685 + " to " + a);
1686 }
1687
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001688 mPendingIdleUntil = a;
1689 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001690 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1691 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1692 mNextWakeFromIdle = a;
1693 // If this wake from idle is earlier than whatever was previously scheduled,
1694 // and we are currently idling, then we need to rebatch alarms in case the idle
1695 // until time needs to be updated.
1696 if (mPendingIdleUntil != null) {
1697 needRebatch = true;
1698 }
1699 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001700 }
1701
1702 if (!rebatching) {
1703 if (DEBUG_VALIDATE) {
1704 if (doValidate && !validateConsistencyLocked()) {
1705 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1706 + " when(hex)=" + Long.toHexString(a.when)
1707 + " whenElapsed=" + a.whenElapsed
1708 + " maxWhenElapsed=" + a.maxWhenElapsed
1709 + " interval=" + a.repeatInterval + " op=" + a.operation
1710 + " flags=0x" + Integer.toHexString(a.flags));
1711 rebatchAllAlarmsLocked(false);
1712 needRebatch = false;
1713 }
1714 }
1715
1716 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001717 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001718 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001719
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001720 rescheduleKernelAlarmsLocked();
1721 updateNextAlarmClockLocked();
1722 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001723 }
1724
Christopher Tate1d99c392017-12-07 16:54:04 -08001725 /**
1726 * System-process internal API
1727 */
1728 private final class LocalService implements AlarmManagerInternal {
1729 @Override
1730 public void removeAlarmsForUid(int uid) {
1731 synchronized (mLock) {
1732 removeLocked(uid);
1733 }
1734 }
1735 }
1736
1737 /**
1738 * Public-facing binder interface
1739 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001740 private final IBinder mService = new IAlarmManager.Stub() {
1741 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001742 public void set(String callingPackage,
1743 int type, long triggerAtTime, long windowLength, long interval, int flags,
1744 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1745 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001746 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001747
1748 // make sure the caller is not lying about which package should be blamed for
1749 // wakelock time spent in alarm delivery
1750 mAppOps.checkPackage(callingUid, callingPackage);
1751
1752 // Repeating alarms must use PendingIntent, not direct listener
1753 if (interval != 0) {
1754 if (directReceiver != null) {
1755 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1756 }
1757 }
1758
Adam Lesinski182f73f2013-12-05 16:48:06 -08001759 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001760 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001761 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001762 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001763 }
1764
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001765 // No incoming callers can request either WAKE_FROM_IDLE or
1766 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1767 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1768 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1769
1770 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1771 // manager when to come out of idle mode, which is only for DeviceIdleController.
1772 if (callingUid != Process.SYSTEM_UID) {
1773 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1774 }
1775
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001776 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001777 if (windowLength == AlarmManager.WINDOW_EXACT) {
1778 flags |= AlarmManager.FLAG_STANDALONE;
1779 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001780
1781 // If this alarm is for an alarm clock, then it must be standalone and we will
1782 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001783 if (alarmClock != null) {
1784 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001785
1786 // If the caller is a core system component or on the user's whitelist, and not calling
1787 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1788 // This means we will allow these alarms to go off as normal even while idle, with no
1789 // timing restrictions.
1790 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001791 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001792 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001793 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001794 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1795 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001796 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001797
Christopher Tate14a7bb02015-10-01 10:24:31 -07001798 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1799 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001800 }
Christopher Tate89779822012-08-31 14:40:03 -07001801
Adam Lesinski182f73f2013-12-05 16:48:06 -08001802 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001803 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001804 getContext().enforceCallingOrSelfPermission(
1805 "android.permission.SET_TIME",
1806 "setTime");
1807
mswest463f4c99d2018-02-01 10:13:10 -08001808 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001810
1811 @Override
1812 public void setTimeZone(String tz) {
1813 getContext().enforceCallingOrSelfPermission(
1814 "android.permission.SET_TIME_ZONE",
1815 "setTimeZone");
1816
1817 final long oldId = Binder.clearCallingIdentity();
1818 try {
1819 setTimeZoneImpl(tz);
1820 } finally {
1821 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001824
Adam Lesinski182f73f2013-12-05 16:48:06 -08001825 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001826 public void remove(PendingIntent operation, IAlarmListener listener) {
1827 if (operation == null && listener == null) {
1828 Slog.w(TAG, "remove() with no intent or listener");
1829 return;
1830 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001831
Christopher Tate14a7bb02015-10-01 10:24:31 -07001832 synchronized (mLock) {
1833 removeLocked(operation, listener);
1834 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001836
Adam Lesinski182f73f2013-12-05 16:48:06 -08001837 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001838 public long getNextWakeFromIdleTime() {
1839 return getNextWakeFromIdleTimeImpl();
1840 }
1841
1842 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001843 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001844 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1845 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1846 "getNextAlarmClock", null);
1847
1848 return getNextAlarmClockImpl(userId);
1849 }
1850
1851 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001852 public long currentNetworkTimeMillis() {
1853 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1854 if (time.hasCache()) {
1855 return time.currentTimeMillis();
1856 } else {
1857 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1858 }
1859 }
1860
1861 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001862 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001863 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001864
1865 if (args.length > 0 && "--proto".equals(args[0])) {
1866 dumpProto(fd);
1867 } else {
1868 dumpImpl(pw);
1869 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001870 }
mswest463f4c99d2018-02-01 10:13:10 -08001871
1872 @Override
1873 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1874 FileDescriptor err, String[] args, ShellCallback callback,
1875 ResultReceiver resultReceiver) {
1876 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1877 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001878 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001879
Adam Lesinski182f73f2013-12-05 16:48:06 -08001880 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 synchronized (mLock) {
1882 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001883 mConstants.dump(pw);
1884 pw.println();
1885
Makoto Onukie4918212018-02-06 11:30:15 -08001886 if (mAppStateTracker != null) {
1887 mAppStateTracker.dump(pw, " ");
1888 pw.println();
1889 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001890
Suprabh Shukla75edab12018-01-29 14:09:06 -08001891 pw.println(" App Standby Parole: " + mAppStandbyParole);
1892 pw.println();
1893
Christopher Tatee0a22b32013-07-11 14:43:13 -07001894 final long nowRTC = System.currentTimeMillis();
1895 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001896 final long nowUPTIME = SystemClock.uptimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001897 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001898
Dianne Hackborna750a632015-06-16 17:18:23 -07001899 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001900 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001901 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001902 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001903 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001904 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001905 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1906 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001907 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001908 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1909 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001910 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1911 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001912
1913 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1914 if (ssm != null) {
1915 pw.println();
1916 pw.print(" RuntimeStarted=");
1917 pw.print(sdf.format(
1918 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1919 if (ssm.isRuntimeRestarted()) {
1920 pw.print(" (Runtime restarted)");
1921 }
1922 pw.println();
1923 pw.print(" Runtime uptime (elapsed): ");
1924 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1925 pw.println();
1926 pw.print(" Runtime uptime (uptime): ");
1927 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1928 pw.println();
1929 }
1930
Dianne Hackbornc3527222015-05-13 14:03:20 -07001931 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001932 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001933 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001934 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1935 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001936 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001937 pw.print(" Max wakeup delay: ");
1938 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1939 pw.println();
1940 pw.print(" Time since last dispatch: ");
1941 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1942 pw.println();
1943 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001944 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001945 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001946
1947 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1948 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001949 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001950 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001951 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001952 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001953 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
1954 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08001955 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1956 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001957 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001958 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001959 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07001960
1961 pw.print(" Next kernel non-wakeup alarm: ");
1962 TimeUtils.formatDuration(getNextAlarm(mNativeData, ELAPSED_REALTIME), pw);
1963 pw.println();
1964 pw.print(" Next kernel wakeup alarm: ");
1965 TimeUtils.formatDuration(getNextAlarm(mNativeData, ELAPSED_REALTIME_WAKEUP), pw);
1966 pw.println();
1967
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001968 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001969 pw.print(" = "); pw.println(mLastWakeup);
1970 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1971 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001972 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001973
John Spurlock604a5ee2015-06-01 12:27:22 -04001974 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001975 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001976 final TreeSet<Integer> users = new TreeSet<>();
1977 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1978 users.add(mNextAlarmClockForUser.keyAt(i));
1979 }
1980 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1981 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1982 }
1983 for (int user : users) {
1984 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1985 final long time = next != null ? next.getTriggerTime() : 0;
1986 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001987 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001988 pw.print(" pendingSend:"); pw.print(pendingSend);
1989 pw.print(" time:"); pw.print(time);
1990 if (time > 0) {
1991 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1992 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1993 }
1994 pw.println();
1995 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001996 if (mAlarmBatches.size() > 0) {
1997 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001998 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001999 pw.println(mAlarmBatches.size());
2000 for (Batch b : mAlarmBatches) {
2001 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002002 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002003 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002004 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002005 pw.println();
2006 pw.println(" Pending user blocked background alarms: ");
2007 boolean blocked = false;
2008 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2009 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2010 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2011 blocked = true;
2012 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2013 }
2014 }
2015 if (!blocked) {
2016 pw.println(" none");
2017 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002018
Suprabh Shukla75edab12018-01-29 14:09:06 -08002019 pw.println(" mLastAlarmDeliveredForPackage:");
2020 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2021 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2022 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2023 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2024 pw.println();
2025 }
2026 pw.println();
2027
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002028 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002029 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002030 pw.println(" Idle mode state:");
2031 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002032 if (mPendingIdleUntil != null) {
2033 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002034 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002035 } else {
2036 pw.println("null");
2037 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002038 pw.println(" Pending alarms:");
2039 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002040 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002041 if (mNextWakeFromIdle != null) {
2042 pw.println();
2043 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002044 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002045 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002046
2047 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002048 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002049 if (mPendingNonWakeupAlarms.size() > 0) {
2050 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002051 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002052 } else {
2053 pw.println("(none)");
2054 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002055 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002056 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2057 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002058 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002059 pw.print(", max non-interactive time: ");
2060 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2061 pw.println();
2062
2063 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002064 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002065 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2066 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2067 pw.print(" Listener send count: "); pw.println(mListenerCount);
2068 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002069 pw.println();
2070
Christopher Tate7f2a0352015-12-08 10:24:33 -08002071 if (mInFlight.size() > 0) {
2072 pw.println("Outstanding deliveries:");
2073 for (int i = 0; i < mInFlight.size(); i++) {
2074 pw.print(" #"); pw.print(i); pw.print(": ");
2075 pw.println(mInFlight.get(i));
2076 }
2077 pw.println();
2078 }
2079
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002080 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002081 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002082 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002083 pw.print(" UID ");
2084 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2085 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002086 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002087 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2088 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2089
2090 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2091 pw.print(" Next allowed:");
2092 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2093 pw.print(" (");
2094 TimeUtils.formatDuration(minInterval, 0, pw);
2095 pw.print(")");
2096
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002097 pw.println();
2098 }
2099 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002100
2101 pw.print(" mUseAllowWhileIdleShortTime: [");
2102 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2103 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2104 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2105 pw.print(" ");
2106 }
2107 }
2108 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002109 pw.println();
2110
Dianne Hackborn81038902012-11-26 17:04:09 -08002111 if (mLog.dump(pw, " Recent problems", " ")) {
2112 pw.println();
2113 }
2114
2115 final FilterStats[] topFilters = new FilterStats[10];
2116 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2117 @Override
2118 public int compare(FilterStats lhs, FilterStats rhs) {
2119 if (lhs.aggregateTime < rhs.aggregateTime) {
2120 return 1;
2121 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2122 return -1;
2123 }
2124 return 0;
2125 }
2126 };
2127 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002128 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002129 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2130 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2131 for (int ip=0; ip<uidStats.size(); ip++) {
2132 BroadcastStats bs = uidStats.valueAt(ip);
2133 for (int is=0; is<bs.filterStats.size(); is++) {
2134 FilterStats fs = bs.filterStats.valueAt(is);
2135 int pos = len > 0
2136 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2137 if (pos < 0) {
2138 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002139 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002140 if (pos < topFilters.length) {
2141 int copylen = topFilters.length - pos - 1;
2142 if (copylen > 0) {
2143 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2144 }
2145 topFilters[pos] = fs;
2146 if (len < topFilters.length) {
2147 len++;
2148 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002149 }
2150 }
2151 }
2152 }
2153 if (len > 0) {
2154 pw.println(" Top Alarms:");
2155 for (int i=0; i<len; i++) {
2156 FilterStats fs = topFilters[i];
2157 pw.print(" ");
2158 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2159 TimeUtils.formatDuration(fs.aggregateTime, pw);
2160 pw.print(" running, "); pw.print(fs.numWakeup);
2161 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002162 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2163 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002164 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002165 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002166 pw.println();
2167 }
2168 }
2169
2170 pw.println(" ");
2171 pw.println(" Alarm Stats:");
2172 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002173 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2174 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2175 for (int ip=0; ip<uidStats.size(); ip++) {
2176 BroadcastStats bs = uidStats.valueAt(ip);
2177 pw.print(" ");
2178 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2179 UserHandle.formatUid(pw, bs.mUid);
2180 pw.print(":");
2181 pw.print(bs.mPackageName);
2182 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2183 pw.print(" running, "); pw.print(bs.numWakeup);
2184 pw.println(" wakeups:");
2185 tmpFilters.clear();
2186 for (int is=0; is<bs.filterStats.size(); is++) {
2187 tmpFilters.add(bs.filterStats.valueAt(is));
2188 }
2189 Collections.sort(tmpFilters, comparator);
2190 for (int i=0; i<tmpFilters.size(); i++) {
2191 FilterStats fs = tmpFilters.get(i);
2192 pw.print(" ");
2193 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2194 TimeUtils.formatDuration(fs.aggregateTime, pw);
2195 pw.print(" "); pw.print(fs.numWakeup);
2196 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002197 pw.print(" alarms, last ");
2198 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2199 pw.println(":");
2200 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002201 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002202 pw.println();
2203 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002204 }
2205 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002206 pw.println();
2207 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002208
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002209 if (RECORD_DEVICE_IDLE_ALARMS) {
2210 pw.println();
2211 pw.println(" Allow while idle dispatches:");
2212 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2213 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2214 pw.print(" ");
2215 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2216 pw.print(": ");
2217 UserHandle.formatUid(pw, ent.uid);
2218 pw.print(":");
2219 pw.println(ent.pkg);
2220 if (ent.op != null) {
2221 pw.print(" ");
2222 pw.print(ent.op);
2223 pw.print(" / ");
2224 pw.print(ent.tag);
2225 if (ent.argRealtime != 0) {
2226 pw.print(" (");
2227 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2228 pw.print(")");
2229 }
2230 pw.println();
2231 }
2232 }
2233 }
2234
Christopher Tate18a75f12013-07-01 18:18:59 -07002235 if (WAKEUP_STATS) {
2236 pw.println();
2237 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002238 long last = -1;
2239 for (WakeupEvent event : mRecentWakeups) {
2240 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2241 pw.print('|');
2242 if (last < 0) {
2243 pw.print('0');
2244 } else {
2245 pw.print(event.when - last);
2246 }
2247 last = event.when;
2248 pw.print('|'); pw.print(event.uid);
2249 pw.print('|'); pw.print(event.action);
2250 pw.println();
2251 }
2252 pw.println();
2253 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002254 }
2255 }
2256
Kweku Adams61e03292017-10-19 14:27:12 -07002257 void dumpProto(FileDescriptor fd) {
2258 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2259
2260 synchronized (mLock) {
2261 final long nowRTC = System.currentTimeMillis();
2262 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002263 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2264 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2265 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002266 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002267 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002268 mLastTimeChangeRealtime);
2269
Yi Jin2b30f322018-02-20 15:41:47 -08002270 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002271
Makoto Onukie4918212018-02-06 11:30:15 -08002272 if (mAppStateTracker != null) {
2273 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002274 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002275 }
Kweku Adams61e03292017-10-19 14:27:12 -07002276
Yi Jin2b30f322018-02-20 15:41:47 -08002277 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002278 if (!mInteractive) {
2279 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002280 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002281 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002282 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002283 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002284 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002285 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002286 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002287 nowElapsed - mNextNonWakeupDeliveryTime);
2288 }
2289
Yi Jin2b30f322018-02-20 15:41:47 -08002290 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002291 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002292 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002293 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002294 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002295 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002296 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002297 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002298 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002299
2300 final TreeSet<Integer> users = new TreeSet<>();
2301 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2302 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2303 users.add(mNextAlarmClockForUser.keyAt(i));
2304 }
2305 final int pendingSendNextAlarmClockChangedForUserSize =
2306 mPendingSendNextAlarmClockChangedForUser.size();
2307 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2308 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2309 }
2310 for (int user : users) {
2311 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2312 final long time = next != null ? next.getTriggerTime() : 0;
2313 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002314 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002315 proto.write(AlarmClockMetadataProto.USER, user);
2316 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2317 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2318 proto.end(aToken);
2319 }
2320 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002321 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002322 nowElapsed, nowRTC);
2323 }
2324 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2325 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2326 if (blockedAlarms != null) {
2327 for (Alarm a : blockedAlarms) {
2328 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002329 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002330 nowElapsed, nowRTC);
2331 }
2332 }
2333 }
2334 if (mPendingIdleUntil != null) {
2335 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002336 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002337 }
2338 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002339 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002340 nowElapsed, nowRTC);
2341 }
2342 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002343 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002344 nowElapsed, nowRTC);
2345 }
2346
2347 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002348 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002349 nowElapsed, nowRTC);
2350 }
2351
Yi Jin2b30f322018-02-20 15:41:47 -08002352 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2353 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2354 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2355 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002356 mNonInteractiveTime);
2357
Yi Jin2b30f322018-02-20 15:41:47 -08002358 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2359 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2360 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2361 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2362 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002363
2364 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002365 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002366 }
2367
Kweku Adams61e03292017-10-19 14:27:12 -07002368 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2369 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002370 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002371 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2372 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2373
Yi Jin2b30f322018-02-20 15:41:47 -08002374 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2375 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2376 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002377 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002378 proto.end(token);
2379 }
2380
Makoto Onukiadb50d82018-01-29 16:20:30 -08002381 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2382 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002383 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002384 mUseAllowWhileIdleShortTime.keyAt(i));
2385 }
2386 }
2387
Yi Jin2b30f322018-02-20 15:41:47 -08002388 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002389
2390 final FilterStats[] topFilters = new FilterStats[10];
2391 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2392 @Override
2393 public int compare(FilterStats lhs, FilterStats rhs) {
2394 if (lhs.aggregateTime < rhs.aggregateTime) {
2395 return 1;
2396 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2397 return -1;
2398 }
2399 return 0;
2400 }
2401 };
2402 int len = 0;
2403 // Get the top 10 FilterStats, ordered by aggregateTime.
2404 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2405 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2406 for (int ip = 0; ip < uidStats.size(); ++ip) {
2407 BroadcastStats bs = uidStats.valueAt(ip);
2408 for (int is = 0; is < bs.filterStats.size(); ++is) {
2409 FilterStats fs = bs.filterStats.valueAt(is);
2410 int pos = len > 0
2411 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2412 if (pos < 0) {
2413 pos = -pos - 1;
2414 }
2415 if (pos < topFilters.length) {
2416 int copylen = topFilters.length - pos - 1;
2417 if (copylen > 0) {
2418 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2419 }
2420 topFilters[pos] = fs;
2421 if (len < topFilters.length) {
2422 len++;
2423 }
2424 }
2425 }
2426 }
2427 }
2428 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002429 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002430 FilterStats fs = topFilters[i];
2431
Yi Jin2b30f322018-02-20 15:41:47 -08002432 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2433 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002434 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002435 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002436
2437 proto.end(token);
2438 }
2439
2440 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2441 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2442 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2443 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002444 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002445
2446 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002447 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002448
2449 // uidStats is an ArrayMap, which we can't sort.
2450 tmpFilters.clear();
2451 for (int is = 0; is < bs.filterStats.size(); ++is) {
2452 tmpFilters.add(bs.filterStats.valueAt(is));
2453 }
2454 Collections.sort(tmpFilters, comparator);
2455 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002456 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002457 }
2458
2459 proto.end(token);
2460 }
2461 }
2462
2463 if (RECORD_DEVICE_IDLE_ALARMS) {
2464 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2465 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2466 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002467 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002468
2469 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2470 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2471 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2472 proto.write(IdleDispatchEntryProto.OP, ent.op);
2473 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2474 ent.elapsedRealtime);
2475 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2476
2477 proto.end(token);
2478 }
2479 }
2480
2481 if (WAKEUP_STATS) {
2482 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002483 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002484 proto.write(WakeupEventProto.UID, event.uid);
2485 proto.write(WakeupEventProto.ACTION, event.action);
2486 proto.write(WakeupEventProto.WHEN, event.when);
2487 proto.end(token);
2488 }
2489 }
2490 }
2491
2492 proto.flush();
2493 }
2494
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002495 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002496 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2497 PrintWriter pw = new PrintWriter(bs);
2498 final long nowRTC = System.currentTimeMillis();
2499 final long nowELAPSED = SystemClock.elapsedRealtime();
2500 final int NZ = mAlarmBatches.size();
2501 for (int iz = 0; iz < NZ; iz++) {
2502 Batch bz = mAlarmBatches.get(iz);
2503 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002504 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002505 pw.flush();
2506 Slog.v(TAG, bs.toString());
2507 bs.reset();
2508 }
2509 }
2510
2511 private boolean validateConsistencyLocked() {
2512 if (DEBUG_VALIDATE) {
2513 long lastTime = Long.MIN_VALUE;
2514 final int N = mAlarmBatches.size();
2515 for (int i = 0; i < N; i++) {
2516 Batch b = mAlarmBatches.get(i);
2517 if (b.start >= lastTime) {
2518 // duplicate start times are okay because of standalone batches
2519 lastTime = b.start;
2520 } else {
2521 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002522 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2523 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002524 return false;
2525 }
2526 }
2527 }
2528 return true;
2529 }
2530
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002531 private Batch findFirstWakeupBatchLocked() {
2532 final int N = mAlarmBatches.size();
2533 for (int i = 0; i < N; i++) {
2534 Batch b = mAlarmBatches.get(i);
2535 if (b.hasWakeups()) {
2536 return b;
2537 }
2538 }
2539 return null;
2540 }
2541
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002542 long getNextWakeFromIdleTimeImpl() {
2543 synchronized (mLock) {
2544 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2545 }
2546 }
2547
2548 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002549 synchronized (mLock) {
2550 return mNextAlarmClockForUser.get(userId);
2551 }
2552 }
2553
2554 /**
2555 * Recomputes the next alarm clock for all users.
2556 */
2557 private void updateNextAlarmClockLocked() {
2558 if (!mNextAlarmClockMayChange) {
2559 return;
2560 }
2561 mNextAlarmClockMayChange = false;
2562
Jose Lima235510e2014-08-13 12:50:01 -07002563 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002564 nextForUser.clear();
2565
2566 final int N = mAlarmBatches.size();
2567 for (int i = 0; i < N; i++) {
2568 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2569 final int M = alarms.size();
2570
2571 for (int j = 0; j < M; j++) {
2572 Alarm a = alarms.get(j);
2573 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002574 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002575 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002576
2577 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002578 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002579 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002580 " for user " + userId);
2581 }
2582
2583 // Alarms and batches are sorted by time, no need to compare times here.
2584 if (nextForUser.get(userId) == null) {
2585 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002586 } else if (a.alarmClock.equals(current)
2587 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2588 // same/earlier time and it's the one we cited before, so stick with it
2589 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002590 }
2591 }
2592 }
2593 }
2594
2595 // Update mNextAlarmForUser with new values.
2596 final int NN = nextForUser.size();
2597 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002598 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002599 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002600 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002601 if (!newAlarm.equals(currentAlarm)) {
2602 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2603 }
2604 }
2605
2606 // Remove users without any alarm clocks scheduled.
2607 final int NNN = mNextAlarmClockForUser.size();
2608 for (int i = NNN - 1; i >= 0; i--) {
2609 int userId = mNextAlarmClockForUser.keyAt(i);
2610 if (nextForUser.get(userId) == null) {
2611 updateNextAlarmInfoForUserLocked(userId, null);
2612 }
2613 }
2614 }
2615
Jose Lima235510e2014-08-13 12:50:01 -07002616 private void updateNextAlarmInfoForUserLocked(int userId,
2617 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002618 if (alarmClock != null) {
2619 if (DEBUG_ALARM_CLOCK) {
2620 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002621 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002622 }
2623 mNextAlarmClockForUser.put(userId, alarmClock);
2624 } else {
2625 if (DEBUG_ALARM_CLOCK) {
2626 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2627 }
2628 mNextAlarmClockForUser.remove(userId);
2629 }
2630
2631 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2632 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2633 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2634 }
2635
2636 /**
2637 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2638 * for which alarm clocks have changed since the last call to this.
2639 *
2640 * Do not call with a lock held. Only call from mHandler's thread.
2641 *
2642 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2643 */
2644 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002645 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002646 pendingUsers.clear();
2647
2648 synchronized (mLock) {
2649 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2650 for (int i = 0; i < N; i++) {
2651 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2652 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2653 }
2654 mPendingSendNextAlarmClockChangedForUser.clear();
2655 }
2656
2657 final int N = pendingUsers.size();
2658 for (int i = 0; i < N; i++) {
2659 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002660 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002661 Settings.System.putStringForUser(getContext().getContentResolver(),
2662 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002663 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002664 userId);
2665
2666 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2667 new UserHandle(userId));
2668 }
2669 }
2670
2671 /**
2672 * Formats an alarm like platform/packages/apps/DeskClock used to.
2673 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002674 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2675 int userId) {
2676 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002677 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2678 return (info == null) ? "" :
2679 DateFormat.format(pattern, info.getTriggerTime()).toString();
2680 }
2681
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002682 /**
2683 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2684 * by more than half a minute, log a wtf.
2685 */
2686 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2687 final StringBuilder errorMsg = new StringBuilder();
2688 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002689 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002690 stuck = true;
2691 errorMsg.append("[mNextNonWakeup=");
2692 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002693 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002694 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002695 errorMsg.append(", mLastWakeup=");
2696 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2697 errorMsg.append(", timerfd_gettime=" + getNextAlarm(mNativeData, ELAPSED_REALTIME));
2698 errorMsg.append("];");
2699 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002700 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002701 stuck = true;
2702 errorMsg.append("[mNextWakeup=");
2703 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002704 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002705 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002706 errorMsg.append(", mLastWakeup=");
2707 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2708 errorMsg.append(", timerfd_gettime="
2709 + getNextAlarm(mNativeData, ELAPSED_REALTIME_WAKEUP));
2710 errorMsg.append("];");
2711 }
2712 if (stuck) {
2713 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2714 }
2715 }
2716
Adam Lesinski182f73f2013-12-05 16:48:06 -08002717 void rescheduleKernelAlarmsLocked() {
2718 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2719 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002720 final long nowElapsed = SystemClock.elapsedRealtime();
2721 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002722 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002723 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002724 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002725 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002726 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002727 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002728 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002729 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002730 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002731 if (firstBatch != firstWakeup) {
2732 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002733 }
2734 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002735 if (mPendingNonWakeupAlarms.size() > 0) {
2736 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2737 nextNonWakeup = mNextNonWakeupDeliveryTime;
2738 }
2739 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002740 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002741 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002742 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002743 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2744 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002745 }
2746
Christopher Tate14a7bb02015-10-01 10:24:31 -07002747 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002748 if (operation == null && directReceiver == null) {
2749 if (localLOGV) {
2750 Slog.w(TAG, "requested remove() of null operation",
2751 new RuntimeException("here"));
2752 }
2753 return;
2754 }
2755
Adam Lesinski182f73f2013-12-05 16:48:06 -08002756 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002757 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002758 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2759 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002760 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002761 if (b.size() == 0) {
2762 mAlarmBatches.remove(i);
2763 }
2764 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002765 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002766 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002767 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2768 mPendingWhileIdleAlarms.remove(i);
2769 }
2770 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002771 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2772 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2773 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2774 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2775 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2776 alarmsForUid.remove(j);
2777 }
2778 }
2779 if (alarmsForUid.size() == 0) {
2780 mPendingBackgroundAlarms.removeAt(i);
2781 }
2782 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002783 if (didRemove) {
2784 if (DEBUG_BATCH) {
2785 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2786 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002787 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002788 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002789 mPendingIdleUntil = null;
2790 restorePending = true;
2791 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002792 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002793 mNextWakeFromIdle = null;
2794 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002795 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002796 if (restorePending) {
2797 restorePendingWhileIdleAlarmsLocked();
2798 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002799 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002800 }
2801 }
2802
Christopher Tate1d99c392017-12-07 16:54:04 -08002803 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002804 if (uid == Process.SYSTEM_UID) {
2805 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2806 return;
2807 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002808 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002809 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002810 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2811 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002812 didRemove |= b.remove(whichAlarms);
2813 if (b.size() == 0) {
2814 mAlarmBatches.remove(i);
2815 }
2816 }
2817 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2818 final Alarm a = mPendingWhileIdleAlarms.get(i);
2819 if (a.uid == uid) {
2820 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2821 mPendingWhileIdleAlarms.remove(i);
2822 }
2823 }
2824 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2825 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2826 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2827 if (alarmsForUid.get(j).uid == uid) {
2828 alarmsForUid.remove(j);
2829 }
2830 }
2831 if (alarmsForUid.size() == 0) {
2832 mPendingBackgroundAlarms.removeAt(i);
2833 }
2834 }
2835 if (didRemove) {
2836 if (DEBUG_BATCH) {
2837 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2838 }
2839 rebatchAllAlarmsLocked(true);
2840 rescheduleKernelAlarmsLocked();
2841 updateNextAlarmClockLocked();
2842 }
2843 }
2844
2845 void removeLocked(final String packageName) {
2846 if (packageName == null) {
2847 if (localLOGV) {
2848 Slog.w(TAG, "requested remove() of null packageName",
2849 new RuntimeException("here"));
2850 }
2851 return;
2852 }
2853
2854 boolean didRemove = false;
2855 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002856 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002857 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2858 Batch b = mAlarmBatches.get(i);
2859 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002860 if (b.size() == 0) {
2861 mAlarmBatches.remove(i);
2862 }
2863 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002864 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2865 if (oldHasTick != newHasTick) {
2866 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2867 }
2868
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002869 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002870 final Alarm a = mPendingWhileIdleAlarms.get(i);
2871 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002872 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2873 mPendingWhileIdleAlarms.remove(i);
2874 }
2875 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002876 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2877 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2878 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2879 if (alarmsForUid.get(j).matches(packageName)) {
2880 alarmsForUid.remove(j);
2881 }
2882 }
2883 if (alarmsForUid.size() == 0) {
2884 mPendingBackgroundAlarms.removeAt(i);
2885 }
2886 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002887 if (didRemove) {
2888 if (DEBUG_BATCH) {
2889 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2890 }
2891 rebatchAllAlarmsLocked(true);
2892 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002893 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002894 }
2895 }
2896
Christopher Tate1d99c392017-12-07 16:54:04 -08002897 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002898 if (uid == Process.SYSTEM_UID) {
2899 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2900 return;
2901 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002902 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002903 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2904 try {
2905 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2906 uid, a.packageName)) {
2907 return true;
2908 }
2909 } catch (RemoteException e) { /* fall through */}
2910 return false;
2911 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002912 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2913 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002914 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002915 if (b.size() == 0) {
2916 mAlarmBatches.remove(i);
2917 }
2918 }
2919 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2920 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002921 if (a.uid == uid) {
2922 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2923 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002924 }
2925 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002926 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2927 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2928 mPendingBackgroundAlarms.removeAt(i);
2929 }
2930 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002931 if (didRemove) {
2932 if (DEBUG_BATCH) {
2933 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2934 }
2935 rebatchAllAlarmsLocked(true);
2936 rescheduleKernelAlarmsLocked();
2937 updateNextAlarmClockLocked();
2938 }
2939 }
2940
Adam Lesinski182f73f2013-12-05 16:48:06 -08002941 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002942 if (userHandle == UserHandle.USER_SYSTEM) {
2943 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2944 return;
2945 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002946 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002947 final Predicate<Alarm> whichAlarms =
2948 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002949 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2950 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002951 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002952 if (b.size() == 0) {
2953 mAlarmBatches.remove(i);
2954 }
2955 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002956 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002957 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002958 == userHandle) {
2959 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2960 mPendingWhileIdleAlarms.remove(i);
2961 }
2962 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002963 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2964 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2965 mPendingBackgroundAlarms.removeAt(i);
2966 }
2967 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002968 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2969 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2970 mLastAllowWhileIdleDispatch.removeAt(i);
2971 }
2972 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002973
2974 if (didRemove) {
2975 if (DEBUG_BATCH) {
2976 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2977 }
2978 rebatchAllAlarmsLocked(true);
2979 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002980 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002981 }
2982 }
2983
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002984 void interactiveStateChangedLocked(boolean interactive) {
2985 if (mInteractive != interactive) {
2986 mInteractive = interactive;
2987 final long nowELAPSED = SystemClock.elapsedRealtime();
2988 if (interactive) {
2989 if (mPendingNonWakeupAlarms.size() > 0) {
2990 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2991 mTotalDelayTime += thisDelayTime;
2992 if (mMaxDelayTime < thisDelayTime) {
2993 mMaxDelayTime = thisDelayTime;
2994 }
2995 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2996 mPendingNonWakeupAlarms.clear();
2997 }
2998 if (mNonInteractiveStartTime > 0) {
2999 long dur = nowELAPSED - mNonInteractiveStartTime;
3000 if (dur > mNonInteractiveTime) {
3001 mNonInteractiveTime = dur;
3002 }
3003 }
3004 } else {
3005 mNonInteractiveStartTime = nowELAPSED;
3006 }
3007 }
3008 }
3009
Adam Lesinski182f73f2013-12-05 16:48:06 -08003010 boolean lookForPackageLocked(String packageName) {
3011 for (int i = 0; i < mAlarmBatches.size(); i++) {
3012 Batch b = mAlarmBatches.get(i);
3013 if (b.hasPackage(packageName)) {
3014 return true;
3015 }
3016 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003017 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003018 final Alarm a = mPendingWhileIdleAlarms.get(i);
3019 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003020 return true;
3021 }
3022 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003023 return false;
3024 }
3025
3026 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08003027 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003028 // The kernel never triggers alarms with negative wakeup times
3029 // so we ensure they are positive.
3030 long alarmSeconds, alarmNanoseconds;
3031 if (when < 0) {
3032 alarmSeconds = 0;
3033 alarmNanoseconds = 0;
3034 } else {
3035 alarmSeconds = when / 1000;
3036 alarmNanoseconds = (when % 1000) * 1000 * 1000;
3037 }
Kweku Adams61e03292017-10-19 14:27:12 -07003038
Christopher Tate8b98ade2018-02-09 11:13:19 -08003039 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
3040 if (result != 0) {
3041 final long nowElapsed = SystemClock.elapsedRealtime();
3042 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3043 + " type=" + type + " when=" + when
3044 + " @ (" + alarmSeconds + "," + alarmNanoseconds
3045 + "), ret = " + result + " = " + Os.strerror(result));
3046 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003047 } else {
3048 Message msg = Message.obtain();
3049 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003050
Adam Lesinski182f73f2013-12-05 16:48:06 -08003051 mHandler.removeMessages(ALARM_EVENT);
3052 mHandler.sendMessageAtTime(msg, when);
3053 }
3054 }
3055
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003056 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003057 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003058 for (int i=list.size()-1; i>=0; i--) {
3059 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003060 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3061 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003062 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063 }
3064 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003065
3066 private static final String labelForType(int type) {
3067 switch (type) {
3068 case RTC: return "RTC";
3069 case RTC_WAKEUP : return "RTC_WAKEUP";
3070 case ELAPSED_REALTIME : return "ELAPSED";
3071 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003072 }
3073 return "--unknown--";
3074 }
3075
3076 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003077 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003078 for (int i=list.size()-1; i>=0; i--) {
3079 Alarm a = list.get(i);
3080 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003081 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3082 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003083 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003084 }
3085 }
3086
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003087 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003088 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003089 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003090 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003091 return false;
3092 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003093 if (alarm.operation != null) {
3094 if (alarm.operation.isActivity()) {
3095 // Don't defer starting actual UI
3096 return false;
3097 }
3098 if (alarm.operation.isForegroundService()) {
3099 // FG service alarms are nearly as important; consult AST policy
3100 exemptOnBatterySaver = true;
3101 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003102 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003103 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003104 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003105 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003106 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3107 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003108 }
3109
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003110 private native long init();
3111 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003112 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003113 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003114 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003115 private native int setKernelTimezone(long nativeData, int minuteswest);
Suprabh Shukla2324e982018-06-05 21:06:22 -07003116 private native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117
Makoto Onukiadb50d82018-01-29 16:20:30 -08003118 private long getWhileIdleMinIntervalLocked(int uid) {
3119 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003120 final boolean ebs = (mAppStateTracker != null)
3121 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003122 if (!dozing && !ebs) {
3123 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3124 }
3125 if (dozing) {
3126 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3127 }
3128 if (mUseAllowWhileIdleShortTime.get(uid)) {
3129 // if the last allow-while-idle went off while uid was fg, or the uid
3130 // recently came into fg, don't block the alarm for long.
3131 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3132 }
3133 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3134 }
3135
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003136 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003137 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003138 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003139 // batches are temporally sorted, so we need only pull from the
3140 // start of the list until we either empty it or hit a batch
3141 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003142 while (mAlarmBatches.size() > 0) {
3143 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003144 if (batch.start > nowELAPSED) {
3145 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 break;
3147 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003148
Christopher Tatee0a22b32013-07-11 14:43:13 -07003149 // We will (re)schedule some alarms now; don't let that interfere
3150 // with delivery of this current batch
3151 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003152
Christopher Tatee0a22b32013-07-11 14:43:13 -07003153 final int N = batch.size();
3154 for (int i = 0; i < N; i++) {
3155 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003156
3157 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3158 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003159 // schedule such alarms. The first such alarm from an app is always delivered.
3160 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003161 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003162 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003163 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3164 // alarm went off for this app. Reschedule the alarm to be in the
3165 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003166 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003167 if (alarm.maxWhenElapsed < minTime) {
3168 alarm.maxWhenElapsed = minTime;
3169 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003170 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003171 if (RECORD_DEVICE_IDLE_ALARMS) {
3172 IdleDispatchEntry ent = new IdleDispatchEntry();
3173 ent.uid = alarm.uid;
3174 ent.pkg = alarm.operation.getCreatorPackage();
3175 ent.tag = alarm.operation.getTag("");
3176 ent.op = "RESCHEDULE";
3177 ent.elapsedRealtime = nowELAPSED;
3178 ent.argRealtime = lastTime;
3179 mAllowWhileIdleDispatches.add(ent);
3180 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003181 setImplLocked(alarm, true, false);
3182 continue;
3183 }
3184 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003185 if (isBackgroundRestricted(alarm)) {
3186 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3187 if (DEBUG_BG_LIMIT) {
3188 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3189 }
3190 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3191 if (alarmsForUid == null) {
3192 alarmsForUid = new ArrayList<>();
3193 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3194 }
3195 alarmsForUid.add(alarm);
3196 continue;
3197 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003198
Christopher Tatee0a22b32013-07-11 14:43:13 -07003199 alarm.count = 1;
3200 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003201 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3202 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003203 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003204 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003205 if (mPendingIdleUntil == alarm) {
3206 mPendingIdleUntil = null;
3207 rebatchAllAlarmsLocked(false);
3208 restorePendingWhileIdleAlarmsLocked();
3209 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003210 if (mNextWakeFromIdle == alarm) {
3211 mNextWakeFromIdle = null;
3212 rebatchAllAlarmsLocked(false);
3213 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003214
3215 // Recurring alarms may have passed several alarm intervals while the
3216 // phone was asleep or off, so pass a trigger count when sending them.
3217 if (alarm.repeatInterval > 0) {
3218 // this adjustment will be zero if we're late by
3219 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003220 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003221
3222 // Also schedule its next recurrence
3223 final long delta = alarm.count * alarm.repeatInterval;
3224 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003225 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003226 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003227 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3228 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003229 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230
Christopher Tate864d42e2014-12-02 11:48:53 -08003231 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003232 hasWakeup = true;
3233 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003234
3235 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3236 if (alarm.alarmClock != null) {
3237 mNextAlarmClockMayChange = true;
3238 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003239 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003241
Christopher Tate1590f1e2014-10-02 17:27:57 -07003242 // This is a new alarm delivery set; bump the sequence number to indicate that
3243 // all apps' alarm delivery classes should be recalculated.
3244 mCurrentSeq++;
3245 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003246 Collections.sort(triggerList, mAlarmDispatchComparator);
3247
3248 if (localLOGV) {
3249 for (int i=0; i<triggerList.size(); i++) {
3250 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3251 }
3252 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003253
3254 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003256
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003257 /**
3258 * This Comparator sorts Alarms into increasing time order.
3259 */
3260 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3261 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003262 long when1 = a1.whenElapsed;
3263 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003264 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 return 1;
3266 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003267 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 return -1;
3269 }
3270 return 0;
3271 }
3272 }
Kweku Adams61e03292017-10-19 14:27:12 -07003273
Makoto Onuki2206af32017-11-21 16:25:35 -08003274 @VisibleForTesting
3275 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003276 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003277 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003278 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003279 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003280 public final IAlarmListener listener;
3281 public final String listenerTag;
3282 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003283 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003284 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003285 public final AlarmManager.AlarmClockInfo alarmClock;
3286 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003287 public final int creatorUid;
3288 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003289 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003290 public int count;
3291 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003292 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003293 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003294 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003295 // Expected alarm expiry time before app standby deferring is applied.
3296 public long expectedWhenElapsed;
3297 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003298 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003299 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003300
Christopher Tate3e04b472013-10-21 17:51:31 -07003301 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003302 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3303 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3304 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003305 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003306 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003307 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3308 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003309 when = _when;
3310 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003311 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003312 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003313 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003314 repeatInterval = _interval;
3315 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003316 listener = _rec;
3317 listenerTag = _listenerTag;
3318 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003319 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003320 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003321 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003322 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003323 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003324 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003325 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003327
Christopher Tate14a7bb02015-10-01 10:24:31 -07003328 public static String makeTag(PendingIntent pi, String tag, int type) {
3329 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3330 ? "*walarm*:" : "*alarm*:";
3331 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3332 }
3333
3334 public WakeupEvent makeWakeupEvent(long nowRTC) {
3335 return new WakeupEvent(nowRTC, creatorUid,
3336 (operation != null)
3337 ? operation.getIntent().getAction()
3338 : ("<listener>:" + listenerTag));
3339 }
3340
3341 // Returns true if either matches
3342 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3343 return (operation != null)
3344 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003345 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003346 }
3347
3348 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003349 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003350 }
3351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003353 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003354 StringBuilder sb = new StringBuilder(128);
3355 sb.append("Alarm{");
3356 sb.append(Integer.toHexString(System.identityHashCode(this)));
3357 sb.append(" type ");
3358 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003359 sb.append(" when ");
3360 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003361 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003362 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003363 sb.append('}');
3364 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 }
3366
Kweku Adams61e03292017-10-19 14:27:12 -07003367 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003368 SimpleDateFormat sdf) {
3369 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003370 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003371 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003372 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3373 expectedWhenElapsed, nowELAPSED, pw);
3374 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3375 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003376 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3377 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003378 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3379 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003380 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003381 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003382 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003383 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003384 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003385 }
3386 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003387 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003388 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003389 pw.print(" count="); pw.print(count);
3390 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003391 if (alarmClock != null) {
3392 pw.print(prefix); pw.println("Alarm clock:");
3393 pw.print(prefix); pw.print(" triggerTime=");
3394 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3395 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3396 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003397 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003398 if (listener != null) {
3399 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 }
Kweku Adams61e03292017-10-19 14:27:12 -07003402
3403 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3404 long nowRTC) {
3405 final long token = proto.start(fieldId);
3406
3407 proto.write(AlarmProto.TAG, statsTag);
3408 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003409 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003410 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3411 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3412 proto.write(AlarmProto.COUNT, count);
3413 proto.write(AlarmProto.FLAGS, flags);
3414 if (alarmClock != null) {
3415 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3416 }
3417 if (operation != null) {
3418 operation.writeToProto(proto, AlarmProto.OPERATION);
3419 }
3420 if (listener != null) {
3421 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3422 }
3423
3424 proto.end(token);
3425 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003427
Christopher Tatee0a22b32013-07-11 14:43:13 -07003428 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3429 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003430 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3431 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003432 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003433 break;
3434 }
3435
Christopher Tatee0a22b32013-07-11 14:43:13 -07003436 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003437 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3438 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003439 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003440 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003441 }
3442 }
3443
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003444 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3445 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3446 if (timeSinceOn < 5*60*1000) {
3447 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3448 return 2*60*1000;
3449 } else if (timeSinceOn < 30*60*1000) {
3450 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3451 return 15*60*1000;
3452 } else {
3453 // Otherwise, we will delay by at most an hour.
3454 return 60*60*1000;
3455 }
3456 }
3457
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003458 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003459 if (duration < 15*60*1000) {
3460 // If the duration until the time is less than 15 minutes, the maximum fuzz
3461 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003462 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003463 } else if (duration < 90*60*1000) {
3464 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3465 return 15*60*1000;
3466 } else {
3467 // Otherwise, we will fuzz by at most half an hour.
3468 return 30*60*1000;
3469 }
3470 }
3471
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003472 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3473 if (mInteractive) {
3474 return false;
3475 }
3476 if (mLastAlarmDeliveryTime <= 0) {
3477 return false;
3478 }
minho.choo649acab2014-12-12 16:13:55 +09003479 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003480 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3481 // and the next delivery time is in the past, then just deliver them all. This
3482 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3483 return false;
3484 }
3485 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3486 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3487 }
3488
3489 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3490 mLastAlarmDeliveryTime = nowELAPSED;
3491 for (int i=0; i<triggerList.size(); i++) {
3492 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003493 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003494 if (alarm.wakeup) {
3495 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3496 } else {
3497 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3498 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003499 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003500 if (localLOGV) {
3501 Slog.v(TAG, "sending alarm " + alarm);
3502 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003503 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003504 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3505 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003506 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003507 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003508 } catch (RuntimeException e) {
3509 Slog.w(TAG, "Failure sending alarm.", e);
3510 }
Tim Murray175c0f92017-11-28 15:01:04 -08003511 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003512 }
3513 }
3514
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003515 private boolean isExemptFromAppStandby(Alarm a) {
3516 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3517 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3518 }
3519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 private class AlarmThread extends Thread
3521 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003522 private int mFalseWakeups;
3523 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 public AlarmThread()
3525 {
3526 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003527 mFalseWakeups = 0;
3528 mWtfThreshold = 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 }
Kweku Adams61e03292017-10-19 14:27:12 -07003530
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 public void run()
3532 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003533 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 while (true)
3536 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003537 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003538
Dianne Hackbornc3527222015-05-13 14:03:20 -07003539 final long nowRTC = System.currentTimeMillis();
3540 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003541 synchronized (mLock) {
3542 mLastWakeup = nowELAPSED;
3543 }
3544
3545 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003546
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003548 // The kernel can give us spurious time change notifications due to
3549 // small adjustments it makes internally; we want to filter those out.
3550 final long lastTimeChangeClockTime;
3551 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003552 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003553 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3554 expectedClockTime = lastTimeChangeClockTime
3555 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003556 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003557 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3558 || nowRTC > (expectedClockTime+1000)) {
3559 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003560 // let's do it!
3561 if (DEBUG_BATCH) {
3562 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3563 }
Bookatz7948c872018-09-04 12:58:33 -07003564 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3565 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003566 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003567 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003568 rebatchAllAlarms();
3569 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003570 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003571 synchronized (mLock) {
3572 mNumTimeChanged++;
3573 mLastTimeChangeClockTime = nowRTC;
3574 mLastTimeChangeRealtime = nowELAPSED;
3575 }
3576 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3577 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003578 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003579 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3580 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003581 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3582
3583 // The world has changed on us, so we need to re-evaluate alarms
3584 // regardless of whether the kernel has told us one went off.
3585 result |= IS_WAKEUP_MASK;
3586 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588
Dianne Hackbornc3527222015-05-13 14:03:20 -07003589 if (result != TIME_CHANGED_MASK) {
3590 // If this was anything besides just a time change, then figure what if
3591 // anything to do about alarms.
3592 synchronized (mLock) {
3593 if (localLOGV) Slog.v(
3594 TAG, "Checking for alarms... rtc=" + nowRTC
3595 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003596
Dianne Hackbornc3527222015-05-13 14:03:20 -07003597 if (WAKEUP_STATS) {
3598 if ((result & IS_WAKEUP_MASK) != 0) {
3599 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3600 int n = 0;
3601 for (WakeupEvent event : mRecentWakeups) {
3602 if (event.when > newEarliest) break;
3603 n++; // number of now-stale entries at the list head
3604 }
3605 for (int i = 0; i < n; i++) {
3606 mRecentWakeups.remove();
3607 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003608
Dianne Hackbornc3527222015-05-13 14:03:20 -07003609 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003610 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003611 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003612
Christopher Tate8b98ade2018-02-09 11:13:19 -08003613 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003614 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3615 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3616 // if there are no wakeup alarms and the screen is off, we can
3617 // delay what we have so far until the future.
3618 if (mPendingNonWakeupAlarms.size() == 0) {
3619 mStartCurrentDelayTime = nowELAPSED;
3620 mNextNonWakeupDeliveryTime = nowELAPSED
3621 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3622 }
3623 mPendingNonWakeupAlarms.addAll(triggerList);
3624 mNumDelayedAlarms += triggerList.size();
3625 rescheduleKernelAlarmsLocked();
3626 updateNextAlarmClockLocked();
3627 } else {
3628 // now deliver the alarm intents; if there are pending non-wakeup
3629 // alarms, we need to merge them in to the list. note we don't
3630 // just deliver them first because we generally want non-wakeup
3631 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003632 if (mPendingNonWakeupAlarms.size() > 0) {
3633 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3634 triggerList.addAll(mPendingNonWakeupAlarms);
3635 Collections.sort(triggerList, mAlarmDispatchComparator);
3636 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3637 mTotalDelayTime += thisDelayTime;
3638 if (mMaxDelayTime < thisDelayTime) {
3639 mMaxDelayTime = thisDelayTime;
3640 }
3641 mPendingNonWakeupAlarms.clear();
3642 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003643 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3644 if (++mFalseWakeups >= mWtfThreshold) {
3645 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3646 + ") false wakeups, nowElapsed=" + nowELAPSED);
3647 if (mWtfThreshold < 100_000) {
3648 mWtfThreshold *= 10;
3649 } else {
3650 mFalseWakeups = 0;
3651 }
3652 }
3653 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003654 final ArraySet<Pair<String, Integer>> triggerPackages =
3655 new ArraySet<>();
3656 for (int i = 0; i < triggerList.size(); i++) {
3657 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003658 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003659 triggerPackages.add(Pair.create(
3660 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003661 }
3662 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003663 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003664 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3665 rescheduleKernelAlarmsLocked();
3666 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003667 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003669
3670 } else {
3671 // Just in case -- even though no wakeup flag was set, make sure
3672 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003673 synchronized (mLock) {
3674 rescheduleKernelAlarmsLocked();
3675 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003676 }
3677 }
3678 }
3679 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003680
David Christieebe51fc2013-07-26 13:23:29 -07003681 /**
3682 * Attribute blame for a WakeLock.
3683 * @param pi PendingIntent to attribute blame to if ws is null.
3684 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003685 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003686 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003687 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003688 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003689 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003690 final boolean unimportant = pi == mTimeTickSender;
3691 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003692 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003693 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003694 } else {
3695 mWakeLock.setHistoryTag(null);
3696 }
3697 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003698 if (ws != null) {
3699 mWakeLock.setWorkSource(ws);
3700 return;
3701 }
3702
Christopher Tate14a7bb02015-10-01 10:24:31 -07003703 final int uid = (knownUid >= 0)
3704 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003705 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003706 if (uid >= 0) {
3707 mWakeLock.setWorkSource(new WorkSource(uid));
3708 return;
3709 }
3710 } catch (Exception e) {
3711 }
3712
3713 // Something went wrong; fall back to attributing the lock to the OS
3714 mWakeLock.setWorkSource(null);
3715 }
3716
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 private class AlarmHandler extends Handler {
3718 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003719 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3720 public static final int LISTENER_TIMEOUT = 3;
3721 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003722 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3723 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003724 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 public AlarmHandler() {
3727 }
Kweku Adams61e03292017-10-19 14:27:12 -07003728
Makoto Onuki4d298b52018-02-05 10:54:58 -08003729 public void postRemoveForStopped(int uid) {
3730 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3731 }
3732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003734 switch (msg.what) {
3735 case ALARM_EVENT: {
3736 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3737 synchronized (mLock) {
3738 final long nowRTC = System.currentTimeMillis();
3739 final long nowELAPSED = SystemClock.elapsedRealtime();
3740 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3741 updateNextAlarmClockLocked();
3742 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003743
Christopher Tate14a7bb02015-10-01 10:24:31 -07003744 // now trigger the alarms without the lock held
3745 for (int i=0; i<triggerList.size(); i++) {
3746 Alarm alarm = triggerList.get(i);
3747 try {
3748 alarm.operation.send();
3749 } catch (PendingIntent.CanceledException e) {
3750 if (alarm.repeatInterval > 0) {
3751 // This IntentSender is no longer valid, but this
3752 // is a repeating alarm, so toss the hoser.
3753 removeImpl(alarm.operation);
3754 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
3756 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003757 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003759
3760 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3761 sendNextAlarmClockChanged();
3762 break;
3763
3764 case LISTENER_TIMEOUT:
3765 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3766 break;
3767
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003768 case REPORT_ALARMS_ACTIVE:
3769 if (mLocalDeviceIdleController != null) {
3770 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3771 }
3772 break;
3773
Suprabh Shukla75edab12018-01-29 14:09:06 -08003774 case APP_STANDBY_PAROLE_CHANGED:
3775 synchronized (mLock) {
3776 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003777 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3778 rescheduleKernelAlarmsLocked();
3779 updateNextAlarmClockLocked();
3780 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003781 }
3782 break;
3783
3784 case APP_STANDBY_BUCKET_CHANGED:
3785 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003786 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3787 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3788 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3789 rescheduleKernelAlarmsLocked();
3790 updateNextAlarmClockLocked();
3791 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003792 }
3793 break;
3794
Makoto Onuki4d298b52018-02-05 10:54:58 -08003795 case REMOVE_FOR_STOPPED:
3796 synchronized (mLock) {
3797 removeForStoppedLocked(msg.arg1);
3798 }
3799 break;
3800
Christopher Tate14a7bb02015-10-01 10:24:31 -07003801 default:
3802 // nope, just ignore it
3803 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003804 }
3805 }
3806 }
Kweku Adams61e03292017-10-19 14:27:12 -07003807
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003808 class ClockReceiver extends BroadcastReceiver {
3809 public ClockReceiver() {
3810 IntentFilter filter = new IntentFilter();
3811 filter.addAction(Intent.ACTION_TIME_TICK);
3812 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003813 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003814 }
Kweku Adams61e03292017-10-19 14:27:12 -07003815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003816 @Override
3817 public void onReceive(Context context, Intent intent) {
3818 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003819 if (DEBUG_BATCH) {
3820 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3821 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003822 synchronized (mLock) {
3823 mLastTickReceived = System.currentTimeMillis();
3824 }
Christopher Tate385e4982013-07-23 18:22:29 -07003825 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003826 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3827 // Since the kernel does not keep track of DST, we need to
3828 // reset the TZ information at the beginning of each day
3829 // based off of the current Zone gmt offset + userspace tracked
3830 // daylight savings information.
3831 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003832 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003833 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003834 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 }
3836 }
Kweku Adams61e03292017-10-19 14:27:12 -07003837
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003838 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003839 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003840 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003841
3842 // Schedule this event for the amount of time that it would take to get to
3843 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003844 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003845
David Christieebe51fc2013-07-26 13:23:29 -07003846 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003847 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003848 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3849 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003850
3851 // Finally, remember when we set the tick alarm
3852 synchronized (mLock) {
3853 mLastTickSet = currentTime;
3854 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 }
Christopher Tate385e4982013-07-23 18:22:29 -07003856
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 public void scheduleDateChangedEvent() {
3858 Calendar calendar = Calendar.getInstance();
3859 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003860 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003861 calendar.set(Calendar.MINUTE, 0);
3862 calendar.set(Calendar.SECOND, 0);
3863 calendar.set(Calendar.MILLISECOND, 0);
3864 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003865
3866 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003867 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3868 AlarmManager.FLAG_STANDALONE, workSource, null,
3869 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003870 }
3871 }
Kweku Adams61e03292017-10-19 14:27:12 -07003872
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003873 class InteractiveStateReceiver extends BroadcastReceiver {
3874 public InteractiveStateReceiver() {
3875 IntentFilter filter = new IntentFilter();
3876 filter.addAction(Intent.ACTION_SCREEN_OFF);
3877 filter.addAction(Intent.ACTION_SCREEN_ON);
3878 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3879 getContext().registerReceiver(this, filter);
3880 }
3881
3882 @Override
3883 public void onReceive(Context context, Intent intent) {
3884 synchronized (mLock) {
3885 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3886 }
3887 }
3888 }
3889
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 class UninstallReceiver extends BroadcastReceiver {
3891 public UninstallReceiver() {
3892 IntentFilter filter = new IntentFilter();
3893 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3894 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003895 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003897 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003898 // Register for events related to sdcard installation.
3899 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003900 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003901 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003902 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003903 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003904 }
Kweku Adams61e03292017-10-19 14:27:12 -07003905
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 @Override
3907 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003908 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003910 String action = intent.getAction();
3911 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003912 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3913 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3914 for (String packageName : pkgList) {
3915 if (lookForPackageLocked(packageName)) {
3916 setResultCode(Activity.RESULT_OK);
3917 return;
3918 }
3919 }
3920 return;
3921 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003922 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003923 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3924 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3925 if (userHandle >= 0) {
3926 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003927 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3928 final Pair<String, Integer> packageUser =
3929 mLastAlarmDeliveredForPackage.keyAt(i);
3930 if (packageUser.second == userHandle) {
3931 mLastAlarmDeliveredForPackage.removeAt(i);
3932 }
3933 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003934 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003935 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003936 if (uid >= 0) {
3937 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003938 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003939 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003940 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003941 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3942 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3943 // This package is being updated; don't kill its alarms.
3944 return;
3945 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003946 Uri data = intent.getData();
3947 if (data != null) {
3948 String pkg = data.getSchemeSpecificPart();
3949 if (pkg != null) {
3950 pkgList = new String[]{pkg};
3951 }
3952 }
3953 }
3954 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003955 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3956 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3957 if (ArrayUtils.contains(pkgList, packageUser.first)
3958 && packageUser.second == UserHandle.getUserId(uid)) {
3959 mLastAlarmDeliveredForPackage.removeAt(i);
3960 }
3961 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003962 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003963 if (uid >= 0) {
3964 // package-removed case
3965 removeLocked(uid);
3966 } else {
3967 // external-applications-unavailable etc case
3968 removeLocked(pkg);
3969 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003970 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003971 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3972 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3973 if (uidStats.remove(pkg) != null) {
3974 if (uidStats.size() <= 0) {
3975 mBroadcastStats.removeAt(i);
3976 }
3977 }
3978 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003979 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 }
3981 }
3982 }
3983 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003984
3985 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003986 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003987 }
3988
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003989 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003990 if (disabled) {
3991 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003992 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003993 }
3994
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003995 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003996 }
3997
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003998 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003999 if (disabled) {
4000 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004001 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004002 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004003
4004 @Override public void onUidCachedChanged(int uid, boolean cached) {
4005 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004006 };
4007
Suprabh Shukla75edab12018-01-29 14:09:06 -08004008 /**
4009 * Tracking of app assignments to standby buckets
4010 */
4011 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4012 @Override
4013 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004014 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004015 if (DEBUG_STANDBY) {
4016 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4017 bucket);
4018 }
4019 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004020 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4021 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004022 }
4023
4024 @Override
4025 public void onParoleStateChanged(boolean isParoleOn) {
4026 if (DEBUG_STANDBY) {
4027 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4028 }
4029 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4030 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4031 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4032 Boolean.valueOf(isParoleOn)).sendToTarget();
4033 }
4034 };
4035
Makoto Onuki2206af32017-11-21 16:25:35 -08004036 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004037 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004038 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004039 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004040 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004041 }
4042 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004043
4044 @Override
4045 public void unblockAlarmsForUid(int uid) {
4046 synchronized (mLock) {
4047 sendPendingBackgroundAlarmsLocked(uid, null);
4048 }
4049 }
4050
4051 @Override
4052 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4053 synchronized (mLock) {
4054 sendPendingBackgroundAlarmsLocked(uid, packageName);
4055 }
4056 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004057
4058 @Override
4059 public void onUidForeground(int uid, boolean foreground) {
4060 synchronized (mLock) {
4061 if (foreground) {
4062 mUseAllowWhileIdleShortTime.put(uid, true);
4063
4064 // Note we don't have to drain the pending while-idle alarms here, because
4065 // this event should coincide with unblockAlarmsForUid().
4066 }
4067 }
4068 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004069 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004070
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004071 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004072 String pkg = pi.getCreatorPackage();
4073 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004074 return getStatsLocked(uid, pkg);
4075 }
4076
4077 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004078 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4079 if (uidStats == null) {
4080 uidStats = new ArrayMap<String, BroadcastStats>();
4081 mBroadcastStats.put(uid, uidStats);
4082 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004083 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004085 bs = new BroadcastStats(uid, pkgName);
4086 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004087 }
4088 return bs;
4089 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004090
Christopher Tate21e9f192017-08-08 13:49:11 -07004091 /**
4092 * Canonical count of (operation.send() - onSendFinished()) and
4093 * listener send/complete/timeout invocations.
4094 * Guarded by the usual lock.
4095 */
4096 @GuardedBy("mLock")
4097 private int mSendCount = 0;
4098 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004099 private int mSendFinishCount = 0;
4100 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004101 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004102 @GuardedBy("mLock")
4103 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004104
Christopher Tate14a7bb02015-10-01 10:24:31 -07004105 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004106
Christopher Tate14a7bb02015-10-01 10:24:31 -07004107 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4108 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004109 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004110 return mInFlight.remove(i);
4111 }
4112 }
4113 mLog.w("No in-flight alarm for " + pi + " " + intent);
4114 return null;
4115 }
4116
4117 private InFlight removeLocked(IBinder listener) {
4118 for (int i = 0; i < mInFlight.size(); i++) {
4119 if (mInFlight.get(i).mListener == listener) {
4120 return mInFlight.remove(i);
4121 }
4122 }
4123 mLog.w("No in-flight alarm for listener " + listener);
4124 return null;
4125 }
4126
4127 private void updateStatsLocked(InFlight inflight) {
4128 final long nowELAPSED = SystemClock.elapsedRealtime();
4129 BroadcastStats bs = inflight.mBroadcastStats;
4130 bs.nesting--;
4131 if (bs.nesting <= 0) {
4132 bs.nesting = 0;
4133 bs.aggregateTime += nowELAPSED - bs.startTime;
4134 }
4135 FilterStats fs = inflight.mFilterStats;
4136 fs.nesting--;
4137 if (fs.nesting <= 0) {
4138 fs.nesting = 0;
4139 fs.aggregateTime += nowELAPSED - fs.startTime;
4140 }
4141 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004142 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4143 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004144 }
4145 }
4146
4147 private void updateTrackingLocked(InFlight inflight) {
4148 if (inflight != null) {
4149 updateStatsLocked(inflight);
4150 }
4151 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004152 if (DEBUG_WAKELOCK) {
4153 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4154 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004155 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004156 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004157 mWakeLock.release();
4158 if (mInFlight.size() > 0) {
4159 mLog.w("Finished all dispatches with " + mInFlight.size()
4160 + " remaining inflights");
4161 for (int i=0; i<mInFlight.size(); i++) {
4162 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4163 }
4164 mInFlight.clear();
4165 }
4166 } else {
4167 // the next of our alarms is now in flight. reattribute the wakelock.
4168 if (mInFlight.size() > 0) {
4169 InFlight inFlight = mInFlight.get(0);
4170 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4171 inFlight.mAlarmType, inFlight.mTag, -1, false);
4172 } else {
4173 // should never happen
4174 mLog.w("Alarm wakelock still held but sent queue empty");
4175 mWakeLock.setWorkSource(null);
4176 }
4177 }
4178 }
4179
4180 /**
4181 * Callback that arrives when a direct-call alarm reports that delivery has finished
4182 */
4183 @Override
4184 public void alarmComplete(IBinder who) {
4185 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004186 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004187 + " pid=" + Binder.getCallingPid());
4188 return;
4189 }
4190
4191 final long ident = Binder.clearCallingIdentity();
4192 try {
4193 synchronized (mLock) {
4194 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4195 InFlight inflight = removeLocked(who);
4196 if (inflight != null) {
4197 if (DEBUG_LISTENER_CALLBACK) {
4198 Slog.i(TAG, "alarmComplete() from " + who);
4199 }
4200 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004201 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004202 } else {
4203 // Delivery timed out, and the timeout handling already took care of
4204 // updating our tracking here, so we needn't do anything further.
4205 if (DEBUG_LISTENER_CALLBACK) {
4206 Slog.i(TAG, "Late alarmComplete() from " + who);
4207 }
4208 }
4209 }
4210 } finally {
4211 Binder.restoreCallingIdentity(ident);
4212 }
4213 }
4214
4215 /**
4216 * Callback that arrives when a PendingIntent alarm has finished delivery
4217 */
4218 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004219 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4220 String resultData, Bundle resultExtras) {
4221 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004222 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004223 updateTrackingLocked(removeLocked(pi, intent));
4224 }
4225 }
4226
4227 /**
4228 * Timeout of a direct-call alarm delivery
4229 */
4230 public void alarmTimedOut(IBinder who) {
4231 synchronized (mLock) {
4232 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004233 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004234 // TODO: implement ANR policy for the target
4235 if (DEBUG_LISTENER_CALLBACK) {
4236 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004237 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004238 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004239 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004240 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004241 if (DEBUG_LISTENER_CALLBACK) {
4242 Slog.i(TAG, "Spurious timeout of listener " + who);
4243 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004244 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004245 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004246 }
4247 }
4248
4249 /**
4250 * Deliver an alarm and set up the post-delivery handling appropriately
4251 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004252 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004253 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4254 if (alarm.operation != null) {
4255 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004256 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004257
4258 if (alarm.priorityClass.priority == PRIO_TICK) {
4259 mLastTickIssued = nowELAPSED;
4260 }
4261
Christopher Tate14a7bb02015-10-01 10:24:31 -07004262 try {
4263 alarm.operation.send(getContext(), 0,
4264 mBackgroundIntent.putExtra(
4265 Intent.EXTRA_ALARM_COUNT, alarm.count),
4266 mDeliveryTracker, mHandler, null,
4267 allowWhileIdle ? mIdleOptions : null);
4268 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004269 if (alarm.operation == mTimeTickSender) {
4270 Slog.wtf(TAG, "mTimeTickSender canceled");
4271 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004272 if (alarm.repeatInterval > 0) {
4273 // This IntentSender is no longer valid, but this
4274 // is a repeating alarm, so toss it
4275 removeImpl(alarm.operation);
4276 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004277 // No actual delivery was possible, so the delivery tracker's
4278 // 'finished' callback won't be invoked. We also don't need
4279 // to do any wakelock or stats tracking, so we have nothing
4280 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004281 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004282 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004283 }
4284 } else {
4285 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004286 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004287 try {
4288 if (DEBUG_LISTENER_CALLBACK) {
4289 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4290 + " listener=" + alarm.listener.asBinder());
4291 }
4292 alarm.listener.doAlarm(this);
4293 mHandler.sendMessageDelayed(
4294 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4295 alarm.listener.asBinder()),
4296 mConstants.LISTENER_TIMEOUT);
4297 } catch (Exception e) {
4298 if (DEBUG_LISTENER_CALLBACK) {
4299 Slog.i(TAG, "Alarm undeliverable to listener "
4300 + alarm.listener.asBinder(), e);
4301 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004302 // As in the PendingIntent.CanceledException case, delivery of the
4303 // alarm was not possible, so we have no wakelock or timeout or
4304 // stats management to do. It threw before we posted the delayed
4305 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004306 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004307 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004308 }
4309 }
4310
4311 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004312 if (DEBUG_WAKELOCK) {
4313 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4314 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004315 if (mBroadcastRefCount == 0) {
4316 setWakelockWorkSource(alarm.operation, alarm.workSource,
4317 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4318 true);
4319 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004320 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004321 }
4322 final InFlight inflight = new InFlight(AlarmManagerService.this,
4323 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4324 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4325 mInFlight.add(inflight);
4326 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004327 if (allowWhileIdle) {
4328 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004329 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004330 if ((mAppStateTracker == null)
4331 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004332 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4333 } else {
4334 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4335 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004336 if (RECORD_DEVICE_IDLE_ALARMS) {
4337 IdleDispatchEntry ent = new IdleDispatchEntry();
4338 ent.uid = alarm.uid;
4339 ent.pkg = alarm.packageName;
4340 ent.tag = alarm.statsTag;
4341 ent.op = "DELIVER";
4342 ent.elapsedRealtime = nowELAPSED;
4343 mAllowWhileIdleDispatches.add(ent);
4344 }
4345 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004346 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004347 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4348 UserHandle.getUserId(alarm.creatorUid));
4349 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4350 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004351
4352 final BroadcastStats bs = inflight.mBroadcastStats;
4353 bs.count++;
4354 if (bs.nesting == 0) {
4355 bs.nesting = 1;
4356 bs.startTime = nowELAPSED;
4357 } else {
4358 bs.nesting++;
4359 }
4360 final FilterStats fs = inflight.mFilterStats;
4361 fs.count++;
4362 if (fs.nesting == 0) {
4363 fs.nesting = 1;
4364 fs.startTime = nowELAPSED;
4365 } else {
4366 fs.nesting++;
4367 }
4368 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4369 || alarm.type == RTC_WAKEUP) {
4370 bs.numWakeup++;
4371 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004372 ActivityManager.noteWakeupAlarm(
4373 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4374 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004375 }
4376 }
4377 }
mswest463f4c99d2018-02-01 10:13:10 -08004378
4379 private class ShellCmd extends ShellCommand {
4380
4381 IAlarmManager getBinderService() {
4382 return IAlarmManager.Stub.asInterface(mService);
4383 }
4384
4385 @Override
4386 public int onCommand(String cmd) {
4387 if (cmd == null) {
4388 return handleDefaultCommands(cmd);
4389 }
4390
4391 final PrintWriter pw = getOutPrintWriter();
4392 try {
4393 switch (cmd) {
4394 case "set-time":
4395 final long millis = Long.parseLong(getNextArgRequired());
4396 return (getBinderService().setTime(millis)) ? 0 : -1;
4397 case "set-timezone":
4398 final String tz = getNextArgRequired();
4399 getBinderService().setTimeZone(tz);
4400 return 0;
4401 default:
4402 return handleDefaultCommands(cmd);
4403 }
4404 } catch (Exception e) {
4405 pw.println(e);
4406 }
4407 return -1;
4408 }
4409
4410 @Override
4411 public void onHelp() {
4412 PrintWriter pw = getOutPrintWriter();
4413 pw.println("Alarm manager service (alarm) commands:");
4414 pw.println(" help");
4415 pw.println(" Print this help text.");
4416 pw.println(" set-time TIME");
4417 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4418 pw.println(" since the Epoch.");
4419 pw.println(" set-timezone TZ");
4420 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4421 }
4422 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004423}