blob: a422b7ccd274c8043c57076c2632ca8cb3dc2fde [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 Onukie4918212018-02-06 11:30:15 -0800103import com.android.internal.util.Preconditions;
104import com.android.server.AppStateTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -0800105
Makoto Onuki2206af32017-11-21 16:25:35 -0800106/**
107 * Alarm manager implementaion.
108 *
109 * Unit test:
110 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
111 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700113 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
114 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700116 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 static final int TIME_CHANGED_MASK = 1 << 16;
118 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800119
Christopher Tatee0a22b32013-07-11 14:43:13 -0700120 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800122
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final boolean localLOGV = false;
125 static final boolean DEBUG_BATCH = localLOGV || false;
126 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200127 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700128 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800129 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700130 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800131 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700132 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700133 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800134 static final int ALARM_EVENT = 1;
135 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200136
Christopher Tate14a7bb02015-10-01 10:24:31 -0700137 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800138 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800139 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700140
Adam Lesinski182f73f2013-12-05 16:48:06 -0800141 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700142
Christopher Tate24cd46f2016-02-02 14:28:01 -0800143 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
144 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700145 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
146 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200147
Adam Lesinski182f73f2013-12-05 16:48:06 -0800148 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800149
Christopher Tate14a7bb02015-10-01 10:24:31 -0700150 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800151 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800152 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700153
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800155
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700156 // List of alarms per uid deferred due to user applied background restrictions on the source app
157 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800158 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800159 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700160 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700161 private long mLastWakeupSet;
162 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800163 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800164 private long mLastTickSet;
165 private long mLastTickIssued; // elapsed
166 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800167 private long mLastTickAdded;
168 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800169 int mBroadcastRefCount = 0;
170 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700171 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700172 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
173 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800174 final AlarmHandler mHandler = new AlarmHandler();
175 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700176 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700178 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800179 PendingIntent mTimeTickSender;
180 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700181 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700182 boolean mInteractive = true;
183 long mNonInteractiveStartTime;
184 long mNonInteractiveTime;
185 long mLastAlarmDeliveryTime;
186 long mStartCurrentDelayTime;
187 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700188 long mLastTimeChangeClockTime;
189 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700190 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800191
Christopher Tatebb9cce52017-04-18 14:19:43 -0700192 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
193
194 /**
195 * This permission must be defined by the canonical System UI package,
196 * with protection level "signature".
197 */
198 private static final String SYSTEM_UI_SELF_PERMISSION =
199 "android.permission.systemui.IDENTITY";
200
201 /**
202 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
203 */
204 int mSystemUiUid;
205
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700206 /**
207 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700208 * used to determine the earliest we can dispatch the next such alarm. Times are in the
209 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700210 */
211 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
212
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800213 /**
214 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
215 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
216 */
217 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
218
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700219 final static class IdleDispatchEntry {
220 int uid;
221 String pkg;
222 String tag;
223 String op;
224 long elapsedRealtime;
225 long argRealtime;
226 }
227 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
228
Suprabh Shukla75edab12018-01-29 14:09:06 -0800229 interface Stats {
230 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800231 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800232 }
233
234 private final StatLogger mStatLogger = new StatLogger(new String[] {
235 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800236 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800237 });
238
Dianne Hackborna750a632015-06-16 17:18:23 -0700239 /**
240 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
241 */
242 Bundle mIdleOptions;
243
Jose Lima235510e2014-08-13 12:50:01 -0700244 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
245 new SparseArray<>();
246 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
247 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200248 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
249 new SparseBooleanArray();
250 private boolean mNextAlarmClockMayChange;
251
252 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700253 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
254 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200255
Makoto Onukie4918212018-02-06 11:30:15 -0800256 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800257 private boolean mAppStandbyParole;
258 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800259
Dianne Hackborna750a632015-06-16 17:18:23 -0700260 /**
261 * All times are in milliseconds. These constants are kept synchronized with the system
262 * global Settings. Any access to this class or its fields should be done while
263 * holding the AlarmManagerService.mLock lock.
264 */
265 private final class Constants extends ContentObserver {
266 // Key names stored in the settings value.
267 private static final String KEY_MIN_FUTURITY = "min_futurity";
268 private static final String KEY_MIN_INTERVAL = "min_interval";
269 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
270 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
271 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
272 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700273 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700274
Suprabh Shukla75edab12018-01-29 14:09:06 -0800275 // Keys for specifying throttling delay based on app standby bucketing
276 private final String[] KEYS_APP_STANDBY_DELAY = {
277 "standby_active_delay",
278 "standby_working_delay",
279 "standby_frequent_delay",
280 "standby_rare_delay",
281 "standby_never_delay",
282 };
283
Dianne Hackborna750a632015-06-16 17:18:23 -0700284 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
285 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700286 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700287 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700288 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700289 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800290 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
291 0, // Active
292 6 * 60_000, // Working
293 30 * 60_000, // Frequent
294 2 * 60 * 60_000, // Rare
295 10 * 24 * 60 * 60_000 // Never
296 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700297
Dianne Hackborna750a632015-06-16 17:18:23 -0700298 // Minimum futurity of a new alarm
299 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
300
301 // Minimum alarm recurrence interval
302 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
303
304 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
305 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
306
307 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
308 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
309
310 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
311 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
312 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
313
Christopher Tate14a7bb02015-10-01 10:24:31 -0700314 // Direct alarm listener callback timeout
315 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
316
Suprabh Shukla75edab12018-01-29 14:09:06 -0800317 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
318
Dianne Hackborna750a632015-06-16 17:18:23 -0700319 private ContentResolver mResolver;
320 private final KeyValueListParser mParser = new KeyValueListParser(',');
321 private long mLastAllowWhileIdleWhitelistDuration = -1;
322
323 public Constants(Handler handler) {
324 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700325 updateAllowWhileIdleWhitelistDurationLocked();
326 }
327
328 public void start(ContentResolver resolver) {
329 mResolver = resolver;
330 mResolver.registerContentObserver(Settings.Global.getUriFor(
331 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
332 updateConstants();
333 }
334
Dianne Hackborna750a632015-06-16 17:18:23 -0700335 public void updateAllowWhileIdleWhitelistDurationLocked() {
336 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
337 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
338 BroadcastOptions opts = BroadcastOptions.makeBasic();
339 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
340 mIdleOptions = opts.toBundle();
341 }
342 }
343
344 @Override
345 public void onChange(boolean selfChange, Uri uri) {
346 updateConstants();
347 }
348
349 private void updateConstants() {
350 synchronized (mLock) {
351 try {
352 mParser.setString(Settings.Global.getString(mResolver,
353 Settings.Global.ALARM_MANAGER_CONSTANTS));
354 } catch (IllegalArgumentException e) {
355 // Failed to parse the settings string, log this and move on
356 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800357 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700358 }
359
360 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
361 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
362 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
363 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
364 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
365 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
366 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
367 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
368 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700369 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
370 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800371 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
372 DEFAULT_APP_STANDBY_DELAYS[0]);
373 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
374 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
375 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
376 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700377 updateAllowWhileIdleWhitelistDurationLocked();
378 }
379 }
380
381 void dump(PrintWriter pw) {
382 pw.println(" Settings:");
383
384 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
385 TimeUtils.formatDuration(MIN_FUTURITY, pw);
386 pw.println();
387
388 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
389 TimeUtils.formatDuration(MIN_INTERVAL, pw);
390 pw.println();
391
Christopher Tate14a7bb02015-10-01 10:24:31 -0700392 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
393 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
394 pw.println();
395
Dianne Hackborna750a632015-06-16 17:18:23 -0700396 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
397 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
398 pw.println();
399
400 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
401 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
402 pw.println();
403
404 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
405 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
406 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800407
408 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
409 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
410 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
411 pw.println();
412 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700413 }
Kweku Adams61e03292017-10-19 14:27:12 -0700414
415 void dumpProto(ProtoOutputStream proto, long fieldId) {
416 final long token = proto.start(fieldId);
417
418 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
419 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
420 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
421 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
422 ALLOW_WHILE_IDLE_SHORT_TIME);
423 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
424 ALLOW_WHILE_IDLE_LONG_TIME);
425 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
426 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
427
428 proto.end(token);
429 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700430 }
431
432 final Constants mConstants;
433
Christopher Tate1590f1e2014-10-02 17:27:57 -0700434 // Alarm delivery ordering bookkeeping
435 static final int PRIO_TICK = 0;
436 static final int PRIO_WAKEUP = 1;
437 static final int PRIO_NORMAL = 2;
438
Dianne Hackborna750a632015-06-16 17:18:23 -0700439 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700440 int seq;
441 int priority;
442
443 PriorityClass() {
444 seq = mCurrentSeq - 1;
445 priority = PRIO_NORMAL;
446 }
447 }
448
Dianne Hackborna750a632015-06-16 17:18:23 -0700449 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700450 int mCurrentSeq = 0;
451
Dianne Hackborna750a632015-06-16 17:18:23 -0700452 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700453 public long when;
454 public int uid;
455 public String action;
456
457 public WakeupEvent(long theTime, int theUid, String theAction) {
458 when = theTime;
459 uid = theUid;
460 action = theAction;
461 }
462 }
463
Adam Lesinski182f73f2013-12-05 16:48:06 -0800464 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
465 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700466
Adrian Roosc42a1e12014-07-07 23:35:53 +0200467 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468 long start; // These endpoints are always in ELAPSED
469 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700470 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700471
472 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
473
474 Batch() {
475 start = 0;
476 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700477 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 }
479
480 Batch(Alarm seed) {
481 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700482 end = seed.maxWhenElapsed;
483 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700484 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800485 if (seed.operation == mTimeTickSender) {
486 mLastTickAdded = System.currentTimeMillis();
487 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700488 }
489
490 int size() {
491 return alarms.size();
492 }
493
494 Alarm get(int index) {
495 return alarms.get(index);
496 }
497
498 boolean canHold(long whenElapsed, long maxWhen) {
499 return (end >= whenElapsed) && (start <= maxWhen);
500 }
501
502 boolean add(Alarm alarm) {
503 boolean newStart = false;
504 // narrows the batch if necessary; presumes that canHold(alarm) is true
505 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
506 if (index < 0) {
507 index = 0 - index - 1;
508 }
509 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800510 if (alarm.operation == mTimeTickSender) {
511 mLastTickAdded = System.currentTimeMillis();
512 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513 if (DEBUG_BATCH) {
514 Slog.v(TAG, "Adding " + alarm + " to " + this);
515 }
516 if (alarm.whenElapsed > start) {
517 start = alarm.whenElapsed;
518 newStart = true;
519 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700520 if (alarm.maxWhenElapsed < end) {
521 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700522 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700523 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524
525 if (DEBUG_BATCH) {
526 Slog.v(TAG, " => now " + this);
527 }
528 return newStart;
529 }
530
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800531 boolean remove(Alarm alarm) {
532 return remove(a -> (a == alarm));
533 }
534
Christopher Tate1d99c392017-12-07 16:54:04 -0800535 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700536 boolean didRemove = false;
537 long newStart = 0; // recalculate endpoints as we go
538 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700539 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700540 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800542 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700543 alarms.remove(i);
544 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200545 if (alarm.alarmClock != null) {
546 mNextAlarmClockMayChange = true;
547 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800548 if (alarm.operation == mTimeTickSender) {
549 mLastTickRemoved = System.currentTimeMillis();
550 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551 } else {
552 if (alarm.whenElapsed > newStart) {
553 newStart = alarm.whenElapsed;
554 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700555 if (alarm.maxWhenElapsed < newEnd) {
556 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700558 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700559 i++;
560 }
561 }
562 if (didRemove) {
563 // commit the new batch bounds
564 start = newStart;
565 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700566 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700567 }
568 return didRemove;
569 }
570
Christopher Tatee0a22b32013-07-11 14:43:13 -0700571 boolean hasPackage(final String packageName) {
572 final int N = alarms.size();
573 for (int i = 0; i < N; i++) {
574 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700575 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 return true;
577 }
578 }
579 return false;
580 }
581
582 boolean hasWakeups() {
583 final int N = alarms.size();
584 for (int i = 0; i < N; i++) {
585 Alarm a = alarms.get(i);
586 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
587 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
588 return true;
589 }
590 }
591 return false;
592 }
593
594 @Override
595 public String toString() {
596 StringBuilder b = new StringBuilder(40);
597 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
598 b.append(" num="); b.append(size());
599 b.append(" start="); b.append(start);
600 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700601 if (flags != 0) {
602 b.append(" flgs=0x");
603 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700604 }
605 b.append('}');
606 return b.toString();
607 }
Kweku Adams61e03292017-10-19 14:27:12 -0700608
609 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
610 long nowRTC) {
611 final long token = proto.start(fieldId);
612
613 proto.write(BatchProto.START_REALTIME, start);
614 proto.write(BatchProto.END_REALTIME, end);
615 proto.write(BatchProto.FLAGS, flags);
616 for (Alarm a : alarms) {
617 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
618 }
619
620 proto.end(token);
621 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700622 }
623
624 static class BatchTimeOrder implements Comparator<Batch> {
625 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800626 long when1 = b1.start;
627 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800628 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700629 return 1;
630 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800631 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700632 return -1;
633 }
634 return 0;
635 }
636 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800637
638 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
639 @Override
640 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700641 // priority class trumps everything. TICK < WAKEUP < NORMAL
642 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
643 return -1;
644 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
645 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800646 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700647
648 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800649 if (lhs.whenElapsed < rhs.whenElapsed) {
650 return -1;
651 } else if (lhs.whenElapsed > rhs.whenElapsed) {
652 return 1;
653 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700654
655 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800656 return 0;
657 }
658 };
659
Christopher Tate1590f1e2014-10-02 17:27:57 -0700660 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
661 final int N = alarms.size();
662 for (int i = 0; i < N; i++) {
663 Alarm a = alarms.get(i);
664
665 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700666 if (a.operation != null
667 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700668 alarmPrio = PRIO_TICK;
669 } else if (a.wakeup) {
670 alarmPrio = PRIO_WAKEUP;
671 } else {
672 alarmPrio = PRIO_NORMAL;
673 }
674
675 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800676 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700677 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700678 if (packagePrio == null) {
679 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700680 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700681 }
682 a.priorityClass = packagePrio;
683
684 if (packagePrio.seq != mCurrentSeq) {
685 // first alarm we've seen in the current delivery generation from this package
686 packagePrio.priority = alarmPrio;
687 packagePrio.seq = mCurrentSeq;
688 } else {
689 // Multiple alarms from this package being delivered in this generation;
690 // bump the package's delivery class if it's warranted.
691 // TICK < WAKEUP < NORMAL
692 if (alarmPrio < packagePrio.priority) {
693 packagePrio.priority = alarmPrio;
694 }
695 }
696 }
697 }
698
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800700 static final long MIN_FUZZABLE_INTERVAL = 10000;
701 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700702 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
703
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700704 // 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 -0700705 // to run during this time are placed in mPendingWhileIdleAlarms
706 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700707 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700708 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700709
Jeff Brownb880d882014-02-10 19:47:07 -0800710 public AlarmManagerService(Context context) {
711 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700712 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800713
Christopher Tate1d99c392017-12-07 16:54:04 -0800714 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800715 }
716
Christopher Tatee0a22b32013-07-11 14:43:13 -0700717 static long convertToElapsed(long when, int type) {
718 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
719 if (isRtc) {
720 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
721 }
722 return when;
723 }
724
725 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
726 // calculate the end of our nominal delivery window for the alarm.
727 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
728 // Current heuristic: batchable window is 75% of either the recurrence interval
729 // [for a periodic alarm] or of the time from now to the desired delivery time,
730 // with a minimum delay/interval of 10 seconds, under which we will simply not
731 // defer the alarm.
732 long futurity = (interval == 0)
733 ? (triggerAtTime - now)
734 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700735 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736 futurity = 0;
737 }
738 return triggerAtTime + (long)(.75 * futurity);
739 }
740
741 // returns true if the batch was added at the head
742 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
743 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
744 if (index < 0) {
745 index = 0 - index - 1;
746 }
747 list.add(index, newBatch);
748 return (index == 0);
749 }
750
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800751 private void insertAndBatchAlarmLocked(Alarm alarm) {
752 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
753 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
754
755 if (whichBatch < 0) {
756 addBatchLocked(mAlarmBatches, new Batch(alarm));
757 } else {
758 final Batch batch = mAlarmBatches.get(whichBatch);
759 if (batch.add(alarm)) {
760 // The start time of this batch advanced, so batch ordering may
761 // have just been broken. Move it to where it now belongs.
762 mAlarmBatches.remove(whichBatch);
763 addBatchLocked(mAlarmBatches, batch);
764 }
765 }
766 }
767
Christopher Tate385e4982013-07-23 18:22:29 -0700768 // Return the index of the matching batch, or -1 if none found.
769 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700770 final int N = mAlarmBatches.size();
771 for (int i = 0; i < N; i++) {
772 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700773 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700774 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700775 }
776 }
Christopher Tate385e4982013-07-23 18:22:29 -0700777 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700778 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800779 /** @return total count of the alarms in a set of alarm batches. */
780 static int getAlarmCount(ArrayList<Batch> batches) {
781 int ret = 0;
782
783 final int size = batches.size();
784 for (int i = 0; i < size; i++) {
785 ret += batches.get(i).size();
786 }
787 return ret;
788 }
789
790 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
791 if (alarms.size() == 0) {
792 return false;
793 }
794 final int batchSize = alarms.size();
795 for (int j = 0; j < batchSize; j++) {
796 if (alarms.get(j).operation == mTimeTickSender) {
797 return true;
798 }
799 }
800 return false;
801 }
802
803 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
804 final int numBatches = batches.size();
805 for (int i = 0; i < numBatches; i++) {
806 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
807 return true;
808 }
809 }
810 return false;
811 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700812
813 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
814 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700815 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700816 rebatchAllAlarmsLocked(true);
817 }
818 }
819
820 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800821 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800822 final int oldCount =
823 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
824 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
825 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
826
Christopher Tate4cb338d2013-07-26 13:11:31 -0700827 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
828 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700829 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700830 final long nowElapsed = SystemClock.elapsedRealtime();
831 final int oldBatches = oldSet.size();
832 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
833 Batch batch = oldSet.get(batchNum);
834 final int N = batch.size();
835 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700836 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700837 }
838 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700839 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
840 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
841 + " to " + mPendingIdleUntil);
842 if (mPendingIdleUntil == null) {
843 // Somehow we lost this... we need to restore all of the pending alarms.
844 restorePendingWhileIdleAlarmsLocked();
845 }
846 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800847 final int newCount =
848 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
849 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
850 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
851
852 if (oldCount != newCount) {
853 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
854 }
855 if (oldHasTick != newHasTick) {
856 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
857 }
858
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700859 rescheduleKernelAlarmsLocked();
860 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800861 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700862 }
863
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800864 /**
865 * Re-orders the alarm batches based on newly evaluated send times based on the current
866 * app-standby buckets
867 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
868 * null indicates all
869 * @return True if there was any reordering done to the current list.
870 */
871 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
872 final long start = mStatLogger.getTime();
873 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
874
875 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
876 final Batch batch = mAlarmBatches.get(batchIndex);
877 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
878 final Alarm alarm = batch.get(alarmIndex);
879 final Pair<String, Integer> packageUser =
880 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
881 if (targetPackages != null && !targetPackages.contains(packageUser)) {
882 continue;
883 }
884 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
885 batch.remove(alarm);
886 rescheduledAlarms.add(alarm);
887 }
888 }
889 if (batch.size() == 0) {
890 mAlarmBatches.remove(batchIndex);
891 }
892 }
893 for (int i = 0; i < rescheduledAlarms.size(); i++) {
894 final Alarm a = rescheduledAlarms.get(i);
895 insertAndBatchAlarmLocked(a);
896 }
897
898 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
899 return rescheduledAlarms.size() > 0;
900 }
901
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700902 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
903 a.when = a.origWhen;
904 long whenElapsed = convertToElapsed(a.when, a.type);
905 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700906 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700907 // Exact
908 maxElapsed = whenElapsed;
909 } else {
910 // Not exact. Preserve any explicit window, otherwise recalculate
911 // the window based on the alarm's new futurity. Note that this
912 // reflects a policy of preferring timely to deferred delivery.
913 maxElapsed = (a.windowLength > 0)
914 ? (whenElapsed + a.windowLength)
915 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
916 }
917 a.whenElapsed = whenElapsed;
918 a.maxWhenElapsed = maxElapsed;
919 setImplLocked(a, true, doValidate);
920 }
921
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700922 /**
923 * Sends alarms that were blocked due to user applied background restrictions - either because
924 * the user lifted those or the uid came to foreground.
925 *
926 * @param uid uid to filter on
927 * @param packageName package to filter on, or null for all packages in uid
928 */
929 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
930 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
931 if (alarmsForUid == null || alarmsForUid.size() == 0) {
932 return;
933 }
934 final ArrayList<Alarm> alarmsToDeliver;
935 if (packageName != null) {
936 if (DEBUG_BG_LIMIT) {
937 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
938 }
939 alarmsToDeliver = new ArrayList<>();
940 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
941 final Alarm a = alarmsForUid.get(i);
942 if (a.matches(packageName)) {
943 alarmsToDeliver.add(alarmsForUid.remove(i));
944 }
945 }
946 if (alarmsForUid.size() == 0) {
947 mPendingBackgroundAlarms.remove(uid);
948 }
949 } else {
950 if (DEBUG_BG_LIMIT) {
951 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
952 }
953 alarmsToDeliver = alarmsForUid;
954 mPendingBackgroundAlarms.remove(uid);
955 }
956 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
957 }
958
Makoto Onuki2206af32017-11-21 16:25:35 -0800959 /**
960 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
961 * restricted.
962 *
963 * This is only called when the global "force all apps-standby" flag changes or when the
964 * power save whitelist changes, so it's okay to be slow.
965 */
966 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700967 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800968
969 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
970 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
971
972 if (alarmsToDeliver.size() > 0) {
973 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
974 }
975 }
976
977 @VisibleForTesting
978 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
979 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
980 Predicate<Alarm> isBackgroundRestricted) {
981
982 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
983 final int uid = pendingAlarms.keyAt(uidIndex);
984 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
985
986 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
987 final Alarm alarm = alarmsForUid.get(alarmIndex);
988
989 if (isBackgroundRestricted.test(alarm)) {
990 continue;
991 }
992
993 unrestrictedAlarms.add(alarm);
994 alarmsForUid.remove(alarmIndex);
995 }
996
997 if (alarmsForUid.size() == 0) {
998 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700999 }
1000 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001001 }
1002
1003 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1004 final int N = alarms.size();
1005 boolean hasWakeup = false;
1006 for (int i = 0; i < N; i++) {
1007 final Alarm alarm = alarms.get(i);
1008 if (alarm.wakeup) {
1009 hasWakeup = true;
1010 }
1011 alarm.count = 1;
1012 // Recurring alarms may have passed several alarm intervals while the
1013 // alarm was kept pending. Send the appropriate trigger count.
1014 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001015 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001016 // Also schedule its next recurrence
1017 final long delta = alarm.count * alarm.repeatInterval;
1018 final long nextElapsed = alarm.whenElapsed + delta;
1019 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1020 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1021 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1022 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1023 // Kernel alarms will be rescheduled as needed in setImplLocked
1024 }
1025 }
1026 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1027 // No need to wakeup for non wakeup alarms
1028 if (mPendingNonWakeupAlarms.size() == 0) {
1029 mStartCurrentDelayTime = nowELAPSED;
1030 mNextNonWakeupDeliveryTime = nowELAPSED
1031 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1032 }
1033 mPendingNonWakeupAlarms.addAll(alarms);
1034 mNumDelayedAlarms += alarms.size();
1035 } else {
1036 if (DEBUG_BG_LIMIT) {
1037 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1038 }
1039 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1040 if (mPendingNonWakeupAlarms.size() > 0) {
1041 alarms.addAll(mPendingNonWakeupAlarms);
1042 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1043 mTotalDelayTime += thisDelayTime;
1044 if (mMaxDelayTime < thisDelayTime) {
1045 mMaxDelayTime = thisDelayTime;
1046 }
1047 mPendingNonWakeupAlarms.clear();
1048 }
1049 calculateDeliveryPriorities(alarms);
1050 Collections.sort(alarms, mAlarmDispatchComparator);
1051 deliverAlarmsLocked(alarms, nowELAPSED);
1052 }
1053 }
1054
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001055 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001056 if (RECORD_DEVICE_IDLE_ALARMS) {
1057 IdleDispatchEntry ent = new IdleDispatchEntry();
1058 ent.uid = 0;
1059 ent.pkg = "FINISH IDLE";
1060 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1061 mAllowWhileIdleDispatches.add(ent);
1062 }
1063
Dianne Hackborn35d54032015-04-23 10:30:43 -07001064 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001065 if (mPendingWhileIdleAlarms.size() > 0) {
1066 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1067 mPendingWhileIdleAlarms = new ArrayList<>();
1068 final long nowElapsed = SystemClock.elapsedRealtime();
1069 for (int i=alarms.size() - 1; i >= 0; i--) {
1070 Alarm a = alarms.get(i);
1071 reAddAlarmLocked(a, nowElapsed, false);
1072 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001073 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001074
1075 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001076 rescheduleKernelAlarmsLocked();
1077 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001078
1079 // And send a TIME_TICK right now, since it is important to get the UI updated.
1080 try {
1081 mTimeTickSender.send();
1082 } catch (PendingIntent.CanceledException e) {
1083 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001084 }
1085
Christopher Tate14a7bb02015-10-01 10:24:31 -07001086 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001087 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001088 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001089 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001090 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001091 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001092 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001093 final BroadcastStats mBroadcastStats;
1094 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001095 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001096
Christopher Tate14a7bb02015-10-01 10:24:31 -07001097 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1098 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1099 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001100 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001101 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001102 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001103 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001104 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001105 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001106 mBroadcastStats = (pendingIntent != null)
1107 ? service.getStatsLocked(pendingIntent)
1108 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001109 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001110 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001111 fs = new FilterStats(mBroadcastStats, mTag);
1112 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001113 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001114 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001115 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001116 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001117 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001118
1119 @Override
1120 public String toString() {
1121 return "InFlight{"
1122 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001123 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001124 + ", workSource=" + mWorkSource
1125 + ", uid=" + mUid
1126 + ", tag=" + mTag
1127 + ", broadcastStats=" + mBroadcastStats
1128 + ", filterStats=" + mFilterStats
1129 + ", alarmType=" + mAlarmType
1130 + "}";
1131 }
Kweku Adams61e03292017-10-19 14:27:12 -07001132
1133 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1134 final long token = proto.start(fieldId);
1135
1136 proto.write(InFlightProto.UID, mUid);
1137 proto.write(InFlightProto.TAG, mTag);
1138 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1139 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1140 if (mPendingIntent != null) {
1141 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1142 }
1143 if (mBroadcastStats != null) {
1144 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1145 }
1146 if (mFilterStats != null) {
1147 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1148 }
1149 if (mWorkSource != null) {
1150 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1151 }
1152
1153 proto.end(token);
1154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001156
Adam Lesinski182f73f2013-12-05 16:48:06 -08001157 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001158 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001159 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001160
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001161 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001163 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 int numWakeup;
1165 long startTime;
1166 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001167
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001168 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001169 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001170 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001171 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001172
1173 @Override
1174 public String toString() {
1175 return "FilterStats{"
1176 + "tag=" + mTag
1177 + ", lastTime=" + lastTime
1178 + ", aggregateTime=" + aggregateTime
1179 + ", count=" + count
1180 + ", numWakeup=" + numWakeup
1181 + ", startTime=" + startTime
1182 + ", nesting=" + nesting
1183 + "}";
1184 }
Kweku Adams61e03292017-10-19 14:27:12 -07001185
1186 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1187 final long token = proto.start(fieldId);
1188
1189 proto.write(FilterStatsProto.TAG, mTag);
1190 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1191 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1192 proto.write(FilterStatsProto.COUNT, count);
1193 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1194 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1195 proto.write(FilterStatsProto.NESTING, nesting);
1196
1197 proto.end(token);
1198 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001199 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001200
Adam Lesinski182f73f2013-12-05 16:48:06 -08001201 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001202 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001203 final String mPackageName;
1204
1205 long aggregateTime;
1206 int count;
1207 int numWakeup;
1208 long startTime;
1209 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001210 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001211
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001212 BroadcastStats(int uid, String packageName) {
1213 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001214 mPackageName = packageName;
1215 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001216
1217 @Override
1218 public String toString() {
1219 return "BroadcastStats{"
1220 + "uid=" + mUid
1221 + ", packageName=" + mPackageName
1222 + ", aggregateTime=" + aggregateTime
1223 + ", count=" + count
1224 + ", numWakeup=" + numWakeup
1225 + ", startTime=" + startTime
1226 + ", nesting=" + nesting
1227 + "}";
1228 }
Kweku Adams61e03292017-10-19 14:27:12 -07001229
1230 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1231 final long token = proto.start(fieldId);
1232
1233 proto.write(BroadcastStatsProto.UID, mUid);
1234 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1235 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1236 proto.write(BroadcastStatsProto.COUNT, count);
1237 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1238 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1239 proto.write(BroadcastStatsProto.NESTING, nesting);
1240
1241 proto.end(token);
1242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001244
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001245 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1246 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001247
1248 int mNumDelayedAlarms = 0;
1249 long mTotalDelayTime = 0;
1250 long mMaxDelayTime = 0;
1251
Adam Lesinski182f73f2013-12-05 16:48:06 -08001252 @Override
1253 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001254 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001255 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001256
1257 // We have to set current TimeZone info to kernel
1258 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001259 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001260
Christopher Tate247571462017-04-10 11:45:05 -07001261 // Also sure that we're booting with a halfway sensible current time
1262 if (mNativeData != 0) {
1263 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1264 if (System.currentTimeMillis() < systemBuildTime) {
1265 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1266 + ", advancing to build time " + systemBuildTime);
1267 setKernelTime(mNativeData, systemBuildTime);
1268 }
1269 }
1270
Christopher Tatebb9cce52017-04-18 14:19:43 -07001271 // Determine SysUI's uid
1272 final PackageManager packMan = getContext().getPackageManager();
1273 try {
1274 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1275 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1276 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1277 mSystemUiUid = sysUi.uid;
1278 } else {
1279 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1280 + " defined by non-privileged app " + sysUi.packageName
1281 + " - ignoring");
1282 }
1283 } catch (NameNotFoundException e) {
1284 }
1285
1286 if (mSystemUiUid <= 0) {
1287 Slog.wtf(TAG, "SysUI package not found!");
1288 }
1289
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001291 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001292
Adam Lesinski182f73f2013-12-05 16:48:06 -08001293 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001295 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001296 | Intent.FLAG_RECEIVER_FOREGROUND
1297 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001298 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001299 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001300 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1301 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001302 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001303 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001306 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 mClockReceiver.scheduleTimeTickEvent();
1308 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001309 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001311
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001312 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001313 AlarmThread waitThread = new AlarmThread();
1314 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001316 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001318
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001319 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001320 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001321 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1322 | ActivityManager.UID_OBSERVER_ACTIVE,
1323 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001324 } catch (RemoteException e) {
1325 // ignored; both services live in system_server
1326 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001329
1330 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001331 public void onBootPhase(int phase) {
1332 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1333 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001334 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001335 mLocalDeviceIdleController
1336 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001337 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1338 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001339
1340 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1341 mAppStateTracker.addListener(mForceAppStandbyListener);
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 Onukie4918212018-02-06 11:30:15 -08001730 || ((mAppStateTracker != null)
1731 && mAppStateTracker.isUidPowerSaveWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001732 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1733 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001734 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001735
Christopher Tate14a7bb02015-10-01 10:24:31 -07001736 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1737 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001738 }
Christopher Tate89779822012-08-31 14:40:03 -07001739
Adam Lesinski182f73f2013-12-05 16:48:06 -08001740 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001741 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001742 getContext().enforceCallingOrSelfPermission(
1743 "android.permission.SET_TIME",
1744 "setTime");
1745
Greg Hackmann0cab8962014-02-21 16:35:52 -08001746 if (mNativeData == 0) {
1747 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1748 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001749 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001750
1751 synchronized (mLock) {
1752 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001755
1756 @Override
1757 public void setTimeZone(String tz) {
1758 getContext().enforceCallingOrSelfPermission(
1759 "android.permission.SET_TIME_ZONE",
1760 "setTimeZone");
1761
1762 final long oldId = Binder.clearCallingIdentity();
1763 try {
1764 setTimeZoneImpl(tz);
1765 } finally {
1766 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
1768 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001769
Adam Lesinski182f73f2013-12-05 16:48:06 -08001770 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001771 public void remove(PendingIntent operation, IAlarmListener listener) {
1772 if (operation == null && listener == null) {
1773 Slog.w(TAG, "remove() with no intent or listener");
1774 return;
1775 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001776
Christopher Tate14a7bb02015-10-01 10:24:31 -07001777 synchronized (mLock) {
1778 removeLocked(operation, listener);
1779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001781
Adam Lesinski182f73f2013-12-05 16:48:06 -08001782 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001783 public long getNextWakeFromIdleTime() {
1784 return getNextWakeFromIdleTimeImpl();
1785 }
1786
1787 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001788 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001789 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1790 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1791 "getNextAlarmClock", null);
1792
1793 return getNextAlarmClockImpl(userId);
1794 }
1795
1796 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001797 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001798 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001799
1800 if (args.length > 0 && "--proto".equals(args[0])) {
1801 dumpProto(fd);
1802 } else {
1803 dumpImpl(pw);
1804 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001805 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001806 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001807
Adam Lesinski182f73f2013-12-05 16:48:06 -08001808 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 synchronized (mLock) {
1810 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001811 mConstants.dump(pw);
1812 pw.println();
1813
Makoto Onukie4918212018-02-06 11:30:15 -08001814 if (mAppStateTracker != null) {
1815 mAppStateTracker.dump(pw, " ");
1816 pw.println();
1817 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001818
Suprabh Shukla75edab12018-01-29 14:09:06 -08001819 pw.println(" App Standby Parole: " + mAppStandbyParole);
1820 pw.println();
1821
Christopher Tatee0a22b32013-07-11 14:43:13 -07001822 final long nowRTC = System.currentTimeMillis();
1823 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001824 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001825
Dianne Hackborna750a632015-06-16 17:18:23 -07001826 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001827 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001828 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001829 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001830 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001831 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001832 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1833 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001834 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001835 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1836 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001837 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1838 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001839 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001840 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001841 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001842 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1843 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001844 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001845 pw.print(" Max wakeup delay: ");
1846 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1847 pw.println();
1848 pw.print(" Time since last dispatch: ");
1849 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1850 pw.println();
1851 pw.print(" Next non-wakeup delivery time: ");
1852 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1853 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001854
1855 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1856 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001857 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001858 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001859 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001860 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001861 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1862 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001863 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001864 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1865 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001866 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001867 pw.print(" = "); pw.println(mLastWakeup);
1868 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1869 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001870 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001871
John Spurlock604a5ee2015-06-01 12:27:22 -04001872 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001873 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001874 final TreeSet<Integer> users = new TreeSet<>();
1875 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1876 users.add(mNextAlarmClockForUser.keyAt(i));
1877 }
1878 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1879 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1880 }
1881 for (int user : users) {
1882 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1883 final long time = next != null ? next.getTriggerTime() : 0;
1884 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001885 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001886 pw.print(" pendingSend:"); pw.print(pendingSend);
1887 pw.print(" time:"); pw.print(time);
1888 if (time > 0) {
1889 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1890 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1891 }
1892 pw.println();
1893 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001894 if (mAlarmBatches.size() > 0) {
1895 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001896 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001897 pw.println(mAlarmBatches.size());
1898 for (Batch b : mAlarmBatches) {
1899 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001900 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001901 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001902 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001903 pw.println();
1904 pw.println(" Pending user blocked background alarms: ");
1905 boolean blocked = false;
1906 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1907 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1908 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1909 blocked = true;
1910 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1911 }
1912 }
1913 if (!blocked) {
1914 pw.println(" none");
1915 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001916
Suprabh Shukla75edab12018-01-29 14:09:06 -08001917 pw.println(" mLastAlarmDeliveredForPackage:");
1918 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1919 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1920 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1921 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1922 pw.println();
1923 }
1924 pw.println();
1925
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001926 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001927 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001928 pw.println(" Idle mode state:");
1929 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001930 if (mPendingIdleUntil != null) {
1931 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001932 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001933 } else {
1934 pw.println("null");
1935 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001936 pw.println(" Pending alarms:");
1937 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001938 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001939 if (mNextWakeFromIdle != null) {
1940 pw.println();
1941 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001942 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001943 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001944
1945 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001946 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001947 if (mPendingNonWakeupAlarms.size() > 0) {
1948 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001949 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001950 } else {
1951 pw.println("(none)");
1952 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001953 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001954 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1955 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001956 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001957 pw.print(", max non-interactive time: ");
1958 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1959 pw.println();
1960
1961 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001962 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001963 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1964 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1965 pw.print(" Listener send count: "); pw.println(mListenerCount);
1966 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001967 pw.println();
1968
Christopher Tate7f2a0352015-12-08 10:24:33 -08001969 if (mInFlight.size() > 0) {
1970 pw.println("Outstanding deliveries:");
1971 for (int i = 0; i < mInFlight.size(); i++) {
1972 pw.print(" #"); pw.print(i); pw.print(": ");
1973 pw.println(mInFlight.get(i));
1974 }
1975 pw.println();
1976 }
1977
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001978 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001979 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001980 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08001981 pw.print(" UID ");
1982 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
1983 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001984 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08001985 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
1986 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
1987
1988 final long minInterval = getWhileIdleMinIntervalLocked(uid);
1989 pw.print(" Next allowed:");
1990 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
1991 pw.print(" (");
1992 TimeUtils.formatDuration(minInterval, 0, pw);
1993 pw.print(")");
1994
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001995 pw.println();
1996 }
1997 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08001998
1999 pw.print(" mUseAllowWhileIdleShortTime: [");
2000 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2001 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2002 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2003 pw.print(" ");
2004 }
2005 }
2006 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002007 pw.println();
2008
Dianne Hackborn81038902012-11-26 17:04:09 -08002009 if (mLog.dump(pw, " Recent problems", " ")) {
2010 pw.println();
2011 }
2012
2013 final FilterStats[] topFilters = new FilterStats[10];
2014 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2015 @Override
2016 public int compare(FilterStats lhs, FilterStats rhs) {
2017 if (lhs.aggregateTime < rhs.aggregateTime) {
2018 return 1;
2019 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2020 return -1;
2021 }
2022 return 0;
2023 }
2024 };
2025 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002026 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002027 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2028 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2029 for (int ip=0; ip<uidStats.size(); ip++) {
2030 BroadcastStats bs = uidStats.valueAt(ip);
2031 for (int is=0; is<bs.filterStats.size(); is++) {
2032 FilterStats fs = bs.filterStats.valueAt(is);
2033 int pos = len > 0
2034 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2035 if (pos < 0) {
2036 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002037 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002038 if (pos < topFilters.length) {
2039 int copylen = topFilters.length - pos - 1;
2040 if (copylen > 0) {
2041 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2042 }
2043 topFilters[pos] = fs;
2044 if (len < topFilters.length) {
2045 len++;
2046 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002047 }
2048 }
2049 }
2050 }
2051 if (len > 0) {
2052 pw.println(" Top Alarms:");
2053 for (int i=0; i<len; i++) {
2054 FilterStats fs = topFilters[i];
2055 pw.print(" ");
2056 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2057 TimeUtils.formatDuration(fs.aggregateTime, pw);
2058 pw.print(" running, "); pw.print(fs.numWakeup);
2059 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002060 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2061 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002062 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002063 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002064 pw.println();
2065 }
2066 }
2067
2068 pw.println(" ");
2069 pw.println(" Alarm Stats:");
2070 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002071 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2072 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2073 for (int ip=0; ip<uidStats.size(); ip++) {
2074 BroadcastStats bs = uidStats.valueAt(ip);
2075 pw.print(" ");
2076 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2077 UserHandle.formatUid(pw, bs.mUid);
2078 pw.print(":");
2079 pw.print(bs.mPackageName);
2080 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2081 pw.print(" running, "); pw.print(bs.numWakeup);
2082 pw.println(" wakeups:");
2083 tmpFilters.clear();
2084 for (int is=0; is<bs.filterStats.size(); is++) {
2085 tmpFilters.add(bs.filterStats.valueAt(is));
2086 }
2087 Collections.sort(tmpFilters, comparator);
2088 for (int i=0; i<tmpFilters.size(); i++) {
2089 FilterStats fs = tmpFilters.get(i);
2090 pw.print(" ");
2091 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2092 TimeUtils.formatDuration(fs.aggregateTime, pw);
2093 pw.print(" "); pw.print(fs.numWakeup);
2094 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002095 pw.print(" alarms, last ");
2096 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2097 pw.println(":");
2098 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002099 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002100 pw.println();
2101 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002102 }
2103 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002104 pw.println();
2105 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002106
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002107 if (RECORD_DEVICE_IDLE_ALARMS) {
2108 pw.println();
2109 pw.println(" Allow while idle dispatches:");
2110 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2111 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2112 pw.print(" ");
2113 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2114 pw.print(": ");
2115 UserHandle.formatUid(pw, ent.uid);
2116 pw.print(":");
2117 pw.println(ent.pkg);
2118 if (ent.op != null) {
2119 pw.print(" ");
2120 pw.print(ent.op);
2121 pw.print(" / ");
2122 pw.print(ent.tag);
2123 if (ent.argRealtime != 0) {
2124 pw.print(" (");
2125 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2126 pw.print(")");
2127 }
2128 pw.println();
2129 }
2130 }
2131 }
2132
Christopher Tate18a75f12013-07-01 18:18:59 -07002133 if (WAKEUP_STATS) {
2134 pw.println();
2135 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002136 long last = -1;
2137 for (WakeupEvent event : mRecentWakeups) {
2138 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2139 pw.print('|');
2140 if (last < 0) {
2141 pw.print('0');
2142 } else {
2143 pw.print(event.when - last);
2144 }
2145 last = event.when;
2146 pw.print('|'); pw.print(event.uid);
2147 pw.print('|'); pw.print(event.action);
2148 pw.println();
2149 }
2150 pw.println();
2151 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 }
2153 }
2154
Kweku Adams61e03292017-10-19 14:27:12 -07002155 void dumpProto(FileDescriptor fd) {
2156 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2157
2158 synchronized (mLock) {
2159 final long nowRTC = System.currentTimeMillis();
2160 final long nowElapsed = SystemClock.elapsedRealtime();
2161 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
2162 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
2163 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
2164 mLastTimeChangeClockTime);
2165 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2166 mLastTimeChangeRealtime);
2167
2168 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2169
Makoto Onukie4918212018-02-06 11:30:15 -08002170 if (mAppStateTracker != null) {
2171 mAppStateTracker.dumpProto(proto,
2172 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
2173 }
Kweku Adams61e03292017-10-19 14:27:12 -07002174
2175 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2176 if (!mInteractive) {
2177 // Durations
2178 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2179 nowElapsed - mNonInteractiveStartTime);
2180 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2181 currentNonWakeupFuzzLocked(nowElapsed));
2182 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2183 nowElapsed - mLastAlarmDeliveryTime);
2184 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2185 nowElapsed - mNextNonWakeupDeliveryTime);
2186 }
2187
2188 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2189 mNextNonWakeup - nowElapsed);
2190 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2191 mNextWakeup - nowElapsed);
2192 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2193 nowElapsed - mLastWakeup);
2194 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2195 nowElapsed - mLastWakeupSet);
2196 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002197
2198 final TreeSet<Integer> users = new TreeSet<>();
2199 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2200 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2201 users.add(mNextAlarmClockForUser.keyAt(i));
2202 }
2203 final int pendingSendNextAlarmClockChangedForUserSize =
2204 mPendingSendNextAlarmClockChangedForUser.size();
2205 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2206 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2207 }
2208 for (int user : users) {
2209 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2210 final long time = next != null ? next.getTriggerTime() : 0;
2211 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2212 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2213 proto.write(AlarmClockMetadataProto.USER, user);
2214 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2215 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2216 proto.end(aToken);
2217 }
2218 for (Batch b : mAlarmBatches) {
2219 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2220 nowElapsed, nowRTC);
2221 }
2222 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2223 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2224 if (blockedAlarms != null) {
2225 for (Alarm a : blockedAlarms) {
2226 a.writeToProto(proto,
2227 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2228 nowElapsed, nowRTC);
2229 }
2230 }
2231 }
2232 if (mPendingIdleUntil != null) {
2233 mPendingIdleUntil.writeToProto(
2234 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2235 }
2236 for (Alarm a : mPendingWhileIdleAlarms) {
2237 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2238 nowElapsed, nowRTC);
2239 }
2240 if (mNextWakeFromIdle != null) {
2241 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2242 nowElapsed, nowRTC);
2243 }
2244
2245 for (Alarm a : mPendingNonWakeupAlarms) {
2246 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2247 nowElapsed, nowRTC);
2248 }
2249
2250 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2251 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2252 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2253 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2254 mNonInteractiveTime);
2255
2256 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2257 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2258 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2259 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2260 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2261
2262 for (InFlight f : mInFlight) {
2263 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2264 }
2265
Kweku Adams61e03292017-10-19 14:27:12 -07002266 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2267 final long token = proto.start(
2268 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002269 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2270 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2271
2272 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID, uid);
2273 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2274 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
2275 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002276 proto.end(token);
2277 }
2278
Makoto Onukiadb50d82018-01-29 16:20:30 -08002279 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2280 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2281 proto.write(AlarmManagerServiceProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
2282 mUseAllowWhileIdleShortTime.keyAt(i));
2283 }
2284 }
2285
Kweku Adams61e03292017-10-19 14:27:12 -07002286 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2287
2288 final FilterStats[] topFilters = new FilterStats[10];
2289 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2290 @Override
2291 public int compare(FilterStats lhs, FilterStats rhs) {
2292 if (lhs.aggregateTime < rhs.aggregateTime) {
2293 return 1;
2294 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2295 return -1;
2296 }
2297 return 0;
2298 }
2299 };
2300 int len = 0;
2301 // Get the top 10 FilterStats, ordered by aggregateTime.
2302 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2303 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2304 for (int ip = 0; ip < uidStats.size(); ++ip) {
2305 BroadcastStats bs = uidStats.valueAt(ip);
2306 for (int is = 0; is < bs.filterStats.size(); ++is) {
2307 FilterStats fs = bs.filterStats.valueAt(is);
2308 int pos = len > 0
2309 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2310 if (pos < 0) {
2311 pos = -pos - 1;
2312 }
2313 if (pos < topFilters.length) {
2314 int copylen = topFilters.length - pos - 1;
2315 if (copylen > 0) {
2316 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2317 }
2318 topFilters[pos] = fs;
2319 if (len < topFilters.length) {
2320 len++;
2321 }
2322 }
2323 }
2324 }
2325 }
2326 for (int i = 0; i < len; ++i) {
2327 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2328 FilterStats fs = topFilters[i];
2329
2330 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2331 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2332 fs.mBroadcastStats.mPackageName);
2333 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2334
2335 proto.end(token);
2336 }
2337
2338 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2339 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2340 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2341 for (int ip = 0; ip < uidStats.size(); ++ip) {
2342 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2343
2344 BroadcastStats bs = uidStats.valueAt(ip);
2345 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2346
2347 // uidStats is an ArrayMap, which we can't sort.
2348 tmpFilters.clear();
2349 for (int is = 0; is < bs.filterStats.size(); ++is) {
2350 tmpFilters.add(bs.filterStats.valueAt(is));
2351 }
2352 Collections.sort(tmpFilters, comparator);
2353 for (FilterStats fs : tmpFilters) {
2354 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2355 }
2356
2357 proto.end(token);
2358 }
2359 }
2360
2361 if (RECORD_DEVICE_IDLE_ALARMS) {
2362 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2363 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2364 final long token = proto.start(
2365 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2366
2367 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2368 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2369 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2370 proto.write(IdleDispatchEntryProto.OP, ent.op);
2371 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2372 ent.elapsedRealtime);
2373 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2374
2375 proto.end(token);
2376 }
2377 }
2378
2379 if (WAKEUP_STATS) {
2380 for (WakeupEvent event : mRecentWakeups) {
2381 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2382 proto.write(WakeupEventProto.UID, event.uid);
2383 proto.write(WakeupEventProto.ACTION, event.action);
2384 proto.write(WakeupEventProto.WHEN, event.when);
2385 proto.end(token);
2386 }
2387 }
2388 }
2389
2390 proto.flush();
2391 }
2392
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002393 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002394 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2395 PrintWriter pw = new PrintWriter(bs);
2396 final long nowRTC = System.currentTimeMillis();
2397 final long nowELAPSED = SystemClock.elapsedRealtime();
2398 final int NZ = mAlarmBatches.size();
2399 for (int iz = 0; iz < NZ; iz++) {
2400 Batch bz = mAlarmBatches.get(iz);
2401 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002402 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002403 pw.flush();
2404 Slog.v(TAG, bs.toString());
2405 bs.reset();
2406 }
2407 }
2408
2409 private boolean validateConsistencyLocked() {
2410 if (DEBUG_VALIDATE) {
2411 long lastTime = Long.MIN_VALUE;
2412 final int N = mAlarmBatches.size();
2413 for (int i = 0; i < N; i++) {
2414 Batch b = mAlarmBatches.get(i);
2415 if (b.start >= lastTime) {
2416 // duplicate start times are okay because of standalone batches
2417 lastTime = b.start;
2418 } else {
2419 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002420 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2421 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002422 return false;
2423 }
2424 }
2425 }
2426 return true;
2427 }
2428
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002429 private Batch findFirstWakeupBatchLocked() {
2430 final int N = mAlarmBatches.size();
2431 for (int i = 0; i < N; i++) {
2432 Batch b = mAlarmBatches.get(i);
2433 if (b.hasWakeups()) {
2434 return b;
2435 }
2436 }
2437 return null;
2438 }
2439
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002440 long getNextWakeFromIdleTimeImpl() {
2441 synchronized (mLock) {
2442 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2443 }
2444 }
2445
2446 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002447 synchronized (mLock) {
2448 return mNextAlarmClockForUser.get(userId);
2449 }
2450 }
2451
2452 /**
2453 * Recomputes the next alarm clock for all users.
2454 */
2455 private void updateNextAlarmClockLocked() {
2456 if (!mNextAlarmClockMayChange) {
2457 return;
2458 }
2459 mNextAlarmClockMayChange = false;
2460
Jose Lima235510e2014-08-13 12:50:01 -07002461 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002462 nextForUser.clear();
2463
2464 final int N = mAlarmBatches.size();
2465 for (int i = 0; i < N; i++) {
2466 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2467 final int M = alarms.size();
2468
2469 for (int j = 0; j < M; j++) {
2470 Alarm a = alarms.get(j);
2471 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002472 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002473 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002474
2475 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002476 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002477 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002478 " for user " + userId);
2479 }
2480
2481 // Alarms and batches are sorted by time, no need to compare times here.
2482 if (nextForUser.get(userId) == null) {
2483 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002484 } else if (a.alarmClock.equals(current)
2485 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2486 // same/earlier time and it's the one we cited before, so stick with it
2487 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002488 }
2489 }
2490 }
2491 }
2492
2493 // Update mNextAlarmForUser with new values.
2494 final int NN = nextForUser.size();
2495 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002496 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002497 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002498 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002499 if (!newAlarm.equals(currentAlarm)) {
2500 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2501 }
2502 }
2503
2504 // Remove users without any alarm clocks scheduled.
2505 final int NNN = mNextAlarmClockForUser.size();
2506 for (int i = NNN - 1; i >= 0; i--) {
2507 int userId = mNextAlarmClockForUser.keyAt(i);
2508 if (nextForUser.get(userId) == null) {
2509 updateNextAlarmInfoForUserLocked(userId, null);
2510 }
2511 }
2512 }
2513
Jose Lima235510e2014-08-13 12:50:01 -07002514 private void updateNextAlarmInfoForUserLocked(int userId,
2515 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002516 if (alarmClock != null) {
2517 if (DEBUG_ALARM_CLOCK) {
2518 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002519 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002520 }
2521 mNextAlarmClockForUser.put(userId, alarmClock);
2522 } else {
2523 if (DEBUG_ALARM_CLOCK) {
2524 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2525 }
2526 mNextAlarmClockForUser.remove(userId);
2527 }
2528
2529 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2530 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2531 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2532 }
2533
2534 /**
2535 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2536 * for which alarm clocks have changed since the last call to this.
2537 *
2538 * Do not call with a lock held. Only call from mHandler's thread.
2539 *
2540 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2541 */
2542 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002543 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002544 pendingUsers.clear();
2545
2546 synchronized (mLock) {
2547 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2548 for (int i = 0; i < N; i++) {
2549 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2550 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2551 }
2552 mPendingSendNextAlarmClockChangedForUser.clear();
2553 }
2554
2555 final int N = pendingUsers.size();
2556 for (int i = 0; i < N; i++) {
2557 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002558 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002559 Settings.System.putStringForUser(getContext().getContentResolver(),
2560 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002561 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002562 userId);
2563
2564 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2565 new UserHandle(userId));
2566 }
2567 }
2568
2569 /**
2570 * Formats an alarm like platform/packages/apps/DeskClock used to.
2571 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002572 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2573 int userId) {
2574 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002575 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2576 return (info == null) ? "" :
2577 DateFormat.format(pattern, info.getTriggerTime()).toString();
2578 }
2579
Adam Lesinski182f73f2013-12-05 16:48:06 -08002580 void rescheduleKernelAlarmsLocked() {
2581 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2582 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002583 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002584 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002585 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002586 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002587 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002588 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002589 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002590 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002591 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002592 if (firstBatch != firstWakeup) {
2593 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002594 }
2595 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002596 if (mPendingNonWakeupAlarms.size() > 0) {
2597 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2598 nextNonWakeup = mNextNonWakeupDeliveryTime;
2599 }
2600 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002601 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002602 mNextNonWakeup = nextNonWakeup;
2603 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2604 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002605 }
2606
Christopher Tate14a7bb02015-10-01 10:24:31 -07002607 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002608 if (operation == null && directReceiver == null) {
2609 if (localLOGV) {
2610 Slog.w(TAG, "requested remove() of null operation",
2611 new RuntimeException("here"));
2612 }
2613 return;
2614 }
2615
Adam Lesinski182f73f2013-12-05 16:48:06 -08002616 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002617 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002618 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2619 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002620 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002621 if (b.size() == 0) {
2622 mAlarmBatches.remove(i);
2623 }
2624 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002625 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002626 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002627 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2628 mPendingWhileIdleAlarms.remove(i);
2629 }
2630 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002631 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2632 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2633 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2634 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2635 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2636 alarmsForUid.remove(j);
2637 }
2638 }
2639 if (alarmsForUid.size() == 0) {
2640 mPendingBackgroundAlarms.removeAt(i);
2641 }
2642 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002643 if (didRemove) {
2644 if (DEBUG_BATCH) {
2645 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2646 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002647 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002648 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002649 mPendingIdleUntil = null;
2650 restorePending = true;
2651 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002652 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002653 mNextWakeFromIdle = null;
2654 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002655 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002656 if (restorePending) {
2657 restorePendingWhileIdleAlarmsLocked();
2658 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002659 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002660 }
2661 }
2662
Christopher Tate1d99c392017-12-07 16:54:04 -08002663 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002664 if (uid == Process.SYSTEM_UID) {
2665 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2666 return;
2667 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002668 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002669 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002670 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2671 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002672 didRemove |= b.remove(whichAlarms);
2673 if (b.size() == 0) {
2674 mAlarmBatches.remove(i);
2675 }
2676 }
2677 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2678 final Alarm a = mPendingWhileIdleAlarms.get(i);
2679 if (a.uid == uid) {
2680 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2681 mPendingWhileIdleAlarms.remove(i);
2682 }
2683 }
2684 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2685 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2686 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2687 if (alarmsForUid.get(j).uid == uid) {
2688 alarmsForUid.remove(j);
2689 }
2690 }
2691 if (alarmsForUid.size() == 0) {
2692 mPendingBackgroundAlarms.removeAt(i);
2693 }
2694 }
2695 if (didRemove) {
2696 if (DEBUG_BATCH) {
2697 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2698 }
2699 rebatchAllAlarmsLocked(true);
2700 rescheduleKernelAlarmsLocked();
2701 updateNextAlarmClockLocked();
2702 }
2703 }
2704
2705 void removeLocked(final String packageName) {
2706 if (packageName == null) {
2707 if (localLOGV) {
2708 Slog.w(TAG, "requested remove() of null packageName",
2709 new RuntimeException("here"));
2710 }
2711 return;
2712 }
2713
2714 boolean didRemove = false;
2715 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002716 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002717 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2718 Batch b = mAlarmBatches.get(i);
2719 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002720 if (b.size() == 0) {
2721 mAlarmBatches.remove(i);
2722 }
2723 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002724 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2725 if (oldHasTick != newHasTick) {
2726 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2727 }
2728
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002729 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002730 final Alarm a = mPendingWhileIdleAlarms.get(i);
2731 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002732 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2733 mPendingWhileIdleAlarms.remove(i);
2734 }
2735 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002736 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2737 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2738 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2739 if (alarmsForUid.get(j).matches(packageName)) {
2740 alarmsForUid.remove(j);
2741 }
2742 }
2743 if (alarmsForUid.size() == 0) {
2744 mPendingBackgroundAlarms.removeAt(i);
2745 }
2746 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002747 if (didRemove) {
2748 if (DEBUG_BATCH) {
2749 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2750 }
2751 rebatchAllAlarmsLocked(true);
2752 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002753 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002754 }
2755 }
2756
Christopher Tate1d99c392017-12-07 16:54:04 -08002757 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002758 if (uid == Process.SYSTEM_UID) {
2759 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2760 return;
2761 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002762 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002763 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2764 try {
2765 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2766 uid, a.packageName)) {
2767 return true;
2768 }
2769 } catch (RemoteException e) { /* fall through */}
2770 return false;
2771 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002772 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2773 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002774 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002775 if (b.size() == 0) {
2776 mAlarmBatches.remove(i);
2777 }
2778 }
2779 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2780 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002781 if (a.uid == uid) {
2782 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2783 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002784 }
2785 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002786 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2787 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2788 mPendingBackgroundAlarms.removeAt(i);
2789 }
2790 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002791 if (didRemove) {
2792 if (DEBUG_BATCH) {
2793 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2794 }
2795 rebatchAllAlarmsLocked(true);
2796 rescheduleKernelAlarmsLocked();
2797 updateNextAlarmClockLocked();
2798 }
2799 }
2800
Adam Lesinski182f73f2013-12-05 16:48:06 -08002801 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002802 if (userHandle == UserHandle.USER_SYSTEM) {
2803 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2804 return;
2805 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002806 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002807 final Predicate<Alarm> whichAlarms =
2808 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002809 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2810 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002811 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002812 if (b.size() == 0) {
2813 mAlarmBatches.remove(i);
2814 }
2815 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002816 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002817 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002818 == userHandle) {
2819 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2820 mPendingWhileIdleAlarms.remove(i);
2821 }
2822 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002823 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2824 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2825 mPendingBackgroundAlarms.removeAt(i);
2826 }
2827 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002828 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2829 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2830 mLastAllowWhileIdleDispatch.removeAt(i);
2831 }
2832 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002833
2834 if (didRemove) {
2835 if (DEBUG_BATCH) {
2836 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2837 }
2838 rebatchAllAlarmsLocked(true);
2839 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002840 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002841 }
2842 }
2843
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002844 void interactiveStateChangedLocked(boolean interactive) {
2845 if (mInteractive != interactive) {
2846 mInteractive = interactive;
2847 final long nowELAPSED = SystemClock.elapsedRealtime();
2848 if (interactive) {
2849 if (mPendingNonWakeupAlarms.size() > 0) {
2850 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2851 mTotalDelayTime += thisDelayTime;
2852 if (mMaxDelayTime < thisDelayTime) {
2853 mMaxDelayTime = thisDelayTime;
2854 }
2855 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2856 mPendingNonWakeupAlarms.clear();
2857 }
2858 if (mNonInteractiveStartTime > 0) {
2859 long dur = nowELAPSED - mNonInteractiveStartTime;
2860 if (dur > mNonInteractiveTime) {
2861 mNonInteractiveTime = dur;
2862 }
2863 }
2864 } else {
2865 mNonInteractiveStartTime = nowELAPSED;
2866 }
2867 }
2868 }
2869
Adam Lesinski182f73f2013-12-05 16:48:06 -08002870 boolean lookForPackageLocked(String packageName) {
2871 for (int i = 0; i < mAlarmBatches.size(); i++) {
2872 Batch b = mAlarmBatches.get(i);
2873 if (b.hasPackage(packageName)) {
2874 return true;
2875 }
2876 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002877 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002878 final Alarm a = mPendingWhileIdleAlarms.get(i);
2879 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002880 return true;
2881 }
2882 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002883 return false;
2884 }
2885
2886 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002887 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002888 // The kernel never triggers alarms with negative wakeup times
2889 // so we ensure they are positive.
2890 long alarmSeconds, alarmNanoseconds;
2891 if (when < 0) {
2892 alarmSeconds = 0;
2893 alarmNanoseconds = 0;
2894 } else {
2895 alarmSeconds = when / 1000;
2896 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2897 }
Kweku Adams61e03292017-10-19 14:27:12 -07002898
Christopher Tate8b98ade2018-02-09 11:13:19 -08002899 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2900 if (result != 0) {
2901 final long nowElapsed = SystemClock.elapsedRealtime();
2902 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2903 + " type=" + type + " when=" + when
2904 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2905 + "), ret = " + result + " = " + Os.strerror(result));
2906 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002907 } else {
2908 Message msg = Message.obtain();
2909 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002910
Adam Lesinski182f73f2013-12-05 16:48:06 -08002911 mHandler.removeMessages(ALARM_EVENT);
2912 mHandler.sendMessageAtTime(msg, when);
2913 }
2914 }
2915
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002916 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002917 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918 for (int i=list.size()-1; i>=0; i--) {
2919 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002920 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2921 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002922 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002923 }
2924 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002925
2926 private static final String labelForType(int type) {
2927 switch (type) {
2928 case RTC: return "RTC";
2929 case RTC_WAKEUP : return "RTC_WAKEUP";
2930 case ELAPSED_REALTIME : return "ELAPSED";
2931 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002932 }
2933 return "--unknown--";
2934 }
2935
2936 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002937 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002938 for (int i=list.size()-1; i>=0; i--) {
2939 Alarm a = list.get(i);
2940 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002941 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2942 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002943 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002944 }
2945 }
2946
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002947 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002948 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002949 if (alarm.alarmClock != null) {
2950 // Don't block alarm clocks
2951 return false;
2952 }
2953 if (alarm.operation != null
2954 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2955 // Don't block starting foreground components
2956 return false;
2957 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002958 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002959 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08002960 return (mAppStateTracker != null) &&
2961 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage, allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002962 }
2963
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002964 private native long init();
2965 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002966 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002967 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002968 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002969 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970
Makoto Onukiadb50d82018-01-29 16:20:30 -08002971 private long getWhileIdleMinIntervalLocked(int uid) {
2972 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08002973 final boolean ebs = (mAppStateTracker != null)
2974 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08002975 if (!dozing && !ebs) {
2976 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2977 }
2978 if (dozing) {
2979 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2980 }
2981 if (mUseAllowWhileIdleShortTime.get(uid)) {
2982 // if the last allow-while-idle went off while uid was fg, or the uid
2983 // recently came into fg, don't block the alarm for long.
2984 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2985 }
2986 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2987 }
2988
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002989 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002990 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002991 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002992 // batches are temporally sorted, so we need only pull from the
2993 // start of the list until we either empty it or hit a batch
2994 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002995 while (mAlarmBatches.size() > 0) {
2996 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002997 if (batch.start > nowELAPSED) {
2998 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999 break;
3000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001
Christopher Tatee0a22b32013-07-11 14:43:13 -07003002 // We will (re)schedule some alarms now; don't let that interfere
3003 // with delivery of this current batch
3004 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003005
Christopher Tatee0a22b32013-07-11 14:43:13 -07003006 final int N = batch.size();
3007 for (int i = 0; i < N; i++) {
3008 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003009
3010 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3011 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
3012 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003013 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003014 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003015 if (nowELAPSED < minTime) {
3016 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3017 // alarm went off for this app. Reschedule the alarm to be in the
3018 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003019 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003020 if (alarm.maxWhenElapsed < minTime) {
3021 alarm.maxWhenElapsed = minTime;
3022 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003023 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003024 if (RECORD_DEVICE_IDLE_ALARMS) {
3025 IdleDispatchEntry ent = new IdleDispatchEntry();
3026 ent.uid = alarm.uid;
3027 ent.pkg = alarm.operation.getCreatorPackage();
3028 ent.tag = alarm.operation.getTag("");
3029 ent.op = "RESCHEDULE";
3030 ent.elapsedRealtime = nowELAPSED;
3031 ent.argRealtime = lastTime;
3032 mAllowWhileIdleDispatches.add(ent);
3033 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003034 setImplLocked(alarm, true, false);
3035 continue;
3036 }
3037 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003038 if (isBackgroundRestricted(alarm)) {
3039 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3040 if (DEBUG_BG_LIMIT) {
3041 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3042 }
3043 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3044 if (alarmsForUid == null) {
3045 alarmsForUid = new ArrayList<>();
3046 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3047 }
3048 alarmsForUid.add(alarm);
3049 continue;
3050 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003051
Christopher Tatee0a22b32013-07-11 14:43:13 -07003052 alarm.count = 1;
3053 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003054 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3055 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003056 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003057 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003058 if (mPendingIdleUntil == alarm) {
3059 mPendingIdleUntil = null;
3060 rebatchAllAlarmsLocked(false);
3061 restorePendingWhileIdleAlarmsLocked();
3062 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003063 if (mNextWakeFromIdle == alarm) {
3064 mNextWakeFromIdle = null;
3065 rebatchAllAlarmsLocked(false);
3066 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003067
3068 // Recurring alarms may have passed several alarm intervals while the
3069 // phone was asleep or off, so pass a trigger count when sending them.
3070 if (alarm.repeatInterval > 0) {
3071 // this adjustment will be zero if we're late by
3072 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003073 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003074
3075 // Also schedule its next recurrence
3076 final long delta = alarm.count * alarm.repeatInterval;
3077 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003078 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003079 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003080 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3081 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003082 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003083
Christopher Tate864d42e2014-12-02 11:48:53 -08003084 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003085 hasWakeup = true;
3086 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003087
3088 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3089 if (alarm.alarmClock != null) {
3090 mNextAlarmClockMayChange = true;
3091 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003093 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003094
Christopher Tate1590f1e2014-10-02 17:27:57 -07003095 // This is a new alarm delivery set; bump the sequence number to indicate that
3096 // all apps' alarm delivery classes should be recalculated.
3097 mCurrentSeq++;
3098 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003099 Collections.sort(triggerList, mAlarmDispatchComparator);
3100
3101 if (localLOGV) {
3102 for (int i=0; i<triggerList.size(); i++) {
3103 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3104 }
3105 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003106
3107 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003109
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 /**
3111 * This Comparator sorts Alarms into increasing time order.
3112 */
3113 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3114 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003115 long when1 = a1.whenElapsed;
3116 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003117 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003118 return 1;
3119 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003120 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 return -1;
3122 }
3123 return 0;
3124 }
3125 }
Kweku Adams61e03292017-10-19 14:27:12 -07003126
Makoto Onuki2206af32017-11-21 16:25:35 -08003127 @VisibleForTesting
3128 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003129 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003130 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003131 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003132 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003133 public final IAlarmListener listener;
3134 public final String listenerTag;
3135 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003136 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003137 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003138 public final AlarmManager.AlarmClockInfo alarmClock;
3139 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003140 public final int creatorUid;
3141 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003142 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 public int count;
3144 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003145 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003146 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003147 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003148 // Expected alarm expiry time before app standby deferring is applied.
3149 public long expectedWhenElapsed;
3150 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003152 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003153
Christopher Tate3e04b472013-10-21 17:51:31 -07003154 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003155 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3156 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3157 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003158 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003159 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003160 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3161 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003162 when = _when;
3163 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003164 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003165 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003166 maxWhenElapsed = _maxWhen;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003167 expectedMaxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003168 repeatInterval = _interval;
3169 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003170 listener = _rec;
3171 listenerTag = _listenerTag;
3172 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003173 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003174 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003175 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003176 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003177 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003178 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003179 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003181
Christopher Tate14a7bb02015-10-01 10:24:31 -07003182 public static String makeTag(PendingIntent pi, String tag, int type) {
3183 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3184 ? "*walarm*:" : "*alarm*:";
3185 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3186 }
3187
3188 public WakeupEvent makeWakeupEvent(long nowRTC) {
3189 return new WakeupEvent(nowRTC, creatorUid,
3190 (operation != null)
3191 ? operation.getIntent().getAction()
3192 : ("<listener>:" + listenerTag));
3193 }
3194
3195 // Returns true if either matches
3196 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3197 return (operation != null)
3198 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003199 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003200 }
3201
3202 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003203 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003204 }
3205
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003206 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003207 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003208 StringBuilder sb = new StringBuilder(128);
3209 sb.append("Alarm{");
3210 sb.append(Integer.toHexString(System.identityHashCode(this)));
3211 sb.append(" type ");
3212 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003213 sb.append(" when ");
3214 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003215 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003216 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003217 sb.append('}');
3218 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003219 }
3220
Kweku Adams61e03292017-10-19 14:27:12 -07003221 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003222 SimpleDateFormat sdf) {
3223 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003224 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003225 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003226 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3227 expectedWhenElapsed, nowELAPSED, pw);
3228 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3229 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003230 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3231 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003232 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3233 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003234 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003235 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003236 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003237 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003238 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003239 }
3240 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003241 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003242 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003243 pw.print(" count="); pw.print(count);
3244 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003245 if (alarmClock != null) {
3246 pw.print(prefix); pw.println("Alarm clock:");
3247 pw.print(prefix); pw.print(" triggerTime=");
3248 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3249 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3250 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003251 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003252 if (listener != null) {
3253 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
Kweku Adams61e03292017-10-19 14:27:12 -07003256
3257 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3258 long nowRTC) {
3259 final long token = proto.start(fieldId);
3260
3261 proto.write(AlarmProto.TAG, statsTag);
3262 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003263 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003264 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3265 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3266 proto.write(AlarmProto.COUNT, count);
3267 proto.write(AlarmProto.FLAGS, flags);
3268 if (alarmClock != null) {
3269 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3270 }
3271 if (operation != null) {
3272 operation.writeToProto(proto, AlarmProto.OPERATION);
3273 }
3274 if (listener != null) {
3275 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3276 }
3277
3278 proto.end(token);
3279 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003281
Christopher Tatee0a22b32013-07-11 14:43:13 -07003282 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3283 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003284 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3285 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003286 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003287 break;
3288 }
3289
Christopher Tatee0a22b32013-07-11 14:43:13 -07003290 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003291 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3292 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003293 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003294 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003295 }
3296 }
3297
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003298 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3299 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3300 if (timeSinceOn < 5*60*1000) {
3301 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3302 return 2*60*1000;
3303 } else if (timeSinceOn < 30*60*1000) {
3304 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3305 return 15*60*1000;
3306 } else {
3307 // Otherwise, we will delay by at most an hour.
3308 return 60*60*1000;
3309 }
3310 }
3311
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003312 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003313 if (duration < 15*60*1000) {
3314 // If the duration until the time is less than 15 minutes, the maximum fuzz
3315 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003316 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003317 } else if (duration < 90*60*1000) {
3318 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3319 return 15*60*1000;
3320 } else {
3321 // Otherwise, we will fuzz by at most half an hour.
3322 return 30*60*1000;
3323 }
3324 }
3325
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003326 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3327 if (mInteractive) {
3328 return false;
3329 }
3330 if (mLastAlarmDeliveryTime <= 0) {
3331 return false;
3332 }
minho.choo649acab2014-12-12 16:13:55 +09003333 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003334 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3335 // and the next delivery time is in the past, then just deliver them all. This
3336 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3337 return false;
3338 }
3339 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3340 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3341 }
3342
3343 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3344 mLastAlarmDeliveryTime = nowELAPSED;
3345 for (int i=0; i<triggerList.size(); i++) {
3346 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003347 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003348 if (alarm.wakeup) {
3349 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3350 } else {
3351 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3352 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003353 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003354 if (localLOGV) {
3355 Slog.v(TAG, "sending alarm " + alarm);
3356 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003357 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003358 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3359 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003360 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003361 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003362 } catch (RuntimeException e) {
3363 Slog.w(TAG, "Failure sending alarm.", e);
3364 }
Tim Murray175c0f92017-11-28 15:01:04 -08003365 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003366 }
3367 }
3368
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003369 private boolean isExemptFromAppStandby(Alarm a) {
3370 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3371 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3372 }
3373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 private class AlarmThread extends Thread
3375 {
3376 public AlarmThread()
3377 {
3378 super("AlarmManager");
3379 }
Kweku Adams61e03292017-10-19 14:27:12 -07003380
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003381 public void run()
3382 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003383 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3384
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003385 while (true)
3386 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003387 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003388
Dianne Hackbornc3527222015-05-13 14:03:20 -07003389 final long nowRTC = System.currentTimeMillis();
3390 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003391 synchronized (mLock) {
3392 mLastWakeup = nowELAPSED;
3393 }
3394
3395 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003396
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003397 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003398 // The kernel can give us spurious time change notifications due to
3399 // small adjustments it makes internally; we want to filter those out.
3400 final long lastTimeChangeClockTime;
3401 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003402 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003403 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3404 expectedClockTime = lastTimeChangeClockTime
3405 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003406 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003407 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3408 || nowRTC > (expectedClockTime+1000)) {
3409 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003410 // let's do it!
3411 if (DEBUG_BATCH) {
3412 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3413 }
3414 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003415 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003416 rebatchAllAlarms();
3417 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003418 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003419 synchronized (mLock) {
3420 mNumTimeChanged++;
3421 mLastTimeChangeClockTime = nowRTC;
3422 mLastTimeChangeRealtime = nowELAPSED;
3423 }
3424 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3425 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003426 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003427 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3428 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003429 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3430
3431 // The world has changed on us, so we need to re-evaluate alarms
3432 // regardless of whether the kernel has told us one went off.
3433 result |= IS_WAKEUP_MASK;
3434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003436
Dianne Hackbornc3527222015-05-13 14:03:20 -07003437 if (result != TIME_CHANGED_MASK) {
3438 // If this was anything besides just a time change, then figure what if
3439 // anything to do about alarms.
3440 synchronized (mLock) {
3441 if (localLOGV) Slog.v(
3442 TAG, "Checking for alarms... rtc=" + nowRTC
3443 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003444
Dianne Hackbornc3527222015-05-13 14:03:20 -07003445 if (WAKEUP_STATS) {
3446 if ((result & IS_WAKEUP_MASK) != 0) {
3447 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3448 int n = 0;
3449 for (WakeupEvent event : mRecentWakeups) {
3450 if (event.when > newEarliest) break;
3451 n++; // number of now-stale entries at the list head
3452 }
3453 for (int i = 0; i < n; i++) {
3454 mRecentWakeups.remove();
3455 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003456
Dianne Hackbornc3527222015-05-13 14:03:20 -07003457 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003458 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003459 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003460
Christopher Tate8b98ade2018-02-09 11:13:19 -08003461 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003462 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3463 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3464 // if there are no wakeup alarms and the screen is off, we can
3465 // delay what we have so far until the future.
3466 if (mPendingNonWakeupAlarms.size() == 0) {
3467 mStartCurrentDelayTime = nowELAPSED;
3468 mNextNonWakeupDeliveryTime = nowELAPSED
3469 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3470 }
3471 mPendingNonWakeupAlarms.addAll(triggerList);
3472 mNumDelayedAlarms += triggerList.size();
3473 rescheduleKernelAlarmsLocked();
3474 updateNextAlarmClockLocked();
3475 } else {
3476 // now deliver the alarm intents; if there are pending non-wakeup
3477 // alarms, we need to merge them in to the list. note we don't
3478 // just deliver them first because we generally want non-wakeup
3479 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003480 if (mPendingNonWakeupAlarms.size() > 0) {
3481 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3482 triggerList.addAll(mPendingNonWakeupAlarms);
3483 Collections.sort(triggerList, mAlarmDispatchComparator);
3484 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3485 mTotalDelayTime += thisDelayTime;
3486 if (mMaxDelayTime < thisDelayTime) {
3487 mMaxDelayTime = thisDelayTime;
3488 }
3489 mPendingNonWakeupAlarms.clear();
3490 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003491 final ArraySet<Pair<String, Integer>> triggerPackages =
3492 new ArraySet<>();
3493 for (int i = 0; i < triggerList.size(); i++) {
3494 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003495 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003496 triggerPackages.add(Pair.create(
3497 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003498 }
3499 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003500 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003501 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3502 rescheduleKernelAlarmsLocked();
3503 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003505 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003506
3507 } else {
3508 // Just in case -- even though no wakeup flag was set, make sure
3509 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003510 synchronized (mLock) {
3511 rescheduleKernelAlarmsLocked();
3512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003513 }
3514 }
3515 }
3516 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003517
David Christieebe51fc2013-07-26 13:23:29 -07003518 /**
3519 * Attribute blame for a WakeLock.
3520 * @param pi PendingIntent to attribute blame to if ws is null.
3521 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003522 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003523 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003524 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003525 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003526 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003527 final boolean unimportant = pi == mTimeTickSender;
3528 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003529 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003530 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003531 } else {
3532 mWakeLock.setHistoryTag(null);
3533 }
3534 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003535 if (ws != null) {
3536 mWakeLock.setWorkSource(ws);
3537 return;
3538 }
3539
Christopher Tate14a7bb02015-10-01 10:24:31 -07003540 final int uid = (knownUid >= 0)
3541 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003542 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003543 if (uid >= 0) {
3544 mWakeLock.setWorkSource(new WorkSource(uid));
3545 return;
3546 }
3547 } catch (Exception e) {
3548 }
3549
3550 // Something went wrong; fall back to attributing the lock to the OS
3551 mWakeLock.setWorkSource(null);
3552 }
3553
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003554 private class AlarmHandler extends Handler {
3555 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003556 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3557 public static final int LISTENER_TIMEOUT = 3;
3558 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003559 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3560 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003561 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 public AlarmHandler() {
3564 }
Kweku Adams61e03292017-10-19 14:27:12 -07003565
Makoto Onuki4d298b52018-02-05 10:54:58 -08003566 public void postRemoveForStopped(int uid) {
3567 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3568 }
3569
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003571 switch (msg.what) {
3572 case ALARM_EVENT: {
3573 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3574 synchronized (mLock) {
3575 final long nowRTC = System.currentTimeMillis();
3576 final long nowELAPSED = SystemClock.elapsedRealtime();
3577 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3578 updateNextAlarmClockLocked();
3579 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003580
Christopher Tate14a7bb02015-10-01 10:24:31 -07003581 // now trigger the alarms without the lock held
3582 for (int i=0; i<triggerList.size(); i++) {
3583 Alarm alarm = triggerList.get(i);
3584 try {
3585 alarm.operation.send();
3586 } catch (PendingIntent.CanceledException e) {
3587 if (alarm.repeatInterval > 0) {
3588 // This IntentSender is no longer valid, but this
3589 // is a repeating alarm, so toss the hoser.
3590 removeImpl(alarm.operation);
3591 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003592 }
3593 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003594 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003596
3597 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3598 sendNextAlarmClockChanged();
3599 break;
3600
3601 case LISTENER_TIMEOUT:
3602 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3603 break;
3604
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003605 case REPORT_ALARMS_ACTIVE:
3606 if (mLocalDeviceIdleController != null) {
3607 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3608 }
3609 break;
3610
Suprabh Shukla75edab12018-01-29 14:09:06 -08003611 case APP_STANDBY_PAROLE_CHANGED:
3612 synchronized (mLock) {
3613 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003614 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3615 rescheduleKernelAlarmsLocked();
3616 updateNextAlarmClockLocked();
3617 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003618 }
3619 break;
3620
3621 case APP_STANDBY_BUCKET_CHANGED:
3622 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003623 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3624 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3625 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3626 rescheduleKernelAlarmsLocked();
3627 updateNextAlarmClockLocked();
3628 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003629 }
3630 break;
3631
Makoto Onuki4d298b52018-02-05 10:54:58 -08003632 case REMOVE_FOR_STOPPED:
3633 synchronized (mLock) {
3634 removeForStoppedLocked(msg.arg1);
3635 }
3636 break;
3637
Christopher Tate14a7bb02015-10-01 10:24:31 -07003638 default:
3639 // nope, just ignore it
3640 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
3642 }
3643 }
Kweku Adams61e03292017-10-19 14:27:12 -07003644
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 class ClockReceiver extends BroadcastReceiver {
3646 public ClockReceiver() {
3647 IntentFilter filter = new IntentFilter();
3648 filter.addAction(Intent.ACTION_TIME_TICK);
3649 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003650 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 }
Kweku Adams61e03292017-10-19 14:27:12 -07003652
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 @Override
3654 public void onReceive(Context context, Intent intent) {
3655 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003656 if (DEBUG_BATCH) {
3657 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3658 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003659 synchronized (mLock) {
3660 mLastTickReceived = System.currentTimeMillis();
3661 }
Christopher Tate385e4982013-07-23 18:22:29 -07003662 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003663 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3664 // Since the kernel does not keep track of DST, we need to
3665 // reset the TZ information at the beginning of each day
3666 // based off of the current Zone gmt offset + userspace tracked
3667 // daylight savings information.
3668 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003669 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003670 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003671 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003672 }
3673 }
Kweku Adams61e03292017-10-19 14:27:12 -07003674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003676 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003677 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003678
3679 // Schedule this event for the amount of time that it would take to get to
3680 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003681 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003682
David Christieebe51fc2013-07-26 13:23:29 -07003683 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003684 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003685 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3686 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003687
3688 // Finally, remember when we set the tick alarm
3689 synchronized (mLock) {
3690 mLastTickSet = currentTime;
3691 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003692 }
Christopher Tate385e4982013-07-23 18:22:29 -07003693
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003694 public void scheduleDateChangedEvent() {
3695 Calendar calendar = Calendar.getInstance();
3696 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003697 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003698 calendar.set(Calendar.MINUTE, 0);
3699 calendar.set(Calendar.SECOND, 0);
3700 calendar.set(Calendar.MILLISECOND, 0);
3701 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003702
3703 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003704 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3705 AlarmManager.FLAG_STANDALONE, workSource, null,
3706 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
3708 }
Kweku Adams61e03292017-10-19 14:27:12 -07003709
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003710 class InteractiveStateReceiver extends BroadcastReceiver {
3711 public InteractiveStateReceiver() {
3712 IntentFilter filter = new IntentFilter();
3713 filter.addAction(Intent.ACTION_SCREEN_OFF);
3714 filter.addAction(Intent.ACTION_SCREEN_ON);
3715 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3716 getContext().registerReceiver(this, filter);
3717 }
3718
3719 @Override
3720 public void onReceive(Context context, Intent intent) {
3721 synchronized (mLock) {
3722 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3723 }
3724 }
3725 }
3726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 class UninstallReceiver extends BroadcastReceiver {
3728 public UninstallReceiver() {
3729 IntentFilter filter = new IntentFilter();
3730 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3731 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003732 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003734 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003735 // Register for events related to sdcard installation.
3736 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003737 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003738 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003739 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003740 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 }
Kweku Adams61e03292017-10-19 14:27:12 -07003742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003743 @Override
3744 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003745 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003747 String action = intent.getAction();
3748 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003749 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3750 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3751 for (String packageName : pkgList) {
3752 if (lookForPackageLocked(packageName)) {
3753 setResultCode(Activity.RESULT_OK);
3754 return;
3755 }
3756 }
3757 return;
3758 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003759 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003760 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3761 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3762 if (userHandle >= 0) {
3763 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003764 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3765 final Pair<String, Integer> packageUser =
3766 mLastAlarmDeliveredForPackage.keyAt(i);
3767 if (packageUser.second == userHandle) {
3768 mLastAlarmDeliveredForPackage.removeAt(i);
3769 }
3770 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003771 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003772 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003773 if (uid >= 0) {
3774 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003775 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003776 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003777 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003778 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3779 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3780 // This package is being updated; don't kill its alarms.
3781 return;
3782 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003783 Uri data = intent.getData();
3784 if (data != null) {
3785 String pkg = data.getSchemeSpecificPart();
3786 if (pkg != null) {
3787 pkgList = new String[]{pkg};
3788 }
3789 }
3790 }
3791 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003792 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3793 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3794 if (ArrayUtils.contains(pkgList, packageUser.first)
3795 && packageUser.second == UserHandle.getUserId(uid)) {
3796 mLastAlarmDeliveredForPackage.removeAt(i);
3797 }
3798 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003799 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003800 if (uid >= 0) {
3801 // package-removed case
3802 removeLocked(uid);
3803 } else {
3804 // external-applications-unavailable etc case
3805 removeLocked(pkg);
3806 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003807 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003808 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3809 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3810 if (uidStats.remove(pkg) != null) {
3811 if (uidStats.size() <= 0) {
3812 mBroadcastStats.removeAt(i);
3813 }
3814 }
3815 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003817 }
3818 }
3819 }
3820 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003821
3822 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003823 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003824 }
3825
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003826 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003827 if (disabled) {
3828 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003829 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003830 }
3831
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003832 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003833 }
3834
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003835 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003836 if (disabled) {
3837 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003838 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003839 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003840
3841 @Override public void onUidCachedChanged(int uid, boolean cached) {
3842 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003843 };
3844
Suprabh Shukla75edab12018-01-29 14:09:06 -08003845 /**
3846 * Tracking of app assignments to standby buckets
3847 */
3848 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3849 @Override
3850 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
3851 boolean idle, int bucket) {
3852 if (DEBUG_STANDBY) {
3853 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3854 bucket);
3855 }
3856 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003857 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3858 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003859 }
3860
3861 @Override
3862 public void onParoleStateChanged(boolean isParoleOn) {
3863 if (DEBUG_STANDBY) {
3864 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3865 }
3866 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3867 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3868 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3869 Boolean.valueOf(isParoleOn)).sendToTarget();
3870 }
3871 };
3872
Makoto Onuki2206af32017-11-21 16:25:35 -08003873 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003874 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003875 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003876 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003877 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003878 }
3879 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003880
3881 @Override
3882 public void unblockAlarmsForUid(int uid) {
3883 synchronized (mLock) {
3884 sendPendingBackgroundAlarmsLocked(uid, null);
3885 }
3886 }
3887
3888 @Override
3889 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3890 synchronized (mLock) {
3891 sendPendingBackgroundAlarmsLocked(uid, packageName);
3892 }
3893 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003894
3895 @Override
3896 public void onUidForeground(int uid, boolean foreground) {
3897 synchronized (mLock) {
3898 if (foreground) {
3899 mUseAllowWhileIdleShortTime.put(uid, true);
3900
3901 // Note we don't have to drain the pending while-idle alarms here, because
3902 // this event should coincide with unblockAlarmsForUid().
3903 }
3904 }
3905 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003906 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003907
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003908 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003909 String pkg = pi.getCreatorPackage();
3910 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003911 return getStatsLocked(uid, pkg);
3912 }
3913
3914 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003915 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3916 if (uidStats == null) {
3917 uidStats = new ArrayMap<String, BroadcastStats>();
3918 mBroadcastStats.put(uid, uidStats);
3919 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003920 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003922 bs = new BroadcastStats(uid, pkgName);
3923 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003924 }
3925 return bs;
3926 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003927
Christopher Tate21e9f192017-08-08 13:49:11 -07003928 /**
3929 * Canonical count of (operation.send() - onSendFinished()) and
3930 * listener send/complete/timeout invocations.
3931 * Guarded by the usual lock.
3932 */
3933 @GuardedBy("mLock")
3934 private int mSendCount = 0;
3935 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003936 private int mSendFinishCount = 0;
3937 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003938 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003939 @GuardedBy("mLock")
3940 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003941
Christopher Tate14a7bb02015-10-01 10:24:31 -07003942 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003943
Christopher Tate14a7bb02015-10-01 10:24:31 -07003944 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3945 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003946 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003947 return mInFlight.remove(i);
3948 }
3949 }
3950 mLog.w("No in-flight alarm for " + pi + " " + intent);
3951 return null;
3952 }
3953
3954 private InFlight removeLocked(IBinder listener) {
3955 for (int i = 0; i < mInFlight.size(); i++) {
3956 if (mInFlight.get(i).mListener == listener) {
3957 return mInFlight.remove(i);
3958 }
3959 }
3960 mLog.w("No in-flight alarm for listener " + listener);
3961 return null;
3962 }
3963
3964 private void updateStatsLocked(InFlight inflight) {
3965 final long nowELAPSED = SystemClock.elapsedRealtime();
3966 BroadcastStats bs = inflight.mBroadcastStats;
3967 bs.nesting--;
3968 if (bs.nesting <= 0) {
3969 bs.nesting = 0;
3970 bs.aggregateTime += nowELAPSED - bs.startTime;
3971 }
3972 FilterStats fs = inflight.mFilterStats;
3973 fs.nesting--;
3974 if (fs.nesting <= 0) {
3975 fs.nesting = 0;
3976 fs.aggregateTime += nowELAPSED - fs.startTime;
3977 }
3978 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003979 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3980 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003981 }
3982 }
3983
3984 private void updateTrackingLocked(InFlight inflight) {
3985 if (inflight != null) {
3986 updateStatsLocked(inflight);
3987 }
3988 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003989 if (DEBUG_WAKELOCK) {
3990 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3991 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003992 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003993 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003994 mWakeLock.release();
3995 if (mInFlight.size() > 0) {
3996 mLog.w("Finished all dispatches with " + mInFlight.size()
3997 + " remaining inflights");
3998 for (int i=0; i<mInFlight.size(); i++) {
3999 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4000 }
4001 mInFlight.clear();
4002 }
4003 } else {
4004 // the next of our alarms is now in flight. reattribute the wakelock.
4005 if (mInFlight.size() > 0) {
4006 InFlight inFlight = mInFlight.get(0);
4007 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4008 inFlight.mAlarmType, inFlight.mTag, -1, false);
4009 } else {
4010 // should never happen
4011 mLog.w("Alarm wakelock still held but sent queue empty");
4012 mWakeLock.setWorkSource(null);
4013 }
4014 }
4015 }
4016
4017 /**
4018 * Callback that arrives when a direct-call alarm reports that delivery has finished
4019 */
4020 @Override
4021 public void alarmComplete(IBinder who) {
4022 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004023 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004024 + " pid=" + Binder.getCallingPid());
4025 return;
4026 }
4027
4028 final long ident = Binder.clearCallingIdentity();
4029 try {
4030 synchronized (mLock) {
4031 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4032 InFlight inflight = removeLocked(who);
4033 if (inflight != null) {
4034 if (DEBUG_LISTENER_CALLBACK) {
4035 Slog.i(TAG, "alarmComplete() from " + who);
4036 }
4037 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004038 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004039 } else {
4040 // Delivery timed out, and the timeout handling already took care of
4041 // updating our tracking here, so we needn't do anything further.
4042 if (DEBUG_LISTENER_CALLBACK) {
4043 Slog.i(TAG, "Late alarmComplete() from " + who);
4044 }
4045 }
4046 }
4047 } finally {
4048 Binder.restoreCallingIdentity(ident);
4049 }
4050 }
4051
4052 /**
4053 * Callback that arrives when a PendingIntent alarm has finished delivery
4054 */
4055 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4057 String resultData, Bundle resultExtras) {
4058 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004059 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004060 updateTrackingLocked(removeLocked(pi, intent));
4061 }
4062 }
4063
4064 /**
4065 * Timeout of a direct-call alarm delivery
4066 */
4067 public void alarmTimedOut(IBinder who) {
4068 synchronized (mLock) {
4069 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004070 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004071 // TODO: implement ANR policy for the target
4072 if (DEBUG_LISTENER_CALLBACK) {
4073 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004074 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004075 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004076 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004077 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004078 if (DEBUG_LISTENER_CALLBACK) {
4079 Slog.i(TAG, "Spurious timeout of listener " + who);
4080 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004081 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004082 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004083 }
4084 }
4085
4086 /**
4087 * Deliver an alarm and set up the post-delivery handling appropriately
4088 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004089 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004090 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4091 if (alarm.operation != null) {
4092 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004093 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004094
4095 if (alarm.priorityClass.priority == PRIO_TICK) {
4096 mLastTickIssued = nowELAPSED;
4097 }
4098
Christopher Tate14a7bb02015-10-01 10:24:31 -07004099 try {
4100 alarm.operation.send(getContext(), 0,
4101 mBackgroundIntent.putExtra(
4102 Intent.EXTRA_ALARM_COUNT, alarm.count),
4103 mDeliveryTracker, mHandler, null,
4104 allowWhileIdle ? mIdleOptions : null);
4105 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004106 if (alarm.operation == mTimeTickSender) {
4107 Slog.wtf(TAG, "mTimeTickSender canceled");
4108 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004109 if (alarm.repeatInterval > 0) {
4110 // This IntentSender is no longer valid, but this
4111 // is a repeating alarm, so toss it
4112 removeImpl(alarm.operation);
4113 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004114 // No actual delivery was possible, so the delivery tracker's
4115 // 'finished' callback won't be invoked. We also don't need
4116 // to do any wakelock or stats tracking, so we have nothing
4117 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004118 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004119 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004120 }
4121 } else {
4122 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004123 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004124 try {
4125 if (DEBUG_LISTENER_CALLBACK) {
4126 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4127 + " listener=" + alarm.listener.asBinder());
4128 }
4129 alarm.listener.doAlarm(this);
4130 mHandler.sendMessageDelayed(
4131 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4132 alarm.listener.asBinder()),
4133 mConstants.LISTENER_TIMEOUT);
4134 } catch (Exception e) {
4135 if (DEBUG_LISTENER_CALLBACK) {
4136 Slog.i(TAG, "Alarm undeliverable to listener "
4137 + alarm.listener.asBinder(), e);
4138 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004139 // As in the PendingIntent.CanceledException case, delivery of the
4140 // alarm was not possible, so we have no wakelock or timeout or
4141 // stats management to do. It threw before we posted the delayed
4142 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004143 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004144 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004145 }
4146 }
4147
4148 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004149 if (DEBUG_WAKELOCK) {
4150 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4151 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004152 if (mBroadcastRefCount == 0) {
4153 setWakelockWorkSource(alarm.operation, alarm.workSource,
4154 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4155 true);
4156 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004157 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004158 }
4159 final InFlight inflight = new InFlight(AlarmManagerService.this,
4160 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4161 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4162 mInFlight.add(inflight);
4163 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004164 if (allowWhileIdle) {
4165 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004166 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004167 if ((mAppStateTracker == null)
4168 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004169 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4170 } else {
4171 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4172 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004173 if (RECORD_DEVICE_IDLE_ALARMS) {
4174 IdleDispatchEntry ent = new IdleDispatchEntry();
4175 ent.uid = alarm.uid;
4176 ent.pkg = alarm.packageName;
4177 ent.tag = alarm.statsTag;
4178 ent.op = "DELIVER";
4179 ent.elapsedRealtime = nowELAPSED;
4180 mAllowWhileIdleDispatches.add(ent);
4181 }
4182 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004183 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004184 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4185 UserHandle.getUserId(alarm.creatorUid));
4186 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4187 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004188
4189 final BroadcastStats bs = inflight.mBroadcastStats;
4190 bs.count++;
4191 if (bs.nesting == 0) {
4192 bs.nesting = 1;
4193 bs.startTime = nowELAPSED;
4194 } else {
4195 bs.nesting++;
4196 }
4197 final FilterStats fs = inflight.mFilterStats;
4198 fs.count++;
4199 if (fs.nesting == 0) {
4200 fs.nesting = 1;
4201 fs.startTime = nowELAPSED;
4202 } else {
4203 fs.nesting++;
4204 }
4205 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4206 || alarm.type == RTC_WAKEUP) {
4207 bs.numWakeup++;
4208 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004209 ActivityManager.noteWakeupAlarm(
4210 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4211 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004212 }
4213 }
4214 }
4215}