blob: 4b91d39934b27ae93ff46552a3aa315281c66825 [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
Suprabh Shukla75edab12018-01-29 14:09:06 -080019import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080020import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020021import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070022import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070023import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070024import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070025import android.app.IAlarmCompleteListener;
26import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080030import android.app.usage.UsageStatsManager;
31import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070033import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070037import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070039import android.content.pm.PackageManager.NameNotFoundException;
40import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070041import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.Uri;
43import android.os.Binder;
44import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070045import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080047import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Message;
49import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070050import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070051import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080054import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070055import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070056import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020057import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080058import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020060import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080061import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080062import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070063import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020064import android.util.Log;
Suprabh Shukla75edab12018-01-29 14:09:06 -080065import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080066import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080067import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020068import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070069import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070070import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070071import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072
Christopher Tate4cb338d2013-07-26 13:11:31 -070073import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.io.FileDescriptor;
75import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070076import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080078import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import java.util.Calendar;
80import java.util.Collections;
81import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050082import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070083import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070084import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020085import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070086import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040088import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -080089import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Suprabh Shuklac25447d2018-01-19 16:43:35 -080091import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -080092import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
Christopher Tatee0a22b32013-07-11 14:43:13 -070093import static android.app.AlarmManager.RTC_WAKEUP;
94import static android.app.AlarmManager.RTC;
95import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
96import static android.app.AlarmManager.ELAPSED_REALTIME;
97
Christopher Tate21e9f192017-08-08 13:49:11 -070098import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080099import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800100import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600101import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -0800102import com.android.internal.util.LocalLog;
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000103import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -0800104
Makoto Onuki2206af32017-11-21 16:25:35 -0800105/**
106 * Alarm manager implementaion.
107 *
108 * Unit test:
109 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
110 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700112 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
113 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700115 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 static final int TIME_CHANGED_MASK = 1 << 16;
117 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800118
Christopher Tatee0a22b32013-07-11 14:43:13 -0700119 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800121
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final boolean localLOGV = false;
124 static final boolean DEBUG_BATCH = localLOGV || false;
125 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200126 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700127 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800128 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700129 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800130 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700131 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700132 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 static final int ALARM_EVENT = 1;
134 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200135
Christopher Tate14a7bb02015-10-01 10:24:31 -0700136 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700139
Adam Lesinski182f73f2013-12-05 16:48:06 -0800140 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700141
Christopher Tate24cd46f2016-02-02 14:28:01 -0800142 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
143 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700144 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
145 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200146
Adam Lesinski182f73f2013-12-05 16:48:06 -0800147 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800148
Christopher Tate14a7bb02015-10-01 10:24:31 -0700149 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800150 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800151 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700152
Adam Lesinski182f73f2013-12-05 16:48:06 -0800153 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800154
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700155 // List of alarms per uid deferred due to user applied background restrictions on the source app
156 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800157 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800158 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700159 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700160 private long mLastWakeupSet;
161 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800162 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800163 private long mLastTickSet;
164 private long mLastTickIssued; // elapsed
165 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800166 private long mLastTickAdded;
167 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800168 int mBroadcastRefCount = 0;
169 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700170 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700171 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
172 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800173 final AlarmHandler mHandler = new AlarmHandler();
174 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700175 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700177 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800178 PendingIntent mTimeTickSender;
179 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700180 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700181 boolean mInteractive = true;
182 long mNonInteractiveStartTime;
183 long mNonInteractiveTime;
184 long mLastAlarmDeliveryTime;
185 long mStartCurrentDelayTime;
186 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700187 long mLastTimeChangeClockTime;
188 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700189 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800190
Christopher Tatebb9cce52017-04-18 14:19:43 -0700191 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
192
193 /**
194 * This permission must be defined by the canonical System UI package,
195 * with protection level "signature".
196 */
197 private static final String SYSTEM_UI_SELF_PERMISSION =
198 "android.permission.systemui.IDENTITY";
199
200 /**
201 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
202 */
203 int mSystemUiUid;
204
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700205 /**
206 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700207 * used to determine the earliest we can dispatch the next such alarm. Times are in the
208 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700209 */
210 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
211
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800212 /**
213 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
214 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
215 */
216 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
217
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700218 final static class IdleDispatchEntry {
219 int uid;
220 String pkg;
221 String tag;
222 String op;
223 long elapsedRealtime;
224 long argRealtime;
225 }
226 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
227
Suprabh Shukla75edab12018-01-29 14:09:06 -0800228 interface Stats {
229 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800230 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800231 }
232
233 private final StatLogger mStatLogger = new StatLogger(new String[] {
234 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800235 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800236 });
237
Dianne Hackborna750a632015-06-16 17:18:23 -0700238 /**
239 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
240 */
241 Bundle mIdleOptions;
242
Jose Lima235510e2014-08-13 12:50:01 -0700243 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
244 new SparseArray<>();
245 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
246 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200247 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
248 new SparseBooleanArray();
249 private boolean mNextAlarmClockMayChange;
250
251 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700252 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
253 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200254
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000255 private final ForceAppStandbyTracker mForceAppStandbyTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800256 private boolean mAppStandbyParole;
257 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800258
Dianne Hackborna750a632015-06-16 17:18:23 -0700259 /**
260 * All times are in milliseconds. These constants are kept synchronized with the system
261 * global Settings. Any access to this class or its fields should be done while
262 * holding the AlarmManagerService.mLock lock.
263 */
264 private final class Constants extends ContentObserver {
265 // Key names stored in the settings value.
266 private static final String KEY_MIN_FUTURITY = "min_futurity";
267 private static final String KEY_MIN_INTERVAL = "min_interval";
268 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
269 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
270 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
271 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700272 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700273
Suprabh Shukla75edab12018-01-29 14:09:06 -0800274 // Keys for specifying throttling delay based on app standby bucketing
275 private final String[] KEYS_APP_STANDBY_DELAY = {
276 "standby_active_delay",
277 "standby_working_delay",
278 "standby_frequent_delay",
279 "standby_rare_delay",
280 "standby_never_delay",
281 };
282
Dianne Hackborna750a632015-06-16 17:18:23 -0700283 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
284 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700285 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700286 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700287 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700288 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800289 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
290 0, // Active
291 6 * 60_000, // Working
292 30 * 60_000, // Frequent
293 2 * 60 * 60_000, // Rare
294 10 * 24 * 60 * 60_000 // Never
295 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700296
Dianne Hackborna750a632015-06-16 17:18:23 -0700297 // Minimum futurity of a new alarm
298 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
299
300 // Minimum alarm recurrence interval
301 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
302
303 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
304 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
305
306 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
307 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
308
309 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
310 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
311 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
312
Christopher Tate14a7bb02015-10-01 10:24:31 -0700313 // Direct alarm listener callback timeout
314 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
315
Suprabh Shukla75edab12018-01-29 14:09:06 -0800316 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
317
Dianne Hackborna750a632015-06-16 17:18:23 -0700318 private ContentResolver mResolver;
319 private final KeyValueListParser mParser = new KeyValueListParser(',');
320 private long mLastAllowWhileIdleWhitelistDuration = -1;
321
322 public Constants(Handler handler) {
323 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700324 updateAllowWhileIdleWhitelistDurationLocked();
325 }
326
327 public void start(ContentResolver resolver) {
328 mResolver = resolver;
329 mResolver.registerContentObserver(Settings.Global.getUriFor(
330 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
331 updateConstants();
332 }
333
Dianne Hackborna750a632015-06-16 17:18:23 -0700334 public void updateAllowWhileIdleWhitelistDurationLocked() {
335 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
336 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
337 BroadcastOptions opts = BroadcastOptions.makeBasic();
338 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
339 mIdleOptions = opts.toBundle();
340 }
341 }
342
343 @Override
344 public void onChange(boolean selfChange, Uri uri) {
345 updateConstants();
346 }
347
348 private void updateConstants() {
349 synchronized (mLock) {
350 try {
351 mParser.setString(Settings.Global.getString(mResolver,
352 Settings.Global.ALARM_MANAGER_CONSTANTS));
353 } catch (IllegalArgumentException e) {
354 // Failed to parse the settings string, log this and move on
355 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800356 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700357 }
358
359 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
360 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
361 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
362 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
363 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
364 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
365 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
366 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
367 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700368 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
369 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800370 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
371 DEFAULT_APP_STANDBY_DELAYS[0]);
372 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
373 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
374 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
375 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700376 updateAllowWhileIdleWhitelistDurationLocked();
377 }
378 }
379
380 void dump(PrintWriter pw) {
381 pw.println(" Settings:");
382
383 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
384 TimeUtils.formatDuration(MIN_FUTURITY, pw);
385 pw.println();
386
387 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
388 TimeUtils.formatDuration(MIN_INTERVAL, pw);
389 pw.println();
390
Christopher Tate14a7bb02015-10-01 10:24:31 -0700391 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
392 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
393 pw.println();
394
Dianne Hackborna750a632015-06-16 17:18:23 -0700395 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
396 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
397 pw.println();
398
399 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
400 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
401 pw.println();
402
403 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
404 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
405 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800406
407 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
408 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
409 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
410 pw.println();
411 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700412 }
Kweku Adams61e03292017-10-19 14:27:12 -0700413
414 void dumpProto(ProtoOutputStream proto, long fieldId) {
415 final long token = proto.start(fieldId);
416
417 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
418 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
419 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
420 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
421 ALLOW_WHILE_IDLE_SHORT_TIME);
422 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
423 ALLOW_WHILE_IDLE_LONG_TIME);
424 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
425 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
426
427 proto.end(token);
428 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700429 }
430
431 final Constants mConstants;
432
Christopher Tate1590f1e2014-10-02 17:27:57 -0700433 // Alarm delivery ordering bookkeeping
434 static final int PRIO_TICK = 0;
435 static final int PRIO_WAKEUP = 1;
436 static final int PRIO_NORMAL = 2;
437
Dianne Hackborna750a632015-06-16 17:18:23 -0700438 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700439 int seq;
440 int priority;
441
442 PriorityClass() {
443 seq = mCurrentSeq - 1;
444 priority = PRIO_NORMAL;
445 }
446 }
447
Dianne Hackborna750a632015-06-16 17:18:23 -0700448 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700449 int mCurrentSeq = 0;
450
Dianne Hackborna750a632015-06-16 17:18:23 -0700451 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700452 public long when;
453 public int uid;
454 public String action;
455
456 public WakeupEvent(long theTime, int theUid, String theAction) {
457 when = theTime;
458 uid = theUid;
459 action = theAction;
460 }
461 }
462
Adam Lesinski182f73f2013-12-05 16:48:06 -0800463 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
464 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700465
Adrian Roosc42a1e12014-07-07 23:35:53 +0200466 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700467 long start; // These endpoints are always in ELAPSED
468 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700469 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700470
471 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
472
473 Batch() {
474 start = 0;
475 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700476 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700477 }
478
479 Batch(Alarm seed) {
480 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700481 end = seed.maxWhenElapsed;
482 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700483 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800484 if (seed.operation == mTimeTickSender) {
485 mLastTickAdded = System.currentTimeMillis();
486 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 }
488
489 int size() {
490 return alarms.size();
491 }
492
493 Alarm get(int index) {
494 return alarms.get(index);
495 }
496
497 boolean canHold(long whenElapsed, long maxWhen) {
498 return (end >= whenElapsed) && (start <= maxWhen);
499 }
500
501 boolean add(Alarm alarm) {
502 boolean newStart = false;
503 // narrows the batch if necessary; presumes that canHold(alarm) is true
504 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
505 if (index < 0) {
506 index = 0 - index - 1;
507 }
508 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800509 if (alarm.operation == mTimeTickSender) {
510 mLastTickAdded = System.currentTimeMillis();
511 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700512 if (DEBUG_BATCH) {
513 Slog.v(TAG, "Adding " + alarm + " to " + this);
514 }
515 if (alarm.whenElapsed > start) {
516 start = alarm.whenElapsed;
517 newStart = true;
518 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700519 if (alarm.maxWhenElapsed < end) {
520 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700521 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700522 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700523
524 if (DEBUG_BATCH) {
525 Slog.v(TAG, " => now " + this);
526 }
527 return newStart;
528 }
529
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800530 boolean remove(Alarm alarm) {
531 return remove(a -> (a == alarm));
532 }
533
Christopher Tate1d99c392017-12-07 16:54:04 -0800534 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700535 boolean didRemove = false;
536 long newStart = 0; // recalculate endpoints as we go
537 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700538 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700539 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800541 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700542 alarms.remove(i);
543 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200544 if (alarm.alarmClock != null) {
545 mNextAlarmClockMayChange = true;
546 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800547 if (alarm.operation == mTimeTickSender) {
548 mLastTickRemoved = System.currentTimeMillis();
549 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 } else {
551 if (alarm.whenElapsed > newStart) {
552 newStart = alarm.whenElapsed;
553 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700554 if (alarm.maxWhenElapsed < newEnd) {
555 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700556 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700557 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700558 i++;
559 }
560 }
561 if (didRemove) {
562 // commit the new batch bounds
563 start = newStart;
564 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700565 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700566 }
567 return didRemove;
568 }
569
Christopher Tatee0a22b32013-07-11 14:43:13 -0700570 boolean hasPackage(final String packageName) {
571 final int N = alarms.size();
572 for (int i = 0; i < N; i++) {
573 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700574 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700575 return true;
576 }
577 }
578 return false;
579 }
580
581 boolean hasWakeups() {
582 final int N = alarms.size();
583 for (int i = 0; i < N; i++) {
584 Alarm a = alarms.get(i);
585 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
586 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
587 return true;
588 }
589 }
590 return false;
591 }
592
593 @Override
594 public String toString() {
595 StringBuilder b = new StringBuilder(40);
596 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
597 b.append(" num="); b.append(size());
598 b.append(" start="); b.append(start);
599 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700600 if (flags != 0) {
601 b.append(" flgs=0x");
602 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700603 }
604 b.append('}');
605 return b.toString();
606 }
Kweku Adams61e03292017-10-19 14:27:12 -0700607
608 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
609 long nowRTC) {
610 final long token = proto.start(fieldId);
611
612 proto.write(BatchProto.START_REALTIME, start);
613 proto.write(BatchProto.END_REALTIME, end);
614 proto.write(BatchProto.FLAGS, flags);
615 for (Alarm a : alarms) {
616 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
617 }
618
619 proto.end(token);
620 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700621 }
622
623 static class BatchTimeOrder implements Comparator<Batch> {
624 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800625 long when1 = b1.start;
626 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800627 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700628 return 1;
629 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800630 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700631 return -1;
632 }
633 return 0;
634 }
635 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800636
637 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
638 @Override
639 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700640 // priority class trumps everything. TICK < WAKEUP < NORMAL
641 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
642 return -1;
643 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
644 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800645 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700646
647 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800648 if (lhs.whenElapsed < rhs.whenElapsed) {
649 return -1;
650 } else if (lhs.whenElapsed > rhs.whenElapsed) {
651 return 1;
652 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700653
654 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800655 return 0;
656 }
657 };
658
Christopher Tate1590f1e2014-10-02 17:27:57 -0700659 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
660 final int N = alarms.size();
661 for (int i = 0; i < N; i++) {
662 Alarm a = alarms.get(i);
663
664 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700665 if (a.operation != null
666 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700667 alarmPrio = PRIO_TICK;
668 } else if (a.wakeup) {
669 alarmPrio = PRIO_WAKEUP;
670 } else {
671 alarmPrio = PRIO_NORMAL;
672 }
673
674 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800675 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700676 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700677 if (packagePrio == null) {
678 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700679 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700680 }
681 a.priorityClass = packagePrio;
682
683 if (packagePrio.seq != mCurrentSeq) {
684 // first alarm we've seen in the current delivery generation from this package
685 packagePrio.priority = alarmPrio;
686 packagePrio.seq = mCurrentSeq;
687 } else {
688 // Multiple alarms from this package being delivered in this generation;
689 // bump the package's delivery class if it's warranted.
690 // TICK < WAKEUP < NORMAL
691 if (alarmPrio < packagePrio.priority) {
692 packagePrio.priority = alarmPrio;
693 }
694 }
695 }
696 }
697
Christopher Tatee0a22b32013-07-11 14:43:13 -0700698 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800699 static final long MIN_FUZZABLE_INTERVAL = 10000;
700 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700701 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
702
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700703 // 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 -0700704 // to run during this time are placed in mPendingWhileIdleAlarms
705 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700706 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700707 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700708
Jeff Brownb880d882014-02-10 19:47:07 -0800709 public AlarmManagerService(Context context) {
710 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700711 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800712
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000713 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
714 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
715
Christopher Tate1d99c392017-12-07 16:54:04 -0800716 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800717 }
718
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 static long convertToElapsed(long when, int type) {
720 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
721 if (isRtc) {
722 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
723 }
724 return when;
725 }
726
727 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
728 // calculate the end of our nominal delivery window for the alarm.
729 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
730 // Current heuristic: batchable window is 75% of either the recurrence interval
731 // [for a periodic alarm] or of the time from now to the desired delivery time,
732 // with a minimum delay/interval of 10 seconds, under which we will simply not
733 // defer the alarm.
734 long futurity = (interval == 0)
735 ? (triggerAtTime - now)
736 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700737 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 futurity = 0;
739 }
740 return triggerAtTime + (long)(.75 * futurity);
741 }
742
743 // returns true if the batch was added at the head
744 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
745 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
746 if (index < 0) {
747 index = 0 - index - 1;
748 }
749 list.add(index, newBatch);
750 return (index == 0);
751 }
752
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800753 private void insertAndBatchAlarmLocked(Alarm alarm) {
754 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
755 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
756
757 if (whichBatch < 0) {
758 addBatchLocked(mAlarmBatches, new Batch(alarm));
759 } else {
760 final Batch batch = mAlarmBatches.get(whichBatch);
761 if (batch.add(alarm)) {
762 // The start time of this batch advanced, so batch ordering may
763 // have just been broken. Move it to where it now belongs.
764 mAlarmBatches.remove(whichBatch);
765 addBatchLocked(mAlarmBatches, batch);
766 }
767 }
768 }
769
Christopher Tate385e4982013-07-23 18:22:29 -0700770 // Return the index of the matching batch, or -1 if none found.
771 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700772 final int N = mAlarmBatches.size();
773 for (int i = 0; i < N; i++) {
774 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700775 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700776 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700777 }
778 }
Christopher Tate385e4982013-07-23 18:22:29 -0700779 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700780 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800781 /** @return total count of the alarms in a set of alarm batches. */
782 static int getAlarmCount(ArrayList<Batch> batches) {
783 int ret = 0;
784
785 final int size = batches.size();
786 for (int i = 0; i < size; i++) {
787 ret += batches.get(i).size();
788 }
789 return ret;
790 }
791
792 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
793 if (alarms.size() == 0) {
794 return false;
795 }
796 final int batchSize = alarms.size();
797 for (int j = 0; j < batchSize; j++) {
798 if (alarms.get(j).operation == mTimeTickSender) {
799 return true;
800 }
801 }
802 return false;
803 }
804
805 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
806 final int numBatches = batches.size();
807 for (int i = 0; i < numBatches; i++) {
808 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
809 return true;
810 }
811 }
812 return false;
813 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700814
815 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
816 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700817 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700818 rebatchAllAlarmsLocked(true);
819 }
820 }
821
822 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800823 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800824 final int oldCount =
825 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
826 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
827 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
828
Christopher Tate4cb338d2013-07-26 13:11:31 -0700829 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
830 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700831 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700832 final long nowElapsed = SystemClock.elapsedRealtime();
833 final int oldBatches = oldSet.size();
834 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
835 Batch batch = oldSet.get(batchNum);
836 final int N = batch.size();
837 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700838 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700839 }
840 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700841 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
842 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
843 + " to " + mPendingIdleUntil);
844 if (mPendingIdleUntil == null) {
845 // Somehow we lost this... we need to restore all of the pending alarms.
846 restorePendingWhileIdleAlarmsLocked();
847 }
848 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800849 final int newCount =
850 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
851 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
852 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
853
854 if (oldCount != newCount) {
855 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
856 }
857 if (oldHasTick != newHasTick) {
858 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
859 }
860
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700861 rescheduleKernelAlarmsLocked();
862 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800863 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700864 }
865
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800866 /**
867 * Re-orders the alarm batches based on newly evaluated send times based on the current
868 * app-standby buckets
869 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
870 * null indicates all
871 * @return True if there was any reordering done to the current list.
872 */
873 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
874 final long start = mStatLogger.getTime();
875 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
876
877 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
878 final Batch batch = mAlarmBatches.get(batchIndex);
879 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
880 final Alarm alarm = batch.get(alarmIndex);
881 final Pair<String, Integer> packageUser =
882 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
883 if (targetPackages != null && !targetPackages.contains(packageUser)) {
884 continue;
885 }
886 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
887 batch.remove(alarm);
888 rescheduledAlarms.add(alarm);
889 }
890 }
891 if (batch.size() == 0) {
892 mAlarmBatches.remove(batchIndex);
893 }
894 }
895 for (int i = 0; i < rescheduledAlarms.size(); i++) {
896 final Alarm a = rescheduledAlarms.get(i);
897 insertAndBatchAlarmLocked(a);
898 }
899
900 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
901 return rescheduledAlarms.size() > 0;
902 }
903
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700904 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
905 a.when = a.origWhen;
906 long whenElapsed = convertToElapsed(a.when, a.type);
907 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700908 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700909 // Exact
910 maxElapsed = whenElapsed;
911 } else {
912 // Not exact. Preserve any explicit window, otherwise recalculate
913 // the window based on the alarm's new futurity. Note that this
914 // reflects a policy of preferring timely to deferred delivery.
915 maxElapsed = (a.windowLength > 0)
916 ? (whenElapsed + a.windowLength)
917 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
918 }
919 a.whenElapsed = whenElapsed;
920 a.maxWhenElapsed = maxElapsed;
921 setImplLocked(a, true, doValidate);
922 }
923
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700924 /**
925 * Sends alarms that were blocked due to user applied background restrictions - either because
926 * the user lifted those or the uid came to foreground.
927 *
928 * @param uid uid to filter on
929 * @param packageName package to filter on, or null for all packages in uid
930 */
931 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
932 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
933 if (alarmsForUid == null || alarmsForUid.size() == 0) {
934 return;
935 }
936 final ArrayList<Alarm> alarmsToDeliver;
937 if (packageName != null) {
938 if (DEBUG_BG_LIMIT) {
939 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
940 }
941 alarmsToDeliver = new ArrayList<>();
942 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
943 final Alarm a = alarmsForUid.get(i);
944 if (a.matches(packageName)) {
945 alarmsToDeliver.add(alarmsForUid.remove(i));
946 }
947 }
948 if (alarmsForUid.size() == 0) {
949 mPendingBackgroundAlarms.remove(uid);
950 }
951 } else {
952 if (DEBUG_BG_LIMIT) {
953 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
954 }
955 alarmsToDeliver = alarmsForUid;
956 mPendingBackgroundAlarms.remove(uid);
957 }
958 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
959 }
960
Makoto Onuki2206af32017-11-21 16:25:35 -0800961 /**
962 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
963 * restricted.
964 *
965 * This is only called when the global "force all apps-standby" flag changes or when the
966 * power save whitelist changes, so it's okay to be slow.
967 */
968 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700969 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800970
971 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
972 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
973
974 if (alarmsToDeliver.size() > 0) {
975 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
976 }
977 }
978
979 @VisibleForTesting
980 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
981 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
982 Predicate<Alarm> isBackgroundRestricted) {
983
984 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
985 final int uid = pendingAlarms.keyAt(uidIndex);
986 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
987
988 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
989 final Alarm alarm = alarmsForUid.get(alarmIndex);
990
991 if (isBackgroundRestricted.test(alarm)) {
992 continue;
993 }
994
995 unrestrictedAlarms.add(alarm);
996 alarmsForUid.remove(alarmIndex);
997 }
998
999 if (alarmsForUid.size() == 0) {
1000 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001001 }
1002 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001003 }
1004
1005 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1006 final int N = alarms.size();
1007 boolean hasWakeup = false;
1008 for (int i = 0; i < N; i++) {
1009 final Alarm alarm = alarms.get(i);
1010 if (alarm.wakeup) {
1011 hasWakeup = true;
1012 }
1013 alarm.count = 1;
1014 // Recurring alarms may have passed several alarm intervals while the
1015 // alarm was kept pending. Send the appropriate trigger count.
1016 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001017 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001018 // Also schedule its next recurrence
1019 final long delta = alarm.count * alarm.repeatInterval;
1020 final long nextElapsed = alarm.whenElapsed + delta;
1021 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1022 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1023 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1024 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1025 // Kernel alarms will be rescheduled as needed in setImplLocked
1026 }
1027 }
1028 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1029 // No need to wakeup for non wakeup alarms
1030 if (mPendingNonWakeupAlarms.size() == 0) {
1031 mStartCurrentDelayTime = nowELAPSED;
1032 mNextNonWakeupDeliveryTime = nowELAPSED
1033 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1034 }
1035 mPendingNonWakeupAlarms.addAll(alarms);
1036 mNumDelayedAlarms += alarms.size();
1037 } else {
1038 if (DEBUG_BG_LIMIT) {
1039 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1040 }
1041 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1042 if (mPendingNonWakeupAlarms.size() > 0) {
1043 alarms.addAll(mPendingNonWakeupAlarms);
1044 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1045 mTotalDelayTime += thisDelayTime;
1046 if (mMaxDelayTime < thisDelayTime) {
1047 mMaxDelayTime = thisDelayTime;
1048 }
1049 mPendingNonWakeupAlarms.clear();
1050 }
1051 calculateDeliveryPriorities(alarms);
1052 Collections.sort(alarms, mAlarmDispatchComparator);
1053 deliverAlarmsLocked(alarms, nowELAPSED);
1054 }
1055 }
1056
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001057 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001058 if (RECORD_DEVICE_IDLE_ALARMS) {
1059 IdleDispatchEntry ent = new IdleDispatchEntry();
1060 ent.uid = 0;
1061 ent.pkg = "FINISH IDLE";
1062 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1063 mAllowWhileIdleDispatches.add(ent);
1064 }
1065
Dianne Hackborn35d54032015-04-23 10:30:43 -07001066 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001067 if (mPendingWhileIdleAlarms.size() > 0) {
1068 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1069 mPendingWhileIdleAlarms = new ArrayList<>();
1070 final long nowElapsed = SystemClock.elapsedRealtime();
1071 for (int i=alarms.size() - 1; i >= 0; i--) {
1072 Alarm a = alarms.get(i);
1073 reAddAlarmLocked(a, nowElapsed, false);
1074 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001075 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001076
1077 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001078 rescheduleKernelAlarmsLocked();
1079 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001080
1081 // And send a TIME_TICK right now, since it is important to get the UI updated.
1082 try {
1083 mTimeTickSender.send();
1084 } catch (PendingIntent.CanceledException e) {
1085 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001086 }
1087
Christopher Tate14a7bb02015-10-01 10:24:31 -07001088 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001089 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001090 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001091 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001092 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001093 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001094 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001095 final BroadcastStats mBroadcastStats;
1096 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001097 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001098
Christopher Tate14a7bb02015-10-01 10:24:31 -07001099 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1100 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1101 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001102 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001103 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001104 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001105 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001106 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001107 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001108 mBroadcastStats = (pendingIntent != null)
1109 ? service.getStatsLocked(pendingIntent)
1110 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001111 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001112 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001113 fs = new FilterStats(mBroadcastStats, mTag);
1114 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001115 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001116 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001117 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001118 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001119 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001120
1121 @Override
1122 public String toString() {
1123 return "InFlight{"
1124 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001125 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001126 + ", workSource=" + mWorkSource
1127 + ", uid=" + mUid
1128 + ", tag=" + mTag
1129 + ", broadcastStats=" + mBroadcastStats
1130 + ", filterStats=" + mFilterStats
1131 + ", alarmType=" + mAlarmType
1132 + "}";
1133 }
Kweku Adams61e03292017-10-19 14:27:12 -07001134
1135 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1136 final long token = proto.start(fieldId);
1137
1138 proto.write(InFlightProto.UID, mUid);
1139 proto.write(InFlightProto.TAG, mTag);
1140 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1141 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1142 if (mPendingIntent != null) {
1143 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1144 }
1145 if (mBroadcastStats != null) {
1146 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1147 }
1148 if (mFilterStats != null) {
1149 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1150 }
1151 if (mWorkSource != null) {
1152 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1153 }
1154
1155 proto.end(token);
1156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001157 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001158
Adam Lesinski182f73f2013-12-05 16:48:06 -08001159 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001160 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001161 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001162
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001163 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001165 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 int numWakeup;
1167 long startTime;
1168 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001169
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001170 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001171 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001172 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001173 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001174
1175 @Override
1176 public String toString() {
1177 return "FilterStats{"
1178 + "tag=" + mTag
1179 + ", lastTime=" + lastTime
1180 + ", aggregateTime=" + aggregateTime
1181 + ", count=" + count
1182 + ", numWakeup=" + numWakeup
1183 + ", startTime=" + startTime
1184 + ", nesting=" + nesting
1185 + "}";
1186 }
Kweku Adams61e03292017-10-19 14:27:12 -07001187
1188 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1189 final long token = proto.start(fieldId);
1190
1191 proto.write(FilterStatsProto.TAG, mTag);
1192 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1193 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1194 proto.write(FilterStatsProto.COUNT, count);
1195 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1196 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1197 proto.write(FilterStatsProto.NESTING, nesting);
1198
1199 proto.end(token);
1200 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001201 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001202
Adam Lesinski182f73f2013-12-05 16:48:06 -08001203 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001204 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001205 final String mPackageName;
1206
1207 long aggregateTime;
1208 int count;
1209 int numWakeup;
1210 long startTime;
1211 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001212 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001213
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001214 BroadcastStats(int uid, String packageName) {
1215 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001216 mPackageName = packageName;
1217 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001218
1219 @Override
1220 public String toString() {
1221 return "BroadcastStats{"
1222 + "uid=" + mUid
1223 + ", packageName=" + mPackageName
1224 + ", aggregateTime=" + aggregateTime
1225 + ", count=" + count
1226 + ", numWakeup=" + numWakeup
1227 + ", startTime=" + startTime
1228 + ", nesting=" + nesting
1229 + "}";
1230 }
Kweku Adams61e03292017-10-19 14:27:12 -07001231
1232 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1233 final long token = proto.start(fieldId);
1234
1235 proto.write(BroadcastStatsProto.UID, mUid);
1236 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1237 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1238 proto.write(BroadcastStatsProto.COUNT, count);
1239 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1240 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1241 proto.write(BroadcastStatsProto.NESTING, nesting);
1242
1243 proto.end(token);
1244 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001246
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001247 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1248 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001249
1250 int mNumDelayedAlarms = 0;
1251 long mTotalDelayTime = 0;
1252 long mMaxDelayTime = 0;
1253
Adam Lesinski182f73f2013-12-05 16:48:06 -08001254 @Override
1255 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001256 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001257 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001258
1259 // We have to set current TimeZone info to kernel
1260 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001261 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001262
Christopher Tate247571462017-04-10 11:45:05 -07001263 // Also sure that we're booting with a halfway sensible current time
1264 if (mNativeData != 0) {
1265 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1266 if (System.currentTimeMillis() < systemBuildTime) {
1267 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1268 + ", advancing to build time " + systemBuildTime);
1269 setKernelTime(mNativeData, systemBuildTime);
1270 }
1271 }
1272
Christopher Tatebb9cce52017-04-18 14:19:43 -07001273 // Determine SysUI's uid
1274 final PackageManager packMan = getContext().getPackageManager();
1275 try {
1276 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1277 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1278 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1279 mSystemUiUid = sysUi.uid;
1280 } else {
1281 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1282 + " defined by non-privileged app " + sysUi.packageName
1283 + " - ignoring");
1284 }
1285 } catch (NameNotFoundException e) {
1286 }
1287
1288 if (mSystemUiUid <= 0) {
1289 Slog.wtf(TAG, "SysUI package not found!");
1290 }
1291
Adam Lesinski182f73f2013-12-05 16:48:06 -08001292 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001293 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001294
Adam Lesinski182f73f2013-12-05 16:48:06 -08001295 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001297 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001298 | Intent.FLAG_RECEIVER_FOREGROUND
1299 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001300 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001301 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001302 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1303 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001304 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001305 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001306
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001308 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309 mClockReceiver.scheduleTimeTickEvent();
1310 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001311 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001313
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001314 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001315 AlarmThread waitThread = new AlarmThread();
1316 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001318 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001320
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001321 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001322 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001323 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1324 | ActivityManager.UID_OBSERVER_ACTIVE,
1325 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001326 } catch (RemoteException e) {
1327 // ignored; both services live in system_server
1328 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001329 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001331
1332 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001333 public void onBootPhase(int phase) {
1334 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001335 mForceAppStandbyTracker.start();
Dianne Hackborna750a632015-06-16 17:18:23 -07001336 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001337 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001338 mLocalDeviceIdleController
1339 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001340 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1341 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Dianne Hackborna750a632015-06-16 17:18:23 -07001342 }
1343 }
1344
1345 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 protected void finalize() throws Throwable {
1347 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001348 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 } finally {
1350 super.finalize();
1351 }
1352 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001353
Adam Lesinski182f73f2013-12-05 16:48:06 -08001354 void setTimeZoneImpl(String tz) {
1355 if (TextUtils.isEmpty(tz)) {
1356 return;
David Christieebe51fc2013-07-26 13:23:29 -07001357 }
1358
Adam Lesinski182f73f2013-12-05 16:48:06 -08001359 TimeZone zone = TimeZone.getTimeZone(tz);
1360 // Prevent reentrant calls from stepping on each other when writing
1361 // the time zone property
1362 boolean timeZoneWasChanged = false;
1363 synchronized (this) {
1364 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1365 if (current == null || !current.equals(zone.getID())) {
1366 if (localLOGV) {
1367 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1368 }
1369 timeZoneWasChanged = true;
1370 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1371 }
1372
1373 // Update the kernel timezone information
1374 // Kernel tracks time offsets as 'minutes west of GMT'
1375 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001376 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001377 }
1378
1379 TimeZone.setDefault(null);
1380
1381 if (timeZoneWasChanged) {
1382 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001383 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001384 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001385 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 intent.putExtra("time-zone", zone.getID());
1387 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1388 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001390
Adam Lesinski182f73f2013-12-05 16:48:06 -08001391 void removeImpl(PendingIntent operation) {
1392 if (operation == null) {
1393 return;
1394 }
1395 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001396 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001397 }
1398 }
1399
1400 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001401 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1402 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1403 int callingUid, String callingPackage) {
1404 // must be *either* PendingIntent or AlarmReceiver, but not both
1405 if ((operation == null && directReceiver == null)
1406 || (operation != null && directReceiver != null)) {
1407 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1408 // NB: previous releases failed silently here, so we are continuing to do the same
1409 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 return;
1411 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001412
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001413 // Sanity check the window length. This will catch people mistakenly
1414 // trying to pass an end-of-window timestamp rather than a duration.
1415 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1416 Slog.w(TAG, "Window length " + windowLength
1417 + "ms suspiciously long; limiting to 1 hour");
1418 windowLength = AlarmManager.INTERVAL_HOUR;
1419 }
1420
Christopher Tate498c6cb2014-11-17 16:09:27 -08001421 // Sanity check the recurrence interval. This will catch people who supply
1422 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001423 final long minInterval = mConstants.MIN_INTERVAL;
1424 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001425 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001426 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001427 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001428 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001429 }
1430
Christopher Tatee0a22b32013-07-11 14:43:13 -07001431 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1432 throw new IllegalArgumentException("Invalid alarm type " + type);
1433 }
1434
Christopher Tate5f221e82013-07-30 17:13:15 -07001435 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001436 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001437 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001438 + " pid=" + what);
1439 triggerAtTime = 0;
1440 }
1441
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001442 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001443 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1444 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001445 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001446 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1447
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001448 final long maxElapsed;
1449 if (windowLength == AlarmManager.WINDOW_EXACT) {
1450 maxElapsed = triggerElapsed;
1451 } else if (windowLength < 0) {
1452 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001453 // Fix this window in place, so that as time approaches we don't collapse it.
1454 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001455 } else {
1456 maxElapsed = triggerElapsed + windowLength;
1457 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001458
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001459 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001460 if (DEBUG_BATCH) {
1461 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001462 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001463 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001464 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001466 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001467 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1468 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469 }
1470 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471
Christopher Tate3e04b472013-10-21 17:51:31 -07001472 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001473 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1474 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1475 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001476 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001477 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1478 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001479 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001480 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001481 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1482 + " -- package not allowed to start");
1483 return;
1484 }
1485 } catch (RemoteException e) {
1486 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001487 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001488 setImplLocked(a, false, doValidate);
1489 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001490
Suprabh Shukla75edab12018-01-29 14:09:06 -08001491 private long getMinDelayForBucketLocked(int bucket) {
1492 // Return the minimum time that should elapse before an app in the specified bucket
1493 // can receive alarms again
1494 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
1495 return mConstants.APP_STANDBY_MIN_DELAYS[4];
1496 }
1497 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) {
1498 return mConstants.APP_STANDBY_MIN_DELAYS[3];
1499 }
1500 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1501 return mConstants.APP_STANDBY_MIN_DELAYS[2];
1502 }
1503 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1504 return mConstants.APP_STANDBY_MIN_DELAYS[1];
1505 }
1506 else return mConstants.APP_STANDBY_MIN_DELAYS[0];
1507 }
1508
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001509 /**
1510 * Adjusts the alarm delivery time based on the current app standby bucket.
1511 * @param alarm The alarm to adjust
1512 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001513 */
1514 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001515 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001516 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001517 }
1518 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001519 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001520 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001521 alarm.whenElapsed = alarm.expectedWhenElapsed;
1522 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1523 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001524 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001525 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001526 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001527 final long oldWhenElapsed = alarm.whenElapsed;
1528 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1529
Suprabh Shukla75edab12018-01-29 14:09:06 -08001530 final String sourcePackage = alarm.sourcePackage;
1531 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1532 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1533 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1534
1535 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1536 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1537 if (lastElapsed > 0) {
1538 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001539 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001540 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001541 } else {
1542 // app is now eligible to run alarms at the originally requested window.
1543 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001544 alarm.whenElapsed = alarm.expectedWhenElapsed;
1545 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001546 }
1547 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001548 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001549 }
1550
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001551 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1552 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001553 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001554 // The caller has given the time they want this to happen at, however we need
1555 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001556 // bring us out of idle at an earlier time.
1557 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001558 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001559 }
1560 // Add fuzz to make the alarm go off some time before the actual desired time.
1561 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001562 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001563 if (fuzz > 0) {
1564 if (mRandom == null) {
1565 mRandom = new Random();
1566 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001567 final int delta = mRandom.nextInt(fuzz);
1568 a.whenElapsed -= delta;
1569 if (false) {
1570 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1571 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1572 Slog.d(TAG, "Applied fuzz: " + fuzz);
1573 Slog.d(TAG, "Final delta: " + delta);
1574 Slog.d(TAG, "Final when: " + a.whenElapsed);
1575 }
1576 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001577 }
1578
1579 } else if (mPendingIdleUntil != null) {
1580 // We currently have an idle until alarm scheduled; if the new alarm has
1581 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001582 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1583 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1584 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001585 == 0) {
1586 mPendingWhileIdleAlarms.add(a);
1587 return;
1588 }
1589 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001590 if (RECORD_DEVICE_IDLE_ALARMS) {
1591 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1592 IdleDispatchEntry ent = new IdleDispatchEntry();
1593 ent.uid = a.uid;
1594 ent.pkg = a.operation.getCreatorPackage();
1595 ent.tag = a.operation.getTag("");
1596 ent.op = "SET";
1597 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1598 ent.argRealtime = a.whenElapsed;
1599 mAllowWhileIdleDispatches.add(ent);
1600 }
1601 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001602 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001603 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001604
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001605 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001606 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001607 }
1608
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001609 boolean needRebatch = false;
1610
1611 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001612 if (RECORD_DEVICE_IDLE_ALARMS) {
1613 if (mPendingIdleUntil == null) {
1614 IdleDispatchEntry ent = new IdleDispatchEntry();
1615 ent.uid = 0;
1616 ent.pkg = "START IDLE";
1617 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1618 mAllowWhileIdleDispatches.add(ent);
1619 }
1620 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001621 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1622 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1623 + " to " + a);
1624 }
1625
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001626 mPendingIdleUntil = a;
1627 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001628 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1629 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1630 mNextWakeFromIdle = a;
1631 // If this wake from idle is earlier than whatever was previously scheduled,
1632 // and we are currently idling, then we need to rebatch alarms in case the idle
1633 // until time needs to be updated.
1634 if (mPendingIdleUntil != null) {
1635 needRebatch = true;
1636 }
1637 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001638 }
1639
1640 if (!rebatching) {
1641 if (DEBUG_VALIDATE) {
1642 if (doValidate && !validateConsistencyLocked()) {
1643 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1644 + " when(hex)=" + Long.toHexString(a.when)
1645 + " whenElapsed=" + a.whenElapsed
1646 + " maxWhenElapsed=" + a.maxWhenElapsed
1647 + " interval=" + a.repeatInterval + " op=" + a.operation
1648 + " flags=0x" + Integer.toHexString(a.flags));
1649 rebatchAllAlarmsLocked(false);
1650 needRebatch = false;
1651 }
1652 }
1653
1654 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001655 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001656 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001657
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001658 rescheduleKernelAlarmsLocked();
1659 updateNextAlarmClockLocked();
1660 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001661 }
1662
Christopher Tate1d99c392017-12-07 16:54:04 -08001663 /**
1664 * System-process internal API
1665 */
1666 private final class LocalService implements AlarmManagerInternal {
1667 @Override
1668 public void removeAlarmsForUid(int uid) {
1669 synchronized (mLock) {
1670 removeLocked(uid);
1671 }
1672 }
1673 }
1674
1675 /**
1676 * Public-facing binder interface
1677 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001678 private final IBinder mService = new IAlarmManager.Stub() {
1679 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001680 public void set(String callingPackage,
1681 int type, long triggerAtTime, long windowLength, long interval, int flags,
1682 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1683 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001684 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001685
1686 // make sure the caller is not lying about which package should be blamed for
1687 // wakelock time spent in alarm delivery
1688 mAppOps.checkPackage(callingUid, callingPackage);
1689
1690 // Repeating alarms must use PendingIntent, not direct listener
1691 if (interval != 0) {
1692 if (directReceiver != null) {
1693 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1694 }
1695 }
1696
Adam Lesinski182f73f2013-12-05 16:48:06 -08001697 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001698 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001699 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001700 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001701 }
1702
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001703 // No incoming callers can request either WAKE_FROM_IDLE or
1704 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1705 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1706 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1707
1708 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1709 // manager when to come out of idle mode, which is only for DeviceIdleController.
1710 if (callingUid != Process.SYSTEM_UID) {
1711 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1712 }
1713
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001714 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001715 if (windowLength == AlarmManager.WINDOW_EXACT) {
1716 flags |= AlarmManager.FLAG_STANDALONE;
1717 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001718
1719 // If this alarm is for an alarm clock, then it must be standalone and we will
1720 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001721 if (alarmClock != null) {
1722 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001723
1724 // If the caller is a core system component or on the user's whitelist, and not calling
1725 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1726 // This means we will allow these alarms to go off as normal even while idle, with no
1727 // timing restrictions.
1728 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001729 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001730 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001731 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1732 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001733 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001734
Christopher Tate14a7bb02015-10-01 10:24:31 -07001735 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1736 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001737 }
Christopher Tate89779822012-08-31 14:40:03 -07001738
Adam Lesinski182f73f2013-12-05 16:48:06 -08001739 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001740 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001741 getContext().enforceCallingOrSelfPermission(
1742 "android.permission.SET_TIME",
1743 "setTime");
1744
Greg Hackmann0cab8962014-02-21 16:35:52 -08001745 if (mNativeData == 0) {
1746 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1747 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001748 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001749
1750 synchronized (mLock) {
1751 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001754
1755 @Override
1756 public void setTimeZone(String tz) {
1757 getContext().enforceCallingOrSelfPermission(
1758 "android.permission.SET_TIME_ZONE",
1759 "setTimeZone");
1760
1761 final long oldId = Binder.clearCallingIdentity();
1762 try {
1763 setTimeZoneImpl(tz);
1764 } finally {
1765 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001768
Adam Lesinski182f73f2013-12-05 16:48:06 -08001769 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001770 public void remove(PendingIntent operation, IAlarmListener listener) {
1771 if (operation == null && listener == null) {
1772 Slog.w(TAG, "remove() with no intent or listener");
1773 return;
1774 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001775
Christopher Tate14a7bb02015-10-01 10:24:31 -07001776 synchronized (mLock) {
1777 removeLocked(operation, listener);
1778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001779 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001780
Adam Lesinski182f73f2013-12-05 16:48:06 -08001781 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001782 public long getNextWakeFromIdleTime() {
1783 return getNextWakeFromIdleTimeImpl();
1784 }
1785
1786 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001787 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001788 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1789 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1790 "getNextAlarmClock", null);
1791
1792 return getNextAlarmClockImpl(userId);
1793 }
1794
1795 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001796 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001797 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001798
1799 if (args.length > 0 && "--proto".equals(args[0])) {
1800 dumpProto(fd);
1801 } else {
1802 dumpImpl(pw);
1803 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001804 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001805 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001806
Adam Lesinski182f73f2013-12-05 16:48:06 -08001807 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 synchronized (mLock) {
1809 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001810 mConstants.dump(pw);
1811 pw.println();
1812
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001813 mForceAppStandbyTracker.dump(pw, " ");
1814 pw.println();
Makoto Onuki2206af32017-11-21 16:25:35 -08001815
Suprabh Shukla75edab12018-01-29 14:09:06 -08001816 pw.println(" App Standby Parole: " + mAppStandbyParole);
1817 pw.println();
1818
Christopher Tatee0a22b32013-07-11 14:43:13 -07001819 final long nowRTC = System.currentTimeMillis();
1820 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001821 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001822
Dianne Hackborna750a632015-06-16 17:18:23 -07001823 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001824 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001825 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001826 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001827 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001828 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001829 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1830 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001831 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001832 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1833 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001834 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1835 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001836 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001837 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001838 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001839 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1840 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001841 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001842 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1843 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001844 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001845 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1846 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001847 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001848 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1849 pw.println();
1850 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001851
1852 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1853 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001854 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001855 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001856 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001857 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001858 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1859 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001860 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001861 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1862 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001863 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001864 pw.print(" = "); pw.println(mLastWakeup);
1865 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1866 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001867 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001868
John Spurlock604a5ee2015-06-01 12:27:22 -04001869 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001870 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001871 final TreeSet<Integer> users = new TreeSet<>();
1872 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1873 users.add(mNextAlarmClockForUser.keyAt(i));
1874 }
1875 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1876 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1877 }
1878 for (int user : users) {
1879 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1880 final long time = next != null ? next.getTriggerTime() : 0;
1881 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001882 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001883 pw.print(" pendingSend:"); pw.print(pendingSend);
1884 pw.print(" time:"); pw.print(time);
1885 if (time > 0) {
1886 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1887 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1888 }
1889 pw.println();
1890 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001891 if (mAlarmBatches.size() > 0) {
1892 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001893 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001894 pw.println(mAlarmBatches.size());
1895 for (Batch b : mAlarmBatches) {
1896 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001897 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001898 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001899 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001900 pw.println();
1901 pw.println(" Pending user blocked background alarms: ");
1902 boolean blocked = false;
1903 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1904 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1905 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1906 blocked = true;
1907 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1908 }
1909 }
1910 if (!blocked) {
1911 pw.println(" none");
1912 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001913
Suprabh Shukla75edab12018-01-29 14:09:06 -08001914 pw.println(" mLastAlarmDeliveredForPackage:");
1915 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1916 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1917 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1918 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1919 pw.println();
1920 }
1921 pw.println();
1922
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001923 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001924 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001925 pw.println(" Idle mode state:");
1926 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001927 if (mPendingIdleUntil != null) {
1928 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001929 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001930 } else {
1931 pw.println("null");
1932 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001933 pw.println(" Pending alarms:");
1934 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001935 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001936 if (mNextWakeFromIdle != null) {
1937 pw.println();
1938 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001939 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001940 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001941
1942 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001943 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001944 if (mPendingNonWakeupAlarms.size() > 0) {
1945 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001946 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001947 } else {
1948 pw.println("(none)");
1949 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001950 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001951 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1952 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001953 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001954 pw.print(", max non-interactive time: ");
1955 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1956 pw.println();
1957
1958 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001959 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001960 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1961 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1962 pw.print(" Listener send count: "); pw.println(mListenerCount);
1963 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001964 pw.println();
1965
Christopher Tate7f2a0352015-12-08 10:24:33 -08001966 if (mInFlight.size() > 0) {
1967 pw.println("Outstanding deliveries:");
1968 for (int i = 0; i < mInFlight.size(); i++) {
1969 pw.print(" #"); pw.print(i); pw.print(": ");
1970 pw.println(mInFlight.get(i));
1971 }
1972 pw.println();
1973 }
1974
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001975 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001976 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001977 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08001978 pw.print(" UID ");
1979 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
1980 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001981 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08001982 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
1983 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
1984
1985 final long minInterval = getWhileIdleMinIntervalLocked(uid);
1986 pw.print(" Next allowed:");
1987 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
1988 pw.print(" (");
1989 TimeUtils.formatDuration(minInterval, 0, pw);
1990 pw.print(")");
1991
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001992 pw.println();
1993 }
1994 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08001995
1996 pw.print(" mUseAllowWhileIdleShortTime: [");
1997 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
1998 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
1999 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2000 pw.print(" ");
2001 }
2002 }
2003 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002004 pw.println();
2005
Dianne Hackborn81038902012-11-26 17:04:09 -08002006 if (mLog.dump(pw, " Recent problems", " ")) {
2007 pw.println();
2008 }
2009
2010 final FilterStats[] topFilters = new FilterStats[10];
2011 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2012 @Override
2013 public int compare(FilterStats lhs, FilterStats rhs) {
2014 if (lhs.aggregateTime < rhs.aggregateTime) {
2015 return 1;
2016 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2017 return -1;
2018 }
2019 return 0;
2020 }
2021 };
2022 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002023 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002024 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2025 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2026 for (int ip=0; ip<uidStats.size(); ip++) {
2027 BroadcastStats bs = uidStats.valueAt(ip);
2028 for (int is=0; is<bs.filterStats.size(); is++) {
2029 FilterStats fs = bs.filterStats.valueAt(is);
2030 int pos = len > 0
2031 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2032 if (pos < 0) {
2033 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002034 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002035 if (pos < topFilters.length) {
2036 int copylen = topFilters.length - pos - 1;
2037 if (copylen > 0) {
2038 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2039 }
2040 topFilters[pos] = fs;
2041 if (len < topFilters.length) {
2042 len++;
2043 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002044 }
2045 }
2046 }
2047 }
2048 if (len > 0) {
2049 pw.println(" Top Alarms:");
2050 for (int i=0; i<len; i++) {
2051 FilterStats fs = topFilters[i];
2052 pw.print(" ");
2053 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2054 TimeUtils.formatDuration(fs.aggregateTime, pw);
2055 pw.print(" running, "); pw.print(fs.numWakeup);
2056 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002057 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2058 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002059 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002060 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002061 pw.println();
2062 }
2063 }
2064
2065 pw.println(" ");
2066 pw.println(" Alarm Stats:");
2067 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002068 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2069 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2070 for (int ip=0; ip<uidStats.size(); ip++) {
2071 BroadcastStats bs = uidStats.valueAt(ip);
2072 pw.print(" ");
2073 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2074 UserHandle.formatUid(pw, bs.mUid);
2075 pw.print(":");
2076 pw.print(bs.mPackageName);
2077 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2078 pw.print(" running, "); pw.print(bs.numWakeup);
2079 pw.println(" wakeups:");
2080 tmpFilters.clear();
2081 for (int is=0; is<bs.filterStats.size(); is++) {
2082 tmpFilters.add(bs.filterStats.valueAt(is));
2083 }
2084 Collections.sort(tmpFilters, comparator);
2085 for (int i=0; i<tmpFilters.size(); i++) {
2086 FilterStats fs = tmpFilters.get(i);
2087 pw.print(" ");
2088 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2089 TimeUtils.formatDuration(fs.aggregateTime, pw);
2090 pw.print(" "); pw.print(fs.numWakeup);
2091 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002092 pw.print(" alarms, last ");
2093 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2094 pw.println(":");
2095 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002096 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002097 pw.println();
2098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002099 }
2100 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002101 pw.println();
2102 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002103
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002104 if (RECORD_DEVICE_IDLE_ALARMS) {
2105 pw.println();
2106 pw.println(" Allow while idle dispatches:");
2107 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2108 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2109 pw.print(" ");
2110 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2111 pw.print(": ");
2112 UserHandle.formatUid(pw, ent.uid);
2113 pw.print(":");
2114 pw.println(ent.pkg);
2115 if (ent.op != null) {
2116 pw.print(" ");
2117 pw.print(ent.op);
2118 pw.print(" / ");
2119 pw.print(ent.tag);
2120 if (ent.argRealtime != 0) {
2121 pw.print(" (");
2122 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2123 pw.print(")");
2124 }
2125 pw.println();
2126 }
2127 }
2128 }
2129
Christopher Tate18a75f12013-07-01 18:18:59 -07002130 if (WAKEUP_STATS) {
2131 pw.println();
2132 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002133 long last = -1;
2134 for (WakeupEvent event : mRecentWakeups) {
2135 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2136 pw.print('|');
2137 if (last < 0) {
2138 pw.print('0');
2139 } else {
2140 pw.print(event.when - last);
2141 }
2142 last = event.when;
2143 pw.print('|'); pw.print(event.uid);
2144 pw.print('|'); pw.print(event.action);
2145 pw.println();
2146 }
2147 pw.println();
2148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150 }
2151
Kweku Adams61e03292017-10-19 14:27:12 -07002152 void dumpProto(FileDescriptor fd) {
2153 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2154
2155 synchronized (mLock) {
2156 final long nowRTC = System.currentTimeMillis();
2157 final long nowElapsed = SystemClock.elapsedRealtime();
2158 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
2159 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
2160 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
2161 mLastTimeChangeClockTime);
2162 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2163 mLastTimeChangeRealtime);
2164
2165 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2166
Makoto Onuki2f0b0312018-02-08 02:30:27 +00002167 mForceAppStandbyTracker.dumpProto(proto,
2168 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07002169
2170 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2171 if (!mInteractive) {
2172 // Durations
2173 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2174 nowElapsed - mNonInteractiveStartTime);
2175 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2176 currentNonWakeupFuzzLocked(nowElapsed));
2177 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2178 nowElapsed - mLastAlarmDeliveryTime);
2179 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2180 nowElapsed - mNextNonWakeupDeliveryTime);
2181 }
2182
2183 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2184 mNextNonWakeup - nowElapsed);
2185 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2186 mNextWakeup - nowElapsed);
2187 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2188 nowElapsed - mLastWakeup);
2189 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2190 nowElapsed - mLastWakeupSet);
2191 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002192
2193 final TreeSet<Integer> users = new TreeSet<>();
2194 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2195 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2196 users.add(mNextAlarmClockForUser.keyAt(i));
2197 }
2198 final int pendingSendNextAlarmClockChangedForUserSize =
2199 mPendingSendNextAlarmClockChangedForUser.size();
2200 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2201 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2202 }
2203 for (int user : users) {
2204 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2205 final long time = next != null ? next.getTriggerTime() : 0;
2206 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2207 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2208 proto.write(AlarmClockMetadataProto.USER, user);
2209 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2210 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2211 proto.end(aToken);
2212 }
2213 for (Batch b : mAlarmBatches) {
2214 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2215 nowElapsed, nowRTC);
2216 }
2217 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2218 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2219 if (blockedAlarms != null) {
2220 for (Alarm a : blockedAlarms) {
2221 a.writeToProto(proto,
2222 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2223 nowElapsed, nowRTC);
2224 }
2225 }
2226 }
2227 if (mPendingIdleUntil != null) {
2228 mPendingIdleUntil.writeToProto(
2229 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2230 }
2231 for (Alarm a : mPendingWhileIdleAlarms) {
2232 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2233 nowElapsed, nowRTC);
2234 }
2235 if (mNextWakeFromIdle != null) {
2236 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2237 nowElapsed, nowRTC);
2238 }
2239
2240 for (Alarm a : mPendingNonWakeupAlarms) {
2241 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2242 nowElapsed, nowRTC);
2243 }
2244
2245 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2246 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2247 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2248 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2249 mNonInteractiveTime);
2250
2251 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2252 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2253 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2254 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2255 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2256
2257 for (InFlight f : mInFlight) {
2258 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2259 }
2260
Kweku Adams61e03292017-10-19 14:27:12 -07002261 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2262 final long token = proto.start(
2263 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002264 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2265 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2266
2267 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID, uid);
2268 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2269 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
2270 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002271 proto.end(token);
2272 }
2273
Makoto Onukiadb50d82018-01-29 16:20:30 -08002274 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2275 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2276 proto.write(AlarmManagerServiceProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
2277 mUseAllowWhileIdleShortTime.keyAt(i));
2278 }
2279 }
2280
Kweku Adams61e03292017-10-19 14:27:12 -07002281 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2282
2283 final FilterStats[] topFilters = new FilterStats[10];
2284 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2285 @Override
2286 public int compare(FilterStats lhs, FilterStats rhs) {
2287 if (lhs.aggregateTime < rhs.aggregateTime) {
2288 return 1;
2289 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2290 return -1;
2291 }
2292 return 0;
2293 }
2294 };
2295 int len = 0;
2296 // Get the top 10 FilterStats, ordered by aggregateTime.
2297 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2298 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2299 for (int ip = 0; ip < uidStats.size(); ++ip) {
2300 BroadcastStats bs = uidStats.valueAt(ip);
2301 for (int is = 0; is < bs.filterStats.size(); ++is) {
2302 FilterStats fs = bs.filterStats.valueAt(is);
2303 int pos = len > 0
2304 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2305 if (pos < 0) {
2306 pos = -pos - 1;
2307 }
2308 if (pos < topFilters.length) {
2309 int copylen = topFilters.length - pos - 1;
2310 if (copylen > 0) {
2311 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2312 }
2313 topFilters[pos] = fs;
2314 if (len < topFilters.length) {
2315 len++;
2316 }
2317 }
2318 }
2319 }
2320 }
2321 for (int i = 0; i < len; ++i) {
2322 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2323 FilterStats fs = topFilters[i];
2324
2325 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2326 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2327 fs.mBroadcastStats.mPackageName);
2328 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2329
2330 proto.end(token);
2331 }
2332
2333 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2334 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2335 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2336 for (int ip = 0; ip < uidStats.size(); ++ip) {
2337 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2338
2339 BroadcastStats bs = uidStats.valueAt(ip);
2340 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2341
2342 // uidStats is an ArrayMap, which we can't sort.
2343 tmpFilters.clear();
2344 for (int is = 0; is < bs.filterStats.size(); ++is) {
2345 tmpFilters.add(bs.filterStats.valueAt(is));
2346 }
2347 Collections.sort(tmpFilters, comparator);
2348 for (FilterStats fs : tmpFilters) {
2349 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2350 }
2351
2352 proto.end(token);
2353 }
2354 }
2355
2356 if (RECORD_DEVICE_IDLE_ALARMS) {
2357 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2358 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2359 final long token = proto.start(
2360 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2361
2362 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2363 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2364 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2365 proto.write(IdleDispatchEntryProto.OP, ent.op);
2366 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2367 ent.elapsedRealtime);
2368 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2369
2370 proto.end(token);
2371 }
2372 }
2373
2374 if (WAKEUP_STATS) {
2375 for (WakeupEvent event : mRecentWakeups) {
2376 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2377 proto.write(WakeupEventProto.UID, event.uid);
2378 proto.write(WakeupEventProto.ACTION, event.action);
2379 proto.write(WakeupEventProto.WHEN, event.when);
2380 proto.end(token);
2381 }
2382 }
2383 }
2384
2385 proto.flush();
2386 }
2387
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002388 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002389 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2390 PrintWriter pw = new PrintWriter(bs);
2391 final long nowRTC = System.currentTimeMillis();
2392 final long nowELAPSED = SystemClock.elapsedRealtime();
2393 final int NZ = mAlarmBatches.size();
2394 for (int iz = 0; iz < NZ; iz++) {
2395 Batch bz = mAlarmBatches.get(iz);
2396 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002397 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002398 pw.flush();
2399 Slog.v(TAG, bs.toString());
2400 bs.reset();
2401 }
2402 }
2403
2404 private boolean validateConsistencyLocked() {
2405 if (DEBUG_VALIDATE) {
2406 long lastTime = Long.MIN_VALUE;
2407 final int N = mAlarmBatches.size();
2408 for (int i = 0; i < N; i++) {
2409 Batch b = mAlarmBatches.get(i);
2410 if (b.start >= lastTime) {
2411 // duplicate start times are okay because of standalone batches
2412 lastTime = b.start;
2413 } else {
2414 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002415 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2416 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002417 return false;
2418 }
2419 }
2420 }
2421 return true;
2422 }
2423
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002424 private Batch findFirstWakeupBatchLocked() {
2425 final int N = mAlarmBatches.size();
2426 for (int i = 0; i < N; i++) {
2427 Batch b = mAlarmBatches.get(i);
2428 if (b.hasWakeups()) {
2429 return b;
2430 }
2431 }
2432 return null;
2433 }
2434
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002435 long getNextWakeFromIdleTimeImpl() {
2436 synchronized (mLock) {
2437 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2438 }
2439 }
2440
2441 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002442 synchronized (mLock) {
2443 return mNextAlarmClockForUser.get(userId);
2444 }
2445 }
2446
2447 /**
2448 * Recomputes the next alarm clock for all users.
2449 */
2450 private void updateNextAlarmClockLocked() {
2451 if (!mNextAlarmClockMayChange) {
2452 return;
2453 }
2454 mNextAlarmClockMayChange = false;
2455
Jose Lima235510e2014-08-13 12:50:01 -07002456 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002457 nextForUser.clear();
2458
2459 final int N = mAlarmBatches.size();
2460 for (int i = 0; i < N; i++) {
2461 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2462 final int M = alarms.size();
2463
2464 for (int j = 0; j < M; j++) {
2465 Alarm a = alarms.get(j);
2466 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002467 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002468 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002469
2470 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002471 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002472 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002473 " for user " + userId);
2474 }
2475
2476 // Alarms and batches are sorted by time, no need to compare times here.
2477 if (nextForUser.get(userId) == null) {
2478 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002479 } else if (a.alarmClock.equals(current)
2480 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2481 // same/earlier time and it's the one we cited before, so stick with it
2482 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002483 }
2484 }
2485 }
2486 }
2487
2488 // Update mNextAlarmForUser with new values.
2489 final int NN = nextForUser.size();
2490 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002491 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002492 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002493 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002494 if (!newAlarm.equals(currentAlarm)) {
2495 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2496 }
2497 }
2498
2499 // Remove users without any alarm clocks scheduled.
2500 final int NNN = mNextAlarmClockForUser.size();
2501 for (int i = NNN - 1; i >= 0; i--) {
2502 int userId = mNextAlarmClockForUser.keyAt(i);
2503 if (nextForUser.get(userId) == null) {
2504 updateNextAlarmInfoForUserLocked(userId, null);
2505 }
2506 }
2507 }
2508
Jose Lima235510e2014-08-13 12:50:01 -07002509 private void updateNextAlarmInfoForUserLocked(int userId,
2510 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002511 if (alarmClock != null) {
2512 if (DEBUG_ALARM_CLOCK) {
2513 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002514 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002515 }
2516 mNextAlarmClockForUser.put(userId, alarmClock);
2517 } else {
2518 if (DEBUG_ALARM_CLOCK) {
2519 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2520 }
2521 mNextAlarmClockForUser.remove(userId);
2522 }
2523
2524 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2525 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2526 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2527 }
2528
2529 /**
2530 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2531 * for which alarm clocks have changed since the last call to this.
2532 *
2533 * Do not call with a lock held. Only call from mHandler's thread.
2534 *
2535 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2536 */
2537 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002538 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002539 pendingUsers.clear();
2540
2541 synchronized (mLock) {
2542 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2543 for (int i = 0; i < N; i++) {
2544 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2545 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2546 }
2547 mPendingSendNextAlarmClockChangedForUser.clear();
2548 }
2549
2550 final int N = pendingUsers.size();
2551 for (int i = 0; i < N; i++) {
2552 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002553 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002554 Settings.System.putStringForUser(getContext().getContentResolver(),
2555 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002556 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002557 userId);
2558
2559 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2560 new UserHandle(userId));
2561 }
2562 }
2563
2564 /**
2565 * Formats an alarm like platform/packages/apps/DeskClock used to.
2566 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002567 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2568 int userId) {
2569 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002570 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2571 return (info == null) ? "" :
2572 DateFormat.format(pattern, info.getTriggerTime()).toString();
2573 }
2574
Adam Lesinski182f73f2013-12-05 16:48:06 -08002575 void rescheduleKernelAlarmsLocked() {
2576 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2577 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002578 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002579 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002580 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002581 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002582 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002583 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002584 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002585 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002586 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002587 if (firstBatch != firstWakeup) {
2588 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002589 }
2590 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002591 if (mPendingNonWakeupAlarms.size() > 0) {
2592 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2593 nextNonWakeup = mNextNonWakeupDeliveryTime;
2594 }
2595 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002596 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002597 mNextNonWakeup = nextNonWakeup;
2598 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2599 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002600 }
2601
Christopher Tate14a7bb02015-10-01 10:24:31 -07002602 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002603 if (operation == null && directReceiver == null) {
2604 if (localLOGV) {
2605 Slog.w(TAG, "requested remove() of null operation",
2606 new RuntimeException("here"));
2607 }
2608 return;
2609 }
2610
Adam Lesinski182f73f2013-12-05 16:48:06 -08002611 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002612 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002613 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2614 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002615 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002616 if (b.size() == 0) {
2617 mAlarmBatches.remove(i);
2618 }
2619 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002620 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002621 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002622 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2623 mPendingWhileIdleAlarms.remove(i);
2624 }
2625 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002626 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2627 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2628 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2629 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2630 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2631 alarmsForUid.remove(j);
2632 }
2633 }
2634 if (alarmsForUid.size() == 0) {
2635 mPendingBackgroundAlarms.removeAt(i);
2636 }
2637 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002638 if (didRemove) {
2639 if (DEBUG_BATCH) {
2640 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2641 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002642 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002643 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002644 mPendingIdleUntil = null;
2645 restorePending = true;
2646 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002647 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002648 mNextWakeFromIdle = null;
2649 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002650 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002651 if (restorePending) {
2652 restorePendingWhileIdleAlarmsLocked();
2653 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002654 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002655 }
2656 }
2657
Christopher Tate1d99c392017-12-07 16:54:04 -08002658 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002659 if (uid == Process.SYSTEM_UID) {
2660 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2661 return;
2662 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002663 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002664 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002665 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2666 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002667 didRemove |= b.remove(whichAlarms);
2668 if (b.size() == 0) {
2669 mAlarmBatches.remove(i);
2670 }
2671 }
2672 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2673 final Alarm a = mPendingWhileIdleAlarms.get(i);
2674 if (a.uid == uid) {
2675 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2676 mPendingWhileIdleAlarms.remove(i);
2677 }
2678 }
2679 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2680 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2681 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2682 if (alarmsForUid.get(j).uid == uid) {
2683 alarmsForUid.remove(j);
2684 }
2685 }
2686 if (alarmsForUid.size() == 0) {
2687 mPendingBackgroundAlarms.removeAt(i);
2688 }
2689 }
2690 if (didRemove) {
2691 if (DEBUG_BATCH) {
2692 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2693 }
2694 rebatchAllAlarmsLocked(true);
2695 rescheduleKernelAlarmsLocked();
2696 updateNextAlarmClockLocked();
2697 }
2698 }
2699
2700 void removeLocked(final String packageName) {
2701 if (packageName == null) {
2702 if (localLOGV) {
2703 Slog.w(TAG, "requested remove() of null packageName",
2704 new RuntimeException("here"));
2705 }
2706 return;
2707 }
2708
2709 boolean didRemove = false;
2710 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002711 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002712 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2713 Batch b = mAlarmBatches.get(i);
2714 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002715 if (b.size() == 0) {
2716 mAlarmBatches.remove(i);
2717 }
2718 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002719 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2720 if (oldHasTick != newHasTick) {
2721 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2722 }
2723
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002724 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002725 final Alarm a = mPendingWhileIdleAlarms.get(i);
2726 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002727 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2728 mPendingWhileIdleAlarms.remove(i);
2729 }
2730 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002731 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2732 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2733 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2734 if (alarmsForUid.get(j).matches(packageName)) {
2735 alarmsForUid.remove(j);
2736 }
2737 }
2738 if (alarmsForUid.size() == 0) {
2739 mPendingBackgroundAlarms.removeAt(i);
2740 }
2741 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002742 if (didRemove) {
2743 if (DEBUG_BATCH) {
2744 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2745 }
2746 rebatchAllAlarmsLocked(true);
2747 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002748 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002749 }
2750 }
2751
Christopher Tate1d99c392017-12-07 16:54:04 -08002752 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002753 if (uid == Process.SYSTEM_UID) {
2754 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2755 return;
2756 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002757 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002758 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2759 try {
2760 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2761 uid, a.packageName)) {
2762 return true;
2763 }
2764 } catch (RemoteException e) { /* fall through */}
2765 return false;
2766 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002767 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2768 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002769 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002770 if (b.size() == 0) {
2771 mAlarmBatches.remove(i);
2772 }
2773 }
2774 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2775 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002776 if (a.uid == uid) {
2777 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2778 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002779 }
2780 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002781 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2782 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2783 mPendingBackgroundAlarms.removeAt(i);
2784 }
2785 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002786 if (didRemove) {
2787 if (DEBUG_BATCH) {
2788 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2789 }
2790 rebatchAllAlarmsLocked(true);
2791 rescheduleKernelAlarmsLocked();
2792 updateNextAlarmClockLocked();
2793 }
2794 }
2795
Adam Lesinski182f73f2013-12-05 16:48:06 -08002796 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002797 if (userHandle == UserHandle.USER_SYSTEM) {
2798 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2799 return;
2800 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002801 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002802 final Predicate<Alarm> whichAlarms =
2803 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002804 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2805 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002806 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002807 if (b.size() == 0) {
2808 mAlarmBatches.remove(i);
2809 }
2810 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002811 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002812 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002813 == userHandle) {
2814 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2815 mPendingWhileIdleAlarms.remove(i);
2816 }
2817 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002818 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2819 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2820 mPendingBackgroundAlarms.removeAt(i);
2821 }
2822 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002823 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2824 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2825 mLastAllowWhileIdleDispatch.removeAt(i);
2826 }
2827 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002828
2829 if (didRemove) {
2830 if (DEBUG_BATCH) {
2831 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2832 }
2833 rebatchAllAlarmsLocked(true);
2834 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002835 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002836 }
2837 }
2838
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002839 void interactiveStateChangedLocked(boolean interactive) {
2840 if (mInteractive != interactive) {
2841 mInteractive = interactive;
2842 final long nowELAPSED = SystemClock.elapsedRealtime();
2843 if (interactive) {
2844 if (mPendingNonWakeupAlarms.size() > 0) {
2845 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2846 mTotalDelayTime += thisDelayTime;
2847 if (mMaxDelayTime < thisDelayTime) {
2848 mMaxDelayTime = thisDelayTime;
2849 }
2850 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2851 mPendingNonWakeupAlarms.clear();
2852 }
2853 if (mNonInteractiveStartTime > 0) {
2854 long dur = nowELAPSED - mNonInteractiveStartTime;
2855 if (dur > mNonInteractiveTime) {
2856 mNonInteractiveTime = dur;
2857 }
2858 }
2859 } else {
2860 mNonInteractiveStartTime = nowELAPSED;
2861 }
2862 }
2863 }
2864
Adam Lesinski182f73f2013-12-05 16:48:06 -08002865 boolean lookForPackageLocked(String packageName) {
2866 for (int i = 0; i < mAlarmBatches.size(); i++) {
2867 Batch b = mAlarmBatches.get(i);
2868 if (b.hasPackage(packageName)) {
2869 return true;
2870 }
2871 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002872 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002873 final Alarm a = mPendingWhileIdleAlarms.get(i);
2874 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002875 return true;
2876 }
2877 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002878 return false;
2879 }
2880
2881 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002882 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002883 // The kernel never triggers alarms with negative wakeup times
2884 // so we ensure they are positive.
2885 long alarmSeconds, alarmNanoseconds;
2886 if (when < 0) {
2887 alarmSeconds = 0;
2888 alarmNanoseconds = 0;
2889 } else {
2890 alarmSeconds = when / 1000;
2891 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2892 }
Kweku Adams61e03292017-10-19 14:27:12 -07002893
Christopher Tate8b98ade2018-02-09 11:13:19 -08002894 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2895 if (result != 0) {
2896 final long nowElapsed = SystemClock.elapsedRealtime();
2897 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2898 + " type=" + type + " when=" + when
2899 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2900 + "), ret = " + result + " = " + Os.strerror(result));
2901 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002902 } else {
2903 Message msg = Message.obtain();
2904 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002905
Adam Lesinski182f73f2013-12-05 16:48:06 -08002906 mHandler.removeMessages(ALARM_EVENT);
2907 mHandler.sendMessageAtTime(msg, when);
2908 }
2909 }
2910
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002911 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002912 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 for (int i=list.size()-1; i>=0; i--) {
2914 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002915 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2916 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002917 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 }
2919 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002920
2921 private static final String labelForType(int type) {
2922 switch (type) {
2923 case RTC: return "RTC";
2924 case RTC_WAKEUP : return "RTC_WAKEUP";
2925 case ELAPSED_REALTIME : return "ELAPSED";
2926 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002927 }
2928 return "--unknown--";
2929 }
2930
2931 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002932 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002933 for (int i=list.size()-1; i>=0; i--) {
2934 Alarm a = list.get(i);
2935 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002936 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2937 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002938 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002939 }
2940 }
2941
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002942 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002943 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002944 if (alarm.alarmClock != null) {
2945 // Don't block alarm clocks
2946 return false;
2947 }
2948 if (alarm.operation != null
2949 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2950 // Don't block starting foreground components
2951 return false;
2952 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002953 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002954 final int sourceUid = alarm.creatorUid;
Makoto Onuki2f0b0312018-02-08 02:30:27 +00002955 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage,
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002956 allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002957 }
2958
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002959 private native long init();
2960 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002961 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002962 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002963 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002964 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965
Makoto Onukiadb50d82018-01-29 16:20:30 -08002966 private long getWhileIdleMinIntervalLocked(int uid) {
2967 final boolean dozing = mPendingIdleUntil != null;
Makoto Onuki2f0b0312018-02-08 02:30:27 +00002968 final boolean ebs = mForceAppStandbyTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08002969 if (!dozing && !ebs) {
2970 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2971 }
2972 if (dozing) {
2973 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2974 }
2975 if (mUseAllowWhileIdleShortTime.get(uid)) {
2976 // if the last allow-while-idle went off while uid was fg, or the uid
2977 // recently came into fg, don't block the alarm for long.
2978 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2979 }
2980 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2981 }
2982
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002983 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002984 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002985 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002986 // batches are temporally sorted, so we need only pull from the
2987 // start of the list until we either empty it or hit a batch
2988 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002989 while (mAlarmBatches.size() > 0) {
2990 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002991 if (batch.start > nowELAPSED) {
2992 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002993 break;
2994 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002995
Christopher Tatee0a22b32013-07-11 14:43:13 -07002996 // We will (re)schedule some alarms now; don't let that interfere
2997 // with delivery of this current batch
2998 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002999
Christopher Tatee0a22b32013-07-11 14:43:13 -07003000 final int N = batch.size();
3001 for (int i = 0; i < N; i++) {
3002 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003003
3004 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3005 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
3006 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003007 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003008 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003009 if (nowELAPSED < minTime) {
3010 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3011 // alarm went off for this app. Reschedule the alarm to be in the
3012 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003013 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003014 if (alarm.maxWhenElapsed < minTime) {
3015 alarm.maxWhenElapsed = minTime;
3016 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003017 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003018 if (RECORD_DEVICE_IDLE_ALARMS) {
3019 IdleDispatchEntry ent = new IdleDispatchEntry();
3020 ent.uid = alarm.uid;
3021 ent.pkg = alarm.operation.getCreatorPackage();
3022 ent.tag = alarm.operation.getTag("");
3023 ent.op = "RESCHEDULE";
3024 ent.elapsedRealtime = nowELAPSED;
3025 ent.argRealtime = lastTime;
3026 mAllowWhileIdleDispatches.add(ent);
3027 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003028 setImplLocked(alarm, true, false);
3029 continue;
3030 }
3031 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003032 if (isBackgroundRestricted(alarm)) {
3033 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3034 if (DEBUG_BG_LIMIT) {
3035 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3036 }
3037 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3038 if (alarmsForUid == null) {
3039 alarmsForUid = new ArrayList<>();
3040 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3041 }
3042 alarmsForUid.add(alarm);
3043 continue;
3044 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003045
Christopher Tatee0a22b32013-07-11 14:43:13 -07003046 alarm.count = 1;
3047 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003048 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3049 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003050 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003051 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003052 if (mPendingIdleUntil == alarm) {
3053 mPendingIdleUntil = null;
3054 rebatchAllAlarmsLocked(false);
3055 restorePendingWhileIdleAlarmsLocked();
3056 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003057 if (mNextWakeFromIdle == alarm) {
3058 mNextWakeFromIdle = null;
3059 rebatchAllAlarmsLocked(false);
3060 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003061
3062 // Recurring alarms may have passed several alarm intervals while the
3063 // phone was asleep or off, so pass a trigger count when sending them.
3064 if (alarm.repeatInterval > 0) {
3065 // this adjustment will be zero if we're late by
3066 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003067 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003068
3069 // Also schedule its next recurrence
3070 final long delta = alarm.count * alarm.repeatInterval;
3071 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003072 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003073 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003074 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3075 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003077
Christopher Tate864d42e2014-12-02 11:48:53 -08003078 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003079 hasWakeup = true;
3080 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003081
3082 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3083 if (alarm.alarmClock != null) {
3084 mNextAlarmClockMayChange = true;
3085 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003086 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003087 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003088
Christopher Tate1590f1e2014-10-02 17:27:57 -07003089 // This is a new alarm delivery set; bump the sequence number to indicate that
3090 // all apps' alarm delivery classes should be recalculated.
3091 mCurrentSeq++;
3092 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003093 Collections.sort(triggerList, mAlarmDispatchComparator);
3094
3095 if (localLOGV) {
3096 for (int i=0; i<triggerList.size(); i++) {
3097 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3098 }
3099 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003100
3101 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003102 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003103
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 /**
3105 * This Comparator sorts Alarms into increasing time order.
3106 */
3107 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3108 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003109 long when1 = a1.whenElapsed;
3110 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003111 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 return 1;
3113 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003114 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003115 return -1;
3116 }
3117 return 0;
3118 }
3119 }
Kweku Adams61e03292017-10-19 14:27:12 -07003120
Makoto Onuki2206af32017-11-21 16:25:35 -08003121 @VisibleForTesting
3122 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003123 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003124 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003125 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003126 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003127 public final IAlarmListener listener;
3128 public final String listenerTag;
3129 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003130 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003131 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003132 public final AlarmManager.AlarmClockInfo alarmClock;
3133 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003134 public final int creatorUid;
3135 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003136 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 public int count;
3138 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003139 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003140 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003141 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003142 // Expected alarm expiry time before app standby deferring is applied.
3143 public long expectedWhenElapsed;
3144 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003146 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003147
Christopher Tate3e04b472013-10-21 17:51:31 -07003148 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003149 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3150 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3151 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003152 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003153 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003154 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3155 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003156 when = _when;
3157 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003158 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003159 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003160 maxWhenElapsed = _maxWhen;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003161 expectedMaxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003162 repeatInterval = _interval;
3163 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003164 listener = _rec;
3165 listenerTag = _listenerTag;
3166 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003167 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003168 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003169 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003170 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003171 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003172 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003173 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003175
Christopher Tate14a7bb02015-10-01 10:24:31 -07003176 public static String makeTag(PendingIntent pi, String tag, int type) {
3177 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3178 ? "*walarm*:" : "*alarm*:";
3179 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3180 }
3181
3182 public WakeupEvent makeWakeupEvent(long nowRTC) {
3183 return new WakeupEvent(nowRTC, creatorUid,
3184 (operation != null)
3185 ? operation.getIntent().getAction()
3186 : ("<listener>:" + listenerTag));
3187 }
3188
3189 // Returns true if either matches
3190 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3191 return (operation != null)
3192 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003193 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003194 }
3195
3196 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003197 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003198 }
3199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003200 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003201 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003202 StringBuilder sb = new StringBuilder(128);
3203 sb.append("Alarm{");
3204 sb.append(Integer.toHexString(System.identityHashCode(this)));
3205 sb.append(" type ");
3206 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003207 sb.append(" when ");
3208 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003209 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003210 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003211 sb.append('}');
3212 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 }
3214
Kweku Adams61e03292017-10-19 14:27:12 -07003215 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003216 SimpleDateFormat sdf) {
3217 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003218 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003219 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003220 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3221 expectedWhenElapsed, nowELAPSED, pw);
3222 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3223 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003224 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3225 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003226 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003227 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003228 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003229 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003230 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003231 }
3232 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003233 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003234 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003235 pw.print(" count="); pw.print(count);
3236 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003237 if (alarmClock != null) {
3238 pw.print(prefix); pw.println("Alarm clock:");
3239 pw.print(prefix); pw.print(" triggerTime=");
3240 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3241 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3242 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003243 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003244 if (listener != null) {
3245 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
Kweku Adams61e03292017-10-19 14:27:12 -07003248
3249 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3250 long nowRTC) {
3251 final long token = proto.start(fieldId);
3252
3253 proto.write(AlarmProto.TAG, statsTag);
3254 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003255 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003256 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3257 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3258 proto.write(AlarmProto.COUNT, count);
3259 proto.write(AlarmProto.FLAGS, flags);
3260 if (alarmClock != null) {
3261 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3262 }
3263 if (operation != null) {
3264 operation.writeToProto(proto, AlarmProto.OPERATION);
3265 }
3266 if (listener != null) {
3267 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3268 }
3269
3270 proto.end(token);
3271 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003273
Christopher Tatee0a22b32013-07-11 14:43:13 -07003274 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3275 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003276 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3277 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003278 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003279 break;
3280 }
3281
Christopher Tatee0a22b32013-07-11 14:43:13 -07003282 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003283 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3284 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003285 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003286 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003287 }
3288 }
3289
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003290 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3291 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3292 if (timeSinceOn < 5*60*1000) {
3293 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3294 return 2*60*1000;
3295 } else if (timeSinceOn < 30*60*1000) {
3296 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3297 return 15*60*1000;
3298 } else {
3299 // Otherwise, we will delay by at most an hour.
3300 return 60*60*1000;
3301 }
3302 }
3303
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003304 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003305 if (duration < 15*60*1000) {
3306 // If the duration until the time is less than 15 minutes, the maximum fuzz
3307 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003308 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003309 } else if (duration < 90*60*1000) {
3310 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3311 return 15*60*1000;
3312 } else {
3313 // Otherwise, we will fuzz by at most half an hour.
3314 return 30*60*1000;
3315 }
3316 }
3317
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003318 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3319 if (mInteractive) {
3320 return false;
3321 }
3322 if (mLastAlarmDeliveryTime <= 0) {
3323 return false;
3324 }
minho.choo649acab2014-12-12 16:13:55 +09003325 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003326 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3327 // and the next delivery time is in the past, then just deliver them all. This
3328 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3329 return false;
3330 }
3331 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3332 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3333 }
3334
3335 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3336 mLastAlarmDeliveryTime = nowELAPSED;
3337 for (int i=0; i<triggerList.size(); i++) {
3338 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003339 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003340 if (alarm.wakeup) {
3341 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3342 } else {
3343 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3344 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003345 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003346 if (localLOGV) {
3347 Slog.v(TAG, "sending alarm " + alarm);
3348 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003349 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003350 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3351 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003352 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003353 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003354 } catch (RuntimeException e) {
3355 Slog.w(TAG, "Failure sending alarm.", e);
3356 }
Tim Murray175c0f92017-11-28 15:01:04 -08003357 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003358 }
3359 }
3360
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003361 private boolean isExemptFromAppStandby(Alarm a) {
3362 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3363 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3364 }
3365
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 private class AlarmThread extends Thread
3367 {
3368 public AlarmThread()
3369 {
3370 super("AlarmManager");
3371 }
Kweku Adams61e03292017-10-19 14:27:12 -07003372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 public void run()
3374 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003375 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3376
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 while (true)
3378 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003379 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003380
Dianne Hackbornc3527222015-05-13 14:03:20 -07003381 final long nowRTC = System.currentTimeMillis();
3382 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003383 synchronized (mLock) {
3384 mLastWakeup = nowELAPSED;
3385 }
3386
3387 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003388
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003389 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003390 // The kernel can give us spurious time change notifications due to
3391 // small adjustments it makes internally; we want to filter those out.
3392 final long lastTimeChangeClockTime;
3393 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003394 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003395 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3396 expectedClockTime = lastTimeChangeClockTime
3397 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003398 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003399 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3400 || nowRTC > (expectedClockTime+1000)) {
3401 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003402 // let's do it!
3403 if (DEBUG_BATCH) {
3404 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3405 }
3406 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003407 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003408 rebatchAllAlarms();
3409 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003410 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003411 synchronized (mLock) {
3412 mNumTimeChanged++;
3413 mLastTimeChangeClockTime = nowRTC;
3414 mLastTimeChangeRealtime = nowELAPSED;
3415 }
3416 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3417 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003418 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003419 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3420 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003421 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3422
3423 // The world has changed on us, so we need to re-evaluate alarms
3424 // regardless of whether the kernel has told us one went off.
3425 result |= IS_WAKEUP_MASK;
3426 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003428
Dianne Hackbornc3527222015-05-13 14:03:20 -07003429 if (result != TIME_CHANGED_MASK) {
3430 // If this was anything besides just a time change, then figure what if
3431 // anything to do about alarms.
3432 synchronized (mLock) {
3433 if (localLOGV) Slog.v(
3434 TAG, "Checking for alarms... rtc=" + nowRTC
3435 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003436
Dianne Hackbornc3527222015-05-13 14:03:20 -07003437 if (WAKEUP_STATS) {
3438 if ((result & IS_WAKEUP_MASK) != 0) {
3439 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3440 int n = 0;
3441 for (WakeupEvent event : mRecentWakeups) {
3442 if (event.when > newEarliest) break;
3443 n++; // number of now-stale entries at the list head
3444 }
3445 for (int i = 0; i < n; i++) {
3446 mRecentWakeups.remove();
3447 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003448
Dianne Hackbornc3527222015-05-13 14:03:20 -07003449 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003450 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003451 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003452
Christopher Tate8b98ade2018-02-09 11:13:19 -08003453 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003454 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3455 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3456 // if there are no wakeup alarms and the screen is off, we can
3457 // delay what we have so far until the future.
3458 if (mPendingNonWakeupAlarms.size() == 0) {
3459 mStartCurrentDelayTime = nowELAPSED;
3460 mNextNonWakeupDeliveryTime = nowELAPSED
3461 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3462 }
3463 mPendingNonWakeupAlarms.addAll(triggerList);
3464 mNumDelayedAlarms += triggerList.size();
3465 rescheduleKernelAlarmsLocked();
3466 updateNextAlarmClockLocked();
3467 } else {
3468 // now deliver the alarm intents; if there are pending non-wakeup
3469 // alarms, we need to merge them in to the list. note we don't
3470 // just deliver them first because we generally want non-wakeup
3471 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003472 if (mPendingNonWakeupAlarms.size() > 0) {
3473 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3474 triggerList.addAll(mPendingNonWakeupAlarms);
3475 Collections.sort(triggerList, mAlarmDispatchComparator);
3476 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3477 mTotalDelayTime += thisDelayTime;
3478 if (mMaxDelayTime < thisDelayTime) {
3479 mMaxDelayTime = thisDelayTime;
3480 }
3481 mPendingNonWakeupAlarms.clear();
3482 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003483 final ArraySet<Pair<String, Integer>> triggerPackages =
3484 new ArraySet<>();
3485 for (int i = 0; i < triggerList.size(); i++) {
3486 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003487 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003488 triggerPackages.add(Pair.create(
3489 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003490 }
3491 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003492 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003493 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3494 rescheduleKernelAlarmsLocked();
3495 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003496 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003497 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003498
3499 } else {
3500 // Just in case -- even though no wakeup flag was set, make sure
3501 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003502 synchronized (mLock) {
3503 rescheduleKernelAlarmsLocked();
3504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 }
3506 }
3507 }
3508 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003509
David Christieebe51fc2013-07-26 13:23:29 -07003510 /**
3511 * Attribute blame for a WakeLock.
3512 * @param pi PendingIntent to attribute blame to if ws is null.
3513 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003514 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003515 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003516 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003517 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003518 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003519 final boolean unimportant = pi == mTimeTickSender;
3520 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003521 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003522 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003523 } else {
3524 mWakeLock.setHistoryTag(null);
3525 }
3526 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003527 if (ws != null) {
3528 mWakeLock.setWorkSource(ws);
3529 return;
3530 }
3531
Christopher Tate14a7bb02015-10-01 10:24:31 -07003532 final int uid = (knownUid >= 0)
3533 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003534 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003535 if (uid >= 0) {
3536 mWakeLock.setWorkSource(new WorkSource(uid));
3537 return;
3538 }
3539 } catch (Exception e) {
3540 }
3541
3542 // Something went wrong; fall back to attributing the lock to the OS
3543 mWakeLock.setWorkSource(null);
3544 }
3545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 private class AlarmHandler extends Handler {
3547 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003548 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3549 public static final int LISTENER_TIMEOUT = 3;
3550 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003551 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3552 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003553 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003554
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 public AlarmHandler() {
3556 }
Kweku Adams61e03292017-10-19 14:27:12 -07003557
Makoto Onuki4d298b52018-02-05 10:54:58 -08003558 public void postRemoveForStopped(int uid) {
3559 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3560 }
3561
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003563 switch (msg.what) {
3564 case ALARM_EVENT: {
3565 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3566 synchronized (mLock) {
3567 final long nowRTC = System.currentTimeMillis();
3568 final long nowELAPSED = SystemClock.elapsedRealtime();
3569 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3570 updateNextAlarmClockLocked();
3571 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003572
Christopher Tate14a7bb02015-10-01 10:24:31 -07003573 // now trigger the alarms without the lock held
3574 for (int i=0; i<triggerList.size(); i++) {
3575 Alarm alarm = triggerList.get(i);
3576 try {
3577 alarm.operation.send();
3578 } catch (PendingIntent.CanceledException e) {
3579 if (alarm.repeatInterval > 0) {
3580 // This IntentSender is no longer valid, but this
3581 // is a repeating alarm, so toss the hoser.
3582 removeImpl(alarm.operation);
3583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 }
3585 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003586 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003587 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003588
3589 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3590 sendNextAlarmClockChanged();
3591 break;
3592
3593 case LISTENER_TIMEOUT:
3594 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3595 break;
3596
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003597 case REPORT_ALARMS_ACTIVE:
3598 if (mLocalDeviceIdleController != null) {
3599 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3600 }
3601 break;
3602
Suprabh Shukla75edab12018-01-29 14:09:06 -08003603 case APP_STANDBY_PAROLE_CHANGED:
3604 synchronized (mLock) {
3605 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003606 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3607 rescheduleKernelAlarmsLocked();
3608 updateNextAlarmClockLocked();
3609 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003610 }
3611 break;
3612
3613 case APP_STANDBY_BUCKET_CHANGED:
3614 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003615 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3616 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3617 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3618 rescheduleKernelAlarmsLocked();
3619 updateNextAlarmClockLocked();
3620 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003621 }
3622 break;
3623
Makoto Onuki4d298b52018-02-05 10:54:58 -08003624 case REMOVE_FOR_STOPPED:
3625 synchronized (mLock) {
3626 removeForStoppedLocked(msg.arg1);
3627 }
3628 break;
3629
Christopher Tate14a7bb02015-10-01 10:24:31 -07003630 default:
3631 // nope, just ignore it
3632 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003633 }
3634 }
3635 }
Kweku Adams61e03292017-10-19 14:27:12 -07003636
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 class ClockReceiver extends BroadcastReceiver {
3638 public ClockReceiver() {
3639 IntentFilter filter = new IntentFilter();
3640 filter.addAction(Intent.ACTION_TIME_TICK);
3641 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003642 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003643 }
Kweku Adams61e03292017-10-19 14:27:12 -07003644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 @Override
3646 public void onReceive(Context context, Intent intent) {
3647 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003648 if (DEBUG_BATCH) {
3649 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3650 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003651 synchronized (mLock) {
3652 mLastTickReceived = System.currentTimeMillis();
3653 }
Christopher Tate385e4982013-07-23 18:22:29 -07003654 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3656 // Since the kernel does not keep track of DST, we need to
3657 // reset the TZ information at the beginning of each day
3658 // based off of the current Zone gmt offset + userspace tracked
3659 // daylight savings information.
3660 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003661 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003662 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003663 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
3665 }
Kweku Adams61e03292017-10-19 14:27:12 -07003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003668 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003669 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003670
3671 // Schedule this event for the amount of time that it would take to get to
3672 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003673 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003674
David Christieebe51fc2013-07-26 13:23:29 -07003675 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003676 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003677 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3678 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003679
3680 // Finally, remember when we set the tick alarm
3681 synchronized (mLock) {
3682 mLastTickSet = currentTime;
3683 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003684 }
Christopher Tate385e4982013-07-23 18:22:29 -07003685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003686 public void scheduleDateChangedEvent() {
3687 Calendar calendar = Calendar.getInstance();
3688 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003689 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003690 calendar.set(Calendar.MINUTE, 0);
3691 calendar.set(Calendar.SECOND, 0);
3692 calendar.set(Calendar.MILLISECOND, 0);
3693 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003694
3695 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003696 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3697 AlarmManager.FLAG_STANDALONE, workSource, null,
3698 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
3700 }
Kweku Adams61e03292017-10-19 14:27:12 -07003701
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003702 class InteractiveStateReceiver extends BroadcastReceiver {
3703 public InteractiveStateReceiver() {
3704 IntentFilter filter = new IntentFilter();
3705 filter.addAction(Intent.ACTION_SCREEN_OFF);
3706 filter.addAction(Intent.ACTION_SCREEN_ON);
3707 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3708 getContext().registerReceiver(this, filter);
3709 }
3710
3711 @Override
3712 public void onReceive(Context context, Intent intent) {
3713 synchronized (mLock) {
3714 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3715 }
3716 }
3717 }
3718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 class UninstallReceiver extends BroadcastReceiver {
3720 public UninstallReceiver() {
3721 IntentFilter filter = new IntentFilter();
3722 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3723 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003724 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003725 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003726 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003727 // Register for events related to sdcard installation.
3728 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003729 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003730 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003731 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003732 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 }
Kweku Adams61e03292017-10-19 14:27:12 -07003734
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003735 @Override
3736 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003737 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003739 String action = intent.getAction();
3740 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003741 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3742 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3743 for (String packageName : pkgList) {
3744 if (lookForPackageLocked(packageName)) {
3745 setResultCode(Activity.RESULT_OK);
3746 return;
3747 }
3748 }
3749 return;
3750 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003751 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003752 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3753 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3754 if (userHandle >= 0) {
3755 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003756 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3757 final Pair<String, Integer> packageUser =
3758 mLastAlarmDeliveredForPackage.keyAt(i);
3759 if (packageUser.second == userHandle) {
3760 mLastAlarmDeliveredForPackage.removeAt(i);
3761 }
3762 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003763 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003764 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003765 if (uid >= 0) {
3766 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003767 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003768 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003769 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003770 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3771 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3772 // This package is being updated; don't kill its alarms.
3773 return;
3774 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003775 Uri data = intent.getData();
3776 if (data != null) {
3777 String pkg = data.getSchemeSpecificPart();
3778 if (pkg != null) {
3779 pkgList = new String[]{pkg};
3780 }
3781 }
3782 }
3783 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003784 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3785 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3786 if (ArrayUtils.contains(pkgList, packageUser.first)
3787 && packageUser.second == UserHandle.getUserId(uid)) {
3788 mLastAlarmDeliveredForPackage.removeAt(i);
3789 }
3790 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003791 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003792 if (uid >= 0) {
3793 // package-removed case
3794 removeLocked(uid);
3795 } else {
3796 // external-applications-unavailable etc case
3797 removeLocked(pkg);
3798 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003799 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003800 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3801 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3802 if (uidStats.remove(pkg) != null) {
3803 if (uidStats.size() <= 0) {
3804 mBroadcastStats.removeAt(i);
3805 }
3806 }
3807 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 }
3810 }
3811 }
3812 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003813
3814 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003815 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003816 }
3817
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003818 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003819 if (disabled) {
3820 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003821 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003822 }
3823
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003824 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003825 }
3826
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003827 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003828 if (disabled) {
3829 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003830 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003831 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003832
3833 @Override public void onUidCachedChanged(int uid, boolean cached) {
3834 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003835 };
3836
Suprabh Shukla75edab12018-01-29 14:09:06 -08003837 /**
3838 * Tracking of app assignments to standby buckets
3839 */
3840 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3841 @Override
3842 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
3843 boolean idle, int bucket) {
3844 if (DEBUG_STANDBY) {
3845 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3846 bucket);
3847 }
3848 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003849 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3850 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003851 }
3852
3853 @Override
3854 public void onParoleStateChanged(boolean isParoleOn) {
3855 if (DEBUG_STANDBY) {
3856 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3857 }
3858 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3859 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3860 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3861 Boolean.valueOf(isParoleOn)).sendToTarget();
3862 }
3863 };
3864
Makoto Onuki2206af32017-11-21 16:25:35 -08003865 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003866 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003867 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003868 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003869 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003870 }
3871 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003872
3873 @Override
3874 public void unblockAlarmsForUid(int uid) {
3875 synchronized (mLock) {
3876 sendPendingBackgroundAlarmsLocked(uid, null);
3877 }
3878 }
3879
3880 @Override
3881 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3882 synchronized (mLock) {
3883 sendPendingBackgroundAlarmsLocked(uid, packageName);
3884 }
3885 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003886
3887 @Override
3888 public void onUidForeground(int uid, boolean foreground) {
3889 synchronized (mLock) {
3890 if (foreground) {
3891 mUseAllowWhileIdleShortTime.put(uid, true);
3892
3893 // Note we don't have to drain the pending while-idle alarms here, because
3894 // this event should coincide with unblockAlarmsForUid().
3895 }
3896 }
3897 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003898 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003899
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003900 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003901 String pkg = pi.getCreatorPackage();
3902 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003903 return getStatsLocked(uid, pkg);
3904 }
3905
3906 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003907 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3908 if (uidStats == null) {
3909 uidStats = new ArrayMap<String, BroadcastStats>();
3910 mBroadcastStats.put(uid, uidStats);
3911 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003912 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003913 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003914 bs = new BroadcastStats(uid, pkgName);
3915 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003916 }
3917 return bs;
3918 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003919
Christopher Tate21e9f192017-08-08 13:49:11 -07003920 /**
3921 * Canonical count of (operation.send() - onSendFinished()) and
3922 * listener send/complete/timeout invocations.
3923 * Guarded by the usual lock.
3924 */
3925 @GuardedBy("mLock")
3926 private int mSendCount = 0;
3927 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003928 private int mSendFinishCount = 0;
3929 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003930 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003931 @GuardedBy("mLock")
3932 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003933
Christopher Tate14a7bb02015-10-01 10:24:31 -07003934 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003935
Christopher Tate14a7bb02015-10-01 10:24:31 -07003936 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3937 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003938 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003939 return mInFlight.remove(i);
3940 }
3941 }
3942 mLog.w("No in-flight alarm for " + pi + " " + intent);
3943 return null;
3944 }
3945
3946 private InFlight removeLocked(IBinder listener) {
3947 for (int i = 0; i < mInFlight.size(); i++) {
3948 if (mInFlight.get(i).mListener == listener) {
3949 return mInFlight.remove(i);
3950 }
3951 }
3952 mLog.w("No in-flight alarm for listener " + listener);
3953 return null;
3954 }
3955
3956 private void updateStatsLocked(InFlight inflight) {
3957 final long nowELAPSED = SystemClock.elapsedRealtime();
3958 BroadcastStats bs = inflight.mBroadcastStats;
3959 bs.nesting--;
3960 if (bs.nesting <= 0) {
3961 bs.nesting = 0;
3962 bs.aggregateTime += nowELAPSED - bs.startTime;
3963 }
3964 FilterStats fs = inflight.mFilterStats;
3965 fs.nesting--;
3966 if (fs.nesting <= 0) {
3967 fs.nesting = 0;
3968 fs.aggregateTime += nowELAPSED - fs.startTime;
3969 }
3970 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003971 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3972 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003973 }
3974 }
3975
3976 private void updateTrackingLocked(InFlight inflight) {
3977 if (inflight != null) {
3978 updateStatsLocked(inflight);
3979 }
3980 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003981 if (DEBUG_WAKELOCK) {
3982 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3983 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003984 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003985 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003986 mWakeLock.release();
3987 if (mInFlight.size() > 0) {
3988 mLog.w("Finished all dispatches with " + mInFlight.size()
3989 + " remaining inflights");
3990 for (int i=0; i<mInFlight.size(); i++) {
3991 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3992 }
3993 mInFlight.clear();
3994 }
3995 } else {
3996 // the next of our alarms is now in flight. reattribute the wakelock.
3997 if (mInFlight.size() > 0) {
3998 InFlight inFlight = mInFlight.get(0);
3999 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4000 inFlight.mAlarmType, inFlight.mTag, -1, false);
4001 } else {
4002 // should never happen
4003 mLog.w("Alarm wakelock still held but sent queue empty");
4004 mWakeLock.setWorkSource(null);
4005 }
4006 }
4007 }
4008
4009 /**
4010 * Callback that arrives when a direct-call alarm reports that delivery has finished
4011 */
4012 @Override
4013 public void alarmComplete(IBinder who) {
4014 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004015 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004016 + " pid=" + Binder.getCallingPid());
4017 return;
4018 }
4019
4020 final long ident = Binder.clearCallingIdentity();
4021 try {
4022 synchronized (mLock) {
4023 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4024 InFlight inflight = removeLocked(who);
4025 if (inflight != null) {
4026 if (DEBUG_LISTENER_CALLBACK) {
4027 Slog.i(TAG, "alarmComplete() from " + who);
4028 }
4029 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004030 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004031 } else {
4032 // Delivery timed out, and the timeout handling already took care of
4033 // updating our tracking here, so we needn't do anything further.
4034 if (DEBUG_LISTENER_CALLBACK) {
4035 Slog.i(TAG, "Late alarmComplete() from " + who);
4036 }
4037 }
4038 }
4039 } finally {
4040 Binder.restoreCallingIdentity(ident);
4041 }
4042 }
4043
4044 /**
4045 * Callback that arrives when a PendingIntent alarm has finished delivery
4046 */
4047 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004048 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4049 String resultData, Bundle resultExtras) {
4050 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004051 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004052 updateTrackingLocked(removeLocked(pi, intent));
4053 }
4054 }
4055
4056 /**
4057 * Timeout of a direct-call alarm delivery
4058 */
4059 public void alarmTimedOut(IBinder who) {
4060 synchronized (mLock) {
4061 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004062 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004063 // TODO: implement ANR policy for the target
4064 if (DEBUG_LISTENER_CALLBACK) {
4065 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004066 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004067 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004068 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004069 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004070 if (DEBUG_LISTENER_CALLBACK) {
4071 Slog.i(TAG, "Spurious timeout of listener " + who);
4072 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004073 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004075 }
4076 }
4077
4078 /**
4079 * Deliver an alarm and set up the post-delivery handling appropriately
4080 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004081 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004082 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4083 if (alarm.operation != null) {
4084 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004085 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004086
4087 if (alarm.priorityClass.priority == PRIO_TICK) {
4088 mLastTickIssued = nowELAPSED;
4089 }
4090
Christopher Tate14a7bb02015-10-01 10:24:31 -07004091 try {
4092 alarm.operation.send(getContext(), 0,
4093 mBackgroundIntent.putExtra(
4094 Intent.EXTRA_ALARM_COUNT, alarm.count),
4095 mDeliveryTracker, mHandler, null,
4096 allowWhileIdle ? mIdleOptions : null);
4097 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004098 if (alarm.operation == mTimeTickSender) {
4099 Slog.wtf(TAG, "mTimeTickSender canceled");
4100 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004101 if (alarm.repeatInterval > 0) {
4102 // This IntentSender is no longer valid, but this
4103 // is a repeating alarm, so toss it
4104 removeImpl(alarm.operation);
4105 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004106 // No actual delivery was possible, so the delivery tracker's
4107 // 'finished' callback won't be invoked. We also don't need
4108 // to do any wakelock or stats tracking, so we have nothing
4109 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004110 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004111 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004112 }
4113 } else {
4114 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004115 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004116 try {
4117 if (DEBUG_LISTENER_CALLBACK) {
4118 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4119 + " listener=" + alarm.listener.asBinder());
4120 }
4121 alarm.listener.doAlarm(this);
4122 mHandler.sendMessageDelayed(
4123 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4124 alarm.listener.asBinder()),
4125 mConstants.LISTENER_TIMEOUT);
4126 } catch (Exception e) {
4127 if (DEBUG_LISTENER_CALLBACK) {
4128 Slog.i(TAG, "Alarm undeliverable to listener "
4129 + alarm.listener.asBinder(), e);
4130 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004131 // As in the PendingIntent.CanceledException case, delivery of the
4132 // alarm was not possible, so we have no wakelock or timeout or
4133 // stats management to do. It threw before we posted the delayed
4134 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004135 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004136 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004137 }
4138 }
4139
4140 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004141 if (DEBUG_WAKELOCK) {
4142 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4143 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004144 if (mBroadcastRefCount == 0) {
4145 setWakelockWorkSource(alarm.operation, alarm.workSource,
4146 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4147 true);
4148 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004149 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004150 }
4151 final InFlight inflight = new InFlight(AlarmManagerService.this,
4152 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4153 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4154 mInFlight.add(inflight);
4155 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004156 if (allowWhileIdle) {
4157 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004158 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onuki2f0b0312018-02-08 02:30:27 +00004159 if (mForceAppStandbyTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004160 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4161 } else {
4162 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4163 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004164 if (RECORD_DEVICE_IDLE_ALARMS) {
4165 IdleDispatchEntry ent = new IdleDispatchEntry();
4166 ent.uid = alarm.uid;
4167 ent.pkg = alarm.packageName;
4168 ent.tag = alarm.statsTag;
4169 ent.op = "DELIVER";
4170 ent.elapsedRealtime = nowELAPSED;
4171 mAllowWhileIdleDispatches.add(ent);
4172 }
4173 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004174 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004175 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4176 UserHandle.getUserId(alarm.creatorUid));
4177 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4178 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004179
4180 final BroadcastStats bs = inflight.mBroadcastStats;
4181 bs.count++;
4182 if (bs.nesting == 0) {
4183 bs.nesting = 1;
4184 bs.startTime = nowELAPSED;
4185 } else {
4186 bs.nesting++;
4187 }
4188 final FilterStats fs = inflight.mFilterStats;
4189 fs.count++;
4190 if (fs.nesting == 0) {
4191 fs.nesting = 1;
4192 fs.startTime = nowELAPSED;
4193 } else {
4194 fs.nesting++;
4195 }
4196 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4197 || alarm.type == RTC_WAKEUP) {
4198 bs.numWakeup++;
4199 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004200 ActivityManager.noteWakeupAlarm(
4201 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4202 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004203 }
4204 }
4205 }
4206}