blob: 23a1d8202b0e7ab1ed0da35d26e24968de32f7a6 [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;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020059import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080060import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080061import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070062import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020063import android.util.Log;
Suprabh Shukla75edab12018-01-29 14:09:06 -080064import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080065import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080066import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020067import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070068import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070069import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070070import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071
Christopher Tate4cb338d2013-07-26 13:11:31 -070072import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.io.FileDescriptor;
74import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070075import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080077import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080078import java.util.Calendar;
79import java.util.Collections;
80import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050081import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070082import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070083import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020084import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070085import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040087import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -080088import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Suprabh Shuklac25447d2018-01-19 16:43:35 -080090import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -080091import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
Christopher Tatee0a22b32013-07-11 14:43:13 -070092import static android.app.AlarmManager.RTC_WAKEUP;
93import static android.app.AlarmManager.RTC;
94import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
95import static android.app.AlarmManager.ELAPSED_REALTIME;
96
Christopher Tate21e9f192017-08-08 13:49:11 -070097import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080098import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki5d93b832018-01-10 16:12:39 -080099import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600100import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -0800101import com.android.internal.util.LocalLog;
Makoto Onukie4918212018-02-06 11:30:15 -0800102import com.android.internal.util.Preconditions;
103import com.android.server.AppStateTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -0800104
Makoto Onuki2206af32017-11-21 16:25:35 -0800105/**
106 * Alarm manager implementaion.
107 *
108 * Unit test:
109 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
110 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800111class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700112 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
113 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700115 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800116 static final int TIME_CHANGED_MASK = 1 << 16;
117 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800118
Christopher Tatee0a22b32013-07-11 14:43:13 -0700119 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800121
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final boolean localLOGV = false;
124 static final boolean DEBUG_BATCH = localLOGV || false;
125 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200126 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700127 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800128 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700129 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800130 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700131 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700132 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 static final int ALARM_EVENT = 1;
134 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200135
Christopher Tate14a7bb02015-10-01 10:24:31 -0700136 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700139
Adam Lesinski182f73f2013-12-05 16:48:06 -0800140 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700141
Christopher Tate24cd46f2016-02-02 14:28:01 -0800142 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
143 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700144 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
145 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200146
Adam Lesinski182f73f2013-12-05 16:48:06 -0800147 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800148
Christopher Tate14a7bb02015-10-01 10:24:31 -0700149 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800150 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800151 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700152
Adam Lesinski182f73f2013-12-05 16:48:06 -0800153 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800154
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700155 // List of alarms per uid deferred due to user applied background restrictions on the source app
156 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800157 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800158 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700159 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700160 private long mLastWakeupSet;
161 private long mLastWakeup;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800162 private long mLastTickSet;
163 private long mLastTickIssued; // elapsed
164 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800165 private long mLastTickAdded;
166 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800167 int mBroadcastRefCount = 0;
168 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700169 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700170 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
171 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 final AlarmHandler mHandler = new AlarmHandler();
173 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700174 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800175 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700176 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800177 PendingIntent mTimeTickSender;
178 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700179 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700180 boolean mInteractive = true;
181 long mNonInteractiveStartTime;
182 long mNonInteractiveTime;
183 long mLastAlarmDeliveryTime;
184 long mStartCurrentDelayTime;
185 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700186 long mLastTimeChangeClockTime;
187 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700188 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800189
Christopher Tatebb9cce52017-04-18 14:19:43 -0700190 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
191
192 /**
193 * This permission must be defined by the canonical System UI package,
194 * with protection level "signature".
195 */
196 private static final String SYSTEM_UI_SELF_PERMISSION =
197 "android.permission.systemui.IDENTITY";
198
199 /**
200 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
201 */
202 int mSystemUiUid;
203
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700204 /**
205 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700206 * used to determine the earliest we can dispatch the next such alarm. Times are in the
207 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700208 */
209 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
210
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800211 /**
212 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
213 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
214 */
215 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
216
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700217 final static class IdleDispatchEntry {
218 int uid;
219 String pkg;
220 String tag;
221 String op;
222 long elapsedRealtime;
223 long argRealtime;
224 }
225 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
226
Suprabh Shukla75edab12018-01-29 14:09:06 -0800227 interface Stats {
228 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800229 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800230 }
231
232 private final StatLogger mStatLogger = new StatLogger(new String[] {
233 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800234 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800235 });
236
Dianne Hackborna750a632015-06-16 17:18:23 -0700237 /**
238 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
239 */
240 Bundle mIdleOptions;
241
Jose Lima235510e2014-08-13 12:50:01 -0700242 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
243 new SparseArray<>();
244 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
245 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200246 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
247 new SparseBooleanArray();
248 private boolean mNextAlarmClockMayChange;
249
250 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700251 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
252 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200253
Makoto Onukie4918212018-02-06 11:30:15 -0800254 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800255 private boolean mAppStandbyParole;
256 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800257
Dianne Hackborna750a632015-06-16 17:18:23 -0700258 /**
259 * All times are in milliseconds. These constants are kept synchronized with the system
260 * global Settings. Any access to this class or its fields should be done while
261 * holding the AlarmManagerService.mLock lock.
262 */
263 private final class Constants extends ContentObserver {
264 // Key names stored in the settings value.
265 private static final String KEY_MIN_FUTURITY = "min_futurity";
266 private static final String KEY_MIN_INTERVAL = "min_interval";
267 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
268 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
269 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
270 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700271 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700272
Suprabh Shukla75edab12018-01-29 14:09:06 -0800273 // Keys for specifying throttling delay based on app standby bucketing
274 private final String[] KEYS_APP_STANDBY_DELAY = {
275 "standby_active_delay",
276 "standby_working_delay",
277 "standby_frequent_delay",
278 "standby_rare_delay",
279 "standby_never_delay",
280 };
281
Dianne Hackborna750a632015-06-16 17:18:23 -0700282 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
283 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700284 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700285 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700286 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700287 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800288 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
289 0, // Active
290 6 * 60_000, // Working
291 30 * 60_000, // Frequent
292 2 * 60 * 60_000, // Rare
293 10 * 24 * 60 * 60_000 // Never
294 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700295
Dianne Hackborna750a632015-06-16 17:18:23 -0700296 // Minimum futurity of a new alarm
297 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
298
299 // Minimum alarm recurrence interval
300 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
301
302 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
303 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
304
305 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
306 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
307
308 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
309 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
310 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
311
Christopher Tate14a7bb02015-10-01 10:24:31 -0700312 // Direct alarm listener callback timeout
313 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
314
Suprabh Shukla75edab12018-01-29 14:09:06 -0800315 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
316
Dianne Hackborna750a632015-06-16 17:18:23 -0700317 private ContentResolver mResolver;
318 private final KeyValueListParser mParser = new KeyValueListParser(',');
319 private long mLastAllowWhileIdleWhitelistDuration = -1;
320
321 public Constants(Handler handler) {
322 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700323 updateAllowWhileIdleWhitelistDurationLocked();
324 }
325
326 public void start(ContentResolver resolver) {
327 mResolver = resolver;
328 mResolver.registerContentObserver(Settings.Global.getUriFor(
329 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
330 updateConstants();
331 }
332
Dianne Hackborna750a632015-06-16 17:18:23 -0700333 public void updateAllowWhileIdleWhitelistDurationLocked() {
334 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
335 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
336 BroadcastOptions opts = BroadcastOptions.makeBasic();
337 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
338 mIdleOptions = opts.toBundle();
339 }
340 }
341
342 @Override
343 public void onChange(boolean selfChange, Uri uri) {
344 updateConstants();
345 }
346
347 private void updateConstants() {
348 synchronized (mLock) {
349 try {
350 mParser.setString(Settings.Global.getString(mResolver,
351 Settings.Global.ALARM_MANAGER_CONSTANTS));
352 } catch (IllegalArgumentException e) {
353 // Failed to parse the settings string, log this and move on
354 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800355 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700356 }
357
358 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
359 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
360 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
361 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
362 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
363 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
364 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
365 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
366 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700367 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
368 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800369 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
370 DEFAULT_APP_STANDBY_DELAYS[0]);
371 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
372 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
373 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
374 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700375 updateAllowWhileIdleWhitelistDurationLocked();
376 }
377 }
378
379 void dump(PrintWriter pw) {
380 pw.println(" Settings:");
381
382 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
383 TimeUtils.formatDuration(MIN_FUTURITY, pw);
384 pw.println();
385
386 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
387 TimeUtils.formatDuration(MIN_INTERVAL, pw);
388 pw.println();
389
Christopher Tate14a7bb02015-10-01 10:24:31 -0700390 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
391 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
392 pw.println();
393
Dianne Hackborna750a632015-06-16 17:18:23 -0700394 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
395 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
396 pw.println();
397
398 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
399 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
400 pw.println();
401
402 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
403 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
404 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800405
406 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
407 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
408 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
409 pw.println();
410 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700411 }
Kweku Adams61e03292017-10-19 14:27:12 -0700412
413 void dumpProto(ProtoOutputStream proto, long fieldId) {
414 final long token = proto.start(fieldId);
415
416 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
417 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
418 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
419 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
420 ALLOW_WHILE_IDLE_SHORT_TIME);
421 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
422 ALLOW_WHILE_IDLE_LONG_TIME);
423 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
424 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
425
426 proto.end(token);
427 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700428 }
429
430 final Constants mConstants;
431
Christopher Tate1590f1e2014-10-02 17:27:57 -0700432 // Alarm delivery ordering bookkeeping
433 static final int PRIO_TICK = 0;
434 static final int PRIO_WAKEUP = 1;
435 static final int PRIO_NORMAL = 2;
436
Dianne Hackborna750a632015-06-16 17:18:23 -0700437 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700438 int seq;
439 int priority;
440
441 PriorityClass() {
442 seq = mCurrentSeq - 1;
443 priority = PRIO_NORMAL;
444 }
445 }
446
Dianne Hackborna750a632015-06-16 17:18:23 -0700447 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700448 int mCurrentSeq = 0;
449
Dianne Hackborna750a632015-06-16 17:18:23 -0700450 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700451 public long when;
452 public int uid;
453 public String action;
454
455 public WakeupEvent(long theTime, int theUid, String theAction) {
456 when = theTime;
457 uid = theUid;
458 action = theAction;
459 }
460 }
461
Adam Lesinski182f73f2013-12-05 16:48:06 -0800462 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
463 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700464
Adrian Roosc42a1e12014-07-07 23:35:53 +0200465 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700466 long start; // These endpoints are always in ELAPSED
467 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700468 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700469
470 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
471
472 Batch() {
473 start = 0;
474 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700475 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700476 }
477
478 Batch(Alarm seed) {
479 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700480 end = seed.maxWhenElapsed;
481 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800483 if (seed.operation == mTimeTickSender) {
484 mLastTickAdded = System.currentTimeMillis();
485 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486 }
487
488 int size() {
489 return alarms.size();
490 }
491
492 Alarm get(int index) {
493 return alarms.get(index);
494 }
495
496 boolean canHold(long whenElapsed, long maxWhen) {
497 return (end >= whenElapsed) && (start <= maxWhen);
498 }
499
500 boolean add(Alarm alarm) {
501 boolean newStart = false;
502 // narrows the batch if necessary; presumes that canHold(alarm) is true
503 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
504 if (index < 0) {
505 index = 0 - index - 1;
506 }
507 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800508 if (alarm.operation == mTimeTickSender) {
509 mLastTickAdded = System.currentTimeMillis();
510 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511 if (DEBUG_BATCH) {
512 Slog.v(TAG, "Adding " + alarm + " to " + this);
513 }
514 if (alarm.whenElapsed > start) {
515 start = alarm.whenElapsed;
516 newStart = true;
517 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700518 if (alarm.maxWhenElapsed < end) {
519 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700521 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700522
523 if (DEBUG_BATCH) {
524 Slog.v(TAG, " => now " + this);
525 }
526 return newStart;
527 }
528
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800529 boolean remove(Alarm alarm) {
530 return remove(a -> (a == alarm));
531 }
532
Christopher Tate1d99c392017-12-07 16:54:04 -0800533 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700534 boolean didRemove = false;
535 long newStart = 0; // recalculate endpoints as we go
536 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700537 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700538 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700539 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800540 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 alarms.remove(i);
542 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200543 if (alarm.alarmClock != null) {
544 mNextAlarmClockMayChange = true;
545 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800546 if (alarm.operation == mTimeTickSender) {
547 mLastTickRemoved = System.currentTimeMillis();
548 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 } else {
550 if (alarm.whenElapsed > newStart) {
551 newStart = alarm.whenElapsed;
552 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700553 if (alarm.maxWhenElapsed < newEnd) {
554 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700556 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557 i++;
558 }
559 }
560 if (didRemove) {
561 // commit the new batch bounds
562 start = newStart;
563 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700564 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 }
566 return didRemove;
567 }
568
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 boolean hasPackage(final String packageName) {
570 final int N = alarms.size();
571 for (int i = 0; i < N; i++) {
572 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700573 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 return true;
575 }
576 }
577 return false;
578 }
579
580 boolean hasWakeups() {
581 final int N = alarms.size();
582 for (int i = 0; i < N; i++) {
583 Alarm a = alarms.get(i);
584 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
585 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
586 return true;
587 }
588 }
589 return false;
590 }
591
592 @Override
593 public String toString() {
594 StringBuilder b = new StringBuilder(40);
595 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
596 b.append(" num="); b.append(size());
597 b.append(" start="); b.append(start);
598 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700599 if (flags != 0) {
600 b.append(" flgs=0x");
601 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700602 }
603 b.append('}');
604 return b.toString();
605 }
Kweku Adams61e03292017-10-19 14:27:12 -0700606
607 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
608 long nowRTC) {
609 final long token = proto.start(fieldId);
610
611 proto.write(BatchProto.START_REALTIME, start);
612 proto.write(BatchProto.END_REALTIME, end);
613 proto.write(BatchProto.FLAGS, flags);
614 for (Alarm a : alarms) {
615 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
616 }
617
618 proto.end(token);
619 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700620 }
621
622 static class BatchTimeOrder implements Comparator<Batch> {
623 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800624 long when1 = b1.start;
625 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800626 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700627 return 1;
628 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800629 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700630 return -1;
631 }
632 return 0;
633 }
634 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800635
636 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
637 @Override
638 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700639 // priority class trumps everything. TICK < WAKEUP < NORMAL
640 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
641 return -1;
642 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
643 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800644 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700645
646 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800647 if (lhs.whenElapsed < rhs.whenElapsed) {
648 return -1;
649 } else if (lhs.whenElapsed > rhs.whenElapsed) {
650 return 1;
651 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700652
653 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800654 return 0;
655 }
656 };
657
Christopher Tate1590f1e2014-10-02 17:27:57 -0700658 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
659 final int N = alarms.size();
660 for (int i = 0; i < N; i++) {
661 Alarm a = alarms.get(i);
662
663 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700664 if (a.operation != null
665 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700666 alarmPrio = PRIO_TICK;
667 } else if (a.wakeup) {
668 alarmPrio = PRIO_WAKEUP;
669 } else {
670 alarmPrio = PRIO_NORMAL;
671 }
672
673 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800674 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700675 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700676 if (packagePrio == null) {
677 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700678 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700679 }
680 a.priorityClass = packagePrio;
681
682 if (packagePrio.seq != mCurrentSeq) {
683 // first alarm we've seen in the current delivery generation from this package
684 packagePrio.priority = alarmPrio;
685 packagePrio.seq = mCurrentSeq;
686 } else {
687 // Multiple alarms from this package being delivered in this generation;
688 // bump the package's delivery class if it's warranted.
689 // TICK < WAKEUP < NORMAL
690 if (alarmPrio < packagePrio.priority) {
691 packagePrio.priority = alarmPrio;
692 }
693 }
694 }
695 }
696
Christopher Tatee0a22b32013-07-11 14:43:13 -0700697 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800698 static final long MIN_FUZZABLE_INTERVAL = 10000;
699 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700700 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
701
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700702 // 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 -0700703 // to run during this time are placed in mPendingWhileIdleAlarms
704 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700705 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700706 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700707
Jeff Brownb880d882014-02-10 19:47:07 -0800708 public AlarmManagerService(Context context) {
709 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700710 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800711
Christopher Tate1d99c392017-12-07 16:54:04 -0800712 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800713 }
714
Christopher Tatee0a22b32013-07-11 14:43:13 -0700715 static long convertToElapsed(long when, int type) {
716 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
717 if (isRtc) {
718 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
719 }
720 return when;
721 }
722
723 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
724 // calculate the end of our nominal delivery window for the alarm.
725 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
726 // Current heuristic: batchable window is 75% of either the recurrence interval
727 // [for a periodic alarm] or of the time from now to the desired delivery time,
728 // with a minimum delay/interval of 10 seconds, under which we will simply not
729 // defer the alarm.
730 long futurity = (interval == 0)
731 ? (triggerAtTime - now)
732 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700733 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700734 futurity = 0;
735 }
736 return triggerAtTime + (long)(.75 * futurity);
737 }
738
739 // returns true if the batch was added at the head
740 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
741 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
742 if (index < 0) {
743 index = 0 - index - 1;
744 }
745 list.add(index, newBatch);
746 return (index == 0);
747 }
748
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800749 private void insertAndBatchAlarmLocked(Alarm alarm) {
750 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
751 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
752
753 if (whichBatch < 0) {
754 addBatchLocked(mAlarmBatches, new Batch(alarm));
755 } else {
756 final Batch batch = mAlarmBatches.get(whichBatch);
757 if (batch.add(alarm)) {
758 // The start time of this batch advanced, so batch ordering may
759 // have just been broken. Move it to where it now belongs.
760 mAlarmBatches.remove(whichBatch);
761 addBatchLocked(mAlarmBatches, batch);
762 }
763 }
764 }
765
Christopher Tate385e4982013-07-23 18:22:29 -0700766 // Return the index of the matching batch, or -1 if none found.
767 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700768 final int N = mAlarmBatches.size();
769 for (int i = 0; i < N; i++) {
770 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700771 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700772 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700773 }
774 }
Christopher Tate385e4982013-07-23 18:22:29 -0700775 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700776 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800777 /** @return total count of the alarms in a set of alarm batches. */
778 static int getAlarmCount(ArrayList<Batch> batches) {
779 int ret = 0;
780
781 final int size = batches.size();
782 for (int i = 0; i < size; i++) {
783 ret += batches.get(i).size();
784 }
785 return ret;
786 }
787
788 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
789 if (alarms.size() == 0) {
790 return false;
791 }
792 final int batchSize = alarms.size();
793 for (int j = 0; j < batchSize; j++) {
794 if (alarms.get(j).operation == mTimeTickSender) {
795 return true;
796 }
797 }
798 return false;
799 }
800
801 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
802 final int numBatches = batches.size();
803 for (int i = 0; i < numBatches; i++) {
804 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
805 return true;
806 }
807 }
808 return false;
809 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700810
811 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
812 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700813 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700814 rebatchAllAlarmsLocked(true);
815 }
816 }
817
818 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800819 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800820 final int oldCount =
821 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
822 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
823 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
824
Christopher Tate4cb338d2013-07-26 13:11:31 -0700825 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
826 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700827 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700828 final long nowElapsed = SystemClock.elapsedRealtime();
829 final int oldBatches = oldSet.size();
830 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
831 Batch batch = oldSet.get(batchNum);
832 final int N = batch.size();
833 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700834 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700835 }
836 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700837 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
838 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
839 + " to " + mPendingIdleUntil);
840 if (mPendingIdleUntil == null) {
841 // Somehow we lost this... we need to restore all of the pending alarms.
842 restorePendingWhileIdleAlarmsLocked();
843 }
844 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800845 final int newCount =
846 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
847 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
848 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
849
850 if (oldCount != newCount) {
851 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
852 }
853 if (oldHasTick != newHasTick) {
854 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
855 }
856
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700857 rescheduleKernelAlarmsLocked();
858 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800859 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700860 }
861
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800862 /**
863 * Re-orders the alarm batches based on newly evaluated send times based on the current
864 * app-standby buckets
865 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
866 * null indicates all
867 * @return True if there was any reordering done to the current list.
868 */
869 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
870 final long start = mStatLogger.getTime();
871 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
872
873 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
874 final Batch batch = mAlarmBatches.get(batchIndex);
875 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
876 final Alarm alarm = batch.get(alarmIndex);
877 final Pair<String, Integer> packageUser =
878 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
879 if (targetPackages != null && !targetPackages.contains(packageUser)) {
880 continue;
881 }
882 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
883 batch.remove(alarm);
884 rescheduledAlarms.add(alarm);
885 }
886 }
887 if (batch.size() == 0) {
888 mAlarmBatches.remove(batchIndex);
889 }
890 }
891 for (int i = 0; i < rescheduledAlarms.size(); i++) {
892 final Alarm a = rescheduledAlarms.get(i);
893 insertAndBatchAlarmLocked(a);
894 }
895
896 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
897 return rescheduledAlarms.size() > 0;
898 }
899
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700900 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
901 a.when = a.origWhen;
902 long whenElapsed = convertToElapsed(a.when, a.type);
903 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700904 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700905 // Exact
906 maxElapsed = whenElapsed;
907 } else {
908 // Not exact. Preserve any explicit window, otherwise recalculate
909 // the window based on the alarm's new futurity. Note that this
910 // reflects a policy of preferring timely to deferred delivery.
911 maxElapsed = (a.windowLength > 0)
912 ? (whenElapsed + a.windowLength)
913 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
914 }
915 a.whenElapsed = whenElapsed;
916 a.maxWhenElapsed = maxElapsed;
917 setImplLocked(a, true, doValidate);
918 }
919
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700920 /**
921 * Sends alarms that were blocked due to user applied background restrictions - either because
922 * the user lifted those or the uid came to foreground.
923 *
924 * @param uid uid to filter on
925 * @param packageName package to filter on, or null for all packages in uid
926 */
927 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
928 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
929 if (alarmsForUid == null || alarmsForUid.size() == 0) {
930 return;
931 }
932 final ArrayList<Alarm> alarmsToDeliver;
933 if (packageName != null) {
934 if (DEBUG_BG_LIMIT) {
935 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
936 }
937 alarmsToDeliver = new ArrayList<>();
938 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
939 final Alarm a = alarmsForUid.get(i);
940 if (a.matches(packageName)) {
941 alarmsToDeliver.add(alarmsForUid.remove(i));
942 }
943 }
944 if (alarmsForUid.size() == 0) {
945 mPendingBackgroundAlarms.remove(uid);
946 }
947 } else {
948 if (DEBUG_BG_LIMIT) {
949 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
950 }
951 alarmsToDeliver = alarmsForUid;
952 mPendingBackgroundAlarms.remove(uid);
953 }
954 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
955 }
956
Makoto Onuki2206af32017-11-21 16:25:35 -0800957 /**
958 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
959 * restricted.
960 *
961 * This is only called when the global "force all apps-standby" flag changes or when the
962 * power save whitelist changes, so it's okay to be slow.
963 */
964 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700965 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800966
967 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
968 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
969
970 if (alarmsToDeliver.size() > 0) {
971 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
972 }
973 }
974
975 @VisibleForTesting
976 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
977 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
978 Predicate<Alarm> isBackgroundRestricted) {
979
980 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
981 final int uid = pendingAlarms.keyAt(uidIndex);
982 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
983
984 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
985 final Alarm alarm = alarmsForUid.get(alarmIndex);
986
987 if (isBackgroundRestricted.test(alarm)) {
988 continue;
989 }
990
991 unrestrictedAlarms.add(alarm);
992 alarmsForUid.remove(alarmIndex);
993 }
994
995 if (alarmsForUid.size() == 0) {
996 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700997 }
998 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700999 }
1000
1001 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1002 final int N = alarms.size();
1003 boolean hasWakeup = false;
1004 for (int i = 0; i < N; i++) {
1005 final Alarm alarm = alarms.get(i);
1006 if (alarm.wakeup) {
1007 hasWakeup = true;
1008 }
1009 alarm.count = 1;
1010 // Recurring alarms may have passed several alarm intervals while the
1011 // alarm was kept pending. Send the appropriate trigger count.
1012 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001013 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001014 // Also schedule its next recurrence
1015 final long delta = alarm.count * alarm.repeatInterval;
1016 final long nextElapsed = alarm.whenElapsed + delta;
1017 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1018 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1019 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1020 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1021 // Kernel alarms will be rescheduled as needed in setImplLocked
1022 }
1023 }
1024 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1025 // No need to wakeup for non wakeup alarms
1026 if (mPendingNonWakeupAlarms.size() == 0) {
1027 mStartCurrentDelayTime = nowELAPSED;
1028 mNextNonWakeupDeliveryTime = nowELAPSED
1029 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1030 }
1031 mPendingNonWakeupAlarms.addAll(alarms);
1032 mNumDelayedAlarms += alarms.size();
1033 } else {
1034 if (DEBUG_BG_LIMIT) {
1035 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1036 }
1037 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1038 if (mPendingNonWakeupAlarms.size() > 0) {
1039 alarms.addAll(mPendingNonWakeupAlarms);
1040 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1041 mTotalDelayTime += thisDelayTime;
1042 if (mMaxDelayTime < thisDelayTime) {
1043 mMaxDelayTime = thisDelayTime;
1044 }
1045 mPendingNonWakeupAlarms.clear();
1046 }
1047 calculateDeliveryPriorities(alarms);
1048 Collections.sort(alarms, mAlarmDispatchComparator);
1049 deliverAlarmsLocked(alarms, nowELAPSED);
1050 }
1051 }
1052
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001053 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001054 if (RECORD_DEVICE_IDLE_ALARMS) {
1055 IdleDispatchEntry ent = new IdleDispatchEntry();
1056 ent.uid = 0;
1057 ent.pkg = "FINISH IDLE";
1058 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1059 mAllowWhileIdleDispatches.add(ent);
1060 }
1061
Dianne Hackborn35d54032015-04-23 10:30:43 -07001062 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001063 if (mPendingWhileIdleAlarms.size() > 0) {
1064 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1065 mPendingWhileIdleAlarms = new ArrayList<>();
1066 final long nowElapsed = SystemClock.elapsedRealtime();
1067 for (int i=alarms.size() - 1; i >= 0; i--) {
1068 Alarm a = alarms.get(i);
1069 reAddAlarmLocked(a, nowElapsed, false);
1070 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001071 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001072
1073 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001074 rescheduleKernelAlarmsLocked();
1075 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001076
1077 // And send a TIME_TICK right now, since it is important to get the UI updated.
1078 try {
1079 mTimeTickSender.send();
1080 } catch (PendingIntent.CanceledException e) {
1081 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001082 }
1083
Christopher Tate14a7bb02015-10-01 10:24:31 -07001084 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001085 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001086 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001087 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001088 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001089 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001090 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001091 final BroadcastStats mBroadcastStats;
1092 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001093 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001094
Christopher Tate14a7bb02015-10-01 10:24:31 -07001095 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1096 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1097 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001098 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001099 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001100 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001101 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001102 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001103 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001104 mBroadcastStats = (pendingIntent != null)
1105 ? service.getStatsLocked(pendingIntent)
1106 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001107 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001108 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001109 fs = new FilterStats(mBroadcastStats, mTag);
1110 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001111 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001112 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001113 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001114 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001115 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001116
1117 @Override
1118 public String toString() {
1119 return "InFlight{"
1120 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001121 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001122 + ", workSource=" + mWorkSource
1123 + ", uid=" + mUid
1124 + ", tag=" + mTag
1125 + ", broadcastStats=" + mBroadcastStats
1126 + ", filterStats=" + mFilterStats
1127 + ", alarmType=" + mAlarmType
1128 + "}";
1129 }
Kweku Adams61e03292017-10-19 14:27:12 -07001130
1131 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1132 final long token = proto.start(fieldId);
1133
1134 proto.write(InFlightProto.UID, mUid);
1135 proto.write(InFlightProto.TAG, mTag);
1136 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1137 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1138 if (mPendingIntent != null) {
1139 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1140 }
1141 if (mBroadcastStats != null) {
1142 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1143 }
1144 if (mFilterStats != null) {
1145 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1146 }
1147 if (mWorkSource != null) {
1148 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1149 }
1150
1151 proto.end(token);
1152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001154
Adam Lesinski182f73f2013-12-05 16:48:06 -08001155 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001156 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001157 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001158
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001159 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001161 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 int numWakeup;
1163 long startTime;
1164 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001165
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001166 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001167 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001168 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001169 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001170
1171 @Override
1172 public String toString() {
1173 return "FilterStats{"
1174 + "tag=" + mTag
1175 + ", lastTime=" + lastTime
1176 + ", aggregateTime=" + aggregateTime
1177 + ", count=" + count
1178 + ", numWakeup=" + numWakeup
1179 + ", startTime=" + startTime
1180 + ", nesting=" + nesting
1181 + "}";
1182 }
Kweku Adams61e03292017-10-19 14:27:12 -07001183
1184 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1185 final long token = proto.start(fieldId);
1186
1187 proto.write(FilterStatsProto.TAG, mTag);
1188 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1189 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1190 proto.write(FilterStatsProto.COUNT, count);
1191 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1192 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1193 proto.write(FilterStatsProto.NESTING, nesting);
1194
1195 proto.end(token);
1196 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001197 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001198
Adam Lesinski182f73f2013-12-05 16:48:06 -08001199 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001200 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001201 final String mPackageName;
1202
1203 long aggregateTime;
1204 int count;
1205 int numWakeup;
1206 long startTime;
1207 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001208 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001209
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001210 BroadcastStats(int uid, String packageName) {
1211 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001212 mPackageName = packageName;
1213 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001214
1215 @Override
1216 public String toString() {
1217 return "BroadcastStats{"
1218 + "uid=" + mUid
1219 + ", packageName=" + mPackageName
1220 + ", aggregateTime=" + aggregateTime
1221 + ", count=" + count
1222 + ", numWakeup=" + numWakeup
1223 + ", startTime=" + startTime
1224 + ", nesting=" + nesting
1225 + "}";
1226 }
Kweku Adams61e03292017-10-19 14:27:12 -07001227
1228 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1229 final long token = proto.start(fieldId);
1230
1231 proto.write(BroadcastStatsProto.UID, mUid);
1232 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1233 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1234 proto.write(BroadcastStatsProto.COUNT, count);
1235 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1236 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1237 proto.write(BroadcastStatsProto.NESTING, nesting);
1238
1239 proto.end(token);
1240 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001242
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001243 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1244 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001245
1246 int mNumDelayedAlarms = 0;
1247 long mTotalDelayTime = 0;
1248 long mMaxDelayTime = 0;
1249
Adam Lesinski182f73f2013-12-05 16:48:06 -08001250 @Override
1251 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001252 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001253 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001254
1255 // We have to set current TimeZone info to kernel
1256 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001257 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001258
Christopher Tate247571462017-04-10 11:45:05 -07001259 // Also sure that we're booting with a halfway sensible current time
1260 if (mNativeData != 0) {
1261 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1262 if (System.currentTimeMillis() < systemBuildTime) {
1263 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1264 + ", advancing to build time " + systemBuildTime);
1265 setKernelTime(mNativeData, systemBuildTime);
1266 }
1267 }
1268
Christopher Tatebb9cce52017-04-18 14:19:43 -07001269 // Determine SysUI's uid
1270 final PackageManager packMan = getContext().getPackageManager();
1271 try {
1272 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1273 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1274 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1275 mSystemUiUid = sysUi.uid;
1276 } else {
1277 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1278 + " defined by non-privileged app " + sysUi.packageName
1279 + " - ignoring");
1280 }
1281 } catch (NameNotFoundException e) {
1282 }
1283
1284 if (mSystemUiUid <= 0) {
1285 Slog.wtf(TAG, "SysUI package not found!");
1286 }
1287
Adam Lesinski182f73f2013-12-05 16:48:06 -08001288 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001289 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001290
Adam Lesinski182f73f2013-12-05 16:48:06 -08001291 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001293 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001294 | Intent.FLAG_RECEIVER_FOREGROUND
1295 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001296 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001297 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001298 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1299 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001300 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001301 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001302
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001303 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001304 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 mClockReceiver.scheduleTimeTickEvent();
1306 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001307 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001309
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001310 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001311 AlarmThread waitThread = new AlarmThread();
1312 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001313 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001314 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001316
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001317 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001318 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001319 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1320 | ActivityManager.UID_OBSERVER_ACTIVE,
1321 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001322 } catch (RemoteException e) {
1323 // ignored; both services live in system_server
1324 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001325 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327
1328 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001329 public void onBootPhase(int phase) {
1330 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1331 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001332 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001333 mLocalDeviceIdleController
1334 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001335 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1336 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001337
1338 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1339 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001340 }
1341 }
1342
1343 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 protected void finalize() throws Throwable {
1345 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001346 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 } finally {
1348 super.finalize();
1349 }
1350 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001351
Adam Lesinski182f73f2013-12-05 16:48:06 -08001352 void setTimeZoneImpl(String tz) {
1353 if (TextUtils.isEmpty(tz)) {
1354 return;
David Christieebe51fc2013-07-26 13:23:29 -07001355 }
1356
Adam Lesinski182f73f2013-12-05 16:48:06 -08001357 TimeZone zone = TimeZone.getTimeZone(tz);
1358 // Prevent reentrant calls from stepping on each other when writing
1359 // the time zone property
1360 boolean timeZoneWasChanged = false;
1361 synchronized (this) {
1362 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1363 if (current == null || !current.equals(zone.getID())) {
1364 if (localLOGV) {
1365 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1366 }
1367 timeZoneWasChanged = true;
1368 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1369 }
1370
1371 // Update the kernel timezone information
1372 // Kernel tracks time offsets as 'minutes west of GMT'
1373 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001374 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001375 }
1376
1377 TimeZone.setDefault(null);
1378
1379 if (timeZoneWasChanged) {
1380 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001381 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001382 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001383 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001384 intent.putExtra("time-zone", zone.getID());
1385 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001388
Adam Lesinski182f73f2013-12-05 16:48:06 -08001389 void removeImpl(PendingIntent operation) {
1390 if (operation == null) {
1391 return;
1392 }
1393 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001394 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001395 }
1396 }
1397
1398 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001399 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1400 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1401 int callingUid, String callingPackage) {
1402 // must be *either* PendingIntent or AlarmReceiver, but not both
1403 if ((operation == null && directReceiver == null)
1404 || (operation != null && directReceiver != null)) {
1405 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1406 // NB: previous releases failed silently here, so we are continuing to do the same
1407 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001408 return;
1409 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001410
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001411 // Sanity check the window length. This will catch people mistakenly
1412 // trying to pass an end-of-window timestamp rather than a duration.
1413 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1414 Slog.w(TAG, "Window length " + windowLength
1415 + "ms suspiciously long; limiting to 1 hour");
1416 windowLength = AlarmManager.INTERVAL_HOUR;
1417 }
1418
Christopher Tate498c6cb2014-11-17 16:09:27 -08001419 // Sanity check the recurrence interval. This will catch people who supply
1420 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001421 final long minInterval = mConstants.MIN_INTERVAL;
1422 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001423 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001424 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001425 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001426 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001427 }
1428
Christopher Tatee0a22b32013-07-11 14:43:13 -07001429 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1430 throw new IllegalArgumentException("Invalid alarm type " + type);
1431 }
1432
Christopher Tate5f221e82013-07-30 17:13:15 -07001433 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001434 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001435 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001436 + " pid=" + what);
1437 triggerAtTime = 0;
1438 }
1439
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001440 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001441 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1442 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001443 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001444 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1445
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001446 final long maxElapsed;
1447 if (windowLength == AlarmManager.WINDOW_EXACT) {
1448 maxElapsed = triggerElapsed;
1449 } else if (windowLength < 0) {
1450 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001451 // Fix this window in place, so that as time approaches we don't collapse it.
1452 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001453 } else {
1454 maxElapsed = triggerElapsed + windowLength;
1455 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001456
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001457 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001458 if (DEBUG_BATCH) {
1459 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001460 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001461 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001462 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001464 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001465 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1466 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 }
1468 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001469
Christopher Tate3e04b472013-10-21 17:51:31 -07001470 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001471 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1472 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1473 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001474 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001475 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1476 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001477 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001478 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001479 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1480 + " -- package not allowed to start");
1481 return;
1482 }
1483 } catch (RemoteException e) {
1484 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001485 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001486 setImplLocked(a, false, doValidate);
1487 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001488
Suprabh Shukla75edab12018-01-29 14:09:06 -08001489 private long getMinDelayForBucketLocked(int bucket) {
1490 // Return the minimum time that should elapse before an app in the specified bucket
1491 // can receive alarms again
1492 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
1493 return mConstants.APP_STANDBY_MIN_DELAYS[4];
1494 }
1495 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) {
1496 return mConstants.APP_STANDBY_MIN_DELAYS[3];
1497 }
1498 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1499 return mConstants.APP_STANDBY_MIN_DELAYS[2];
1500 }
1501 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1502 return mConstants.APP_STANDBY_MIN_DELAYS[1];
1503 }
1504 else return mConstants.APP_STANDBY_MIN_DELAYS[0];
1505 }
1506
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001507 /**
1508 * Adjusts the alarm delivery time based on the current app standby bucket.
1509 * @param alarm The alarm to adjust
1510 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001511 */
1512 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001513 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001514 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001515 }
1516 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001517 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001518 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001519 alarm.whenElapsed = alarm.expectedWhenElapsed;
1520 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1521 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001522 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001523 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001524 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001525 final long oldWhenElapsed = alarm.whenElapsed;
1526 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1527
Suprabh Shukla75edab12018-01-29 14:09:06 -08001528 final String sourcePackage = alarm.sourcePackage;
1529 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1530 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1531 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1532
1533 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1534 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1535 if (lastElapsed > 0) {
1536 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001537 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001538 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001539 } else {
1540 // app is now eligible to run alarms at the originally requested window.
1541 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001542 alarm.whenElapsed = alarm.expectedWhenElapsed;
1543 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001544 }
1545 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001546 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001547 }
1548
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001549 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1550 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001551 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001552 // The caller has given the time they want this to happen at, however we need
1553 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001554 // bring us out of idle at an earlier time.
1555 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001556 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001557 }
1558 // Add fuzz to make the alarm go off some time before the actual desired time.
1559 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001560 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001561 if (fuzz > 0) {
1562 if (mRandom == null) {
1563 mRandom = new Random();
1564 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001565 final int delta = mRandom.nextInt(fuzz);
1566 a.whenElapsed -= delta;
1567 if (false) {
1568 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1569 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1570 Slog.d(TAG, "Applied fuzz: " + fuzz);
1571 Slog.d(TAG, "Final delta: " + delta);
1572 Slog.d(TAG, "Final when: " + a.whenElapsed);
1573 }
1574 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001575 }
1576
1577 } else if (mPendingIdleUntil != null) {
1578 // We currently have an idle until alarm scheduled; if the new alarm has
1579 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001580 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1581 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1582 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001583 == 0) {
1584 mPendingWhileIdleAlarms.add(a);
1585 return;
1586 }
1587 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001588 if (RECORD_DEVICE_IDLE_ALARMS) {
1589 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1590 IdleDispatchEntry ent = new IdleDispatchEntry();
1591 ent.uid = a.uid;
1592 ent.pkg = a.operation.getCreatorPackage();
1593 ent.tag = a.operation.getTag("");
1594 ent.op = "SET";
1595 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1596 ent.argRealtime = a.whenElapsed;
1597 mAllowWhileIdleDispatches.add(ent);
1598 }
1599 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001600 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001601 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001603 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001604 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001605 }
1606
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001607 boolean needRebatch = false;
1608
1609 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001610 if (RECORD_DEVICE_IDLE_ALARMS) {
1611 if (mPendingIdleUntil == null) {
1612 IdleDispatchEntry ent = new IdleDispatchEntry();
1613 ent.uid = 0;
1614 ent.pkg = "START IDLE";
1615 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1616 mAllowWhileIdleDispatches.add(ent);
1617 }
1618 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001619 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1620 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1621 + " to " + a);
1622 }
1623
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001624 mPendingIdleUntil = a;
1625 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001626 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1627 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1628 mNextWakeFromIdle = a;
1629 // If this wake from idle is earlier than whatever was previously scheduled,
1630 // and we are currently idling, then we need to rebatch alarms in case the idle
1631 // until time needs to be updated.
1632 if (mPendingIdleUntil != null) {
1633 needRebatch = true;
1634 }
1635 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001636 }
1637
1638 if (!rebatching) {
1639 if (DEBUG_VALIDATE) {
1640 if (doValidate && !validateConsistencyLocked()) {
1641 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1642 + " when(hex)=" + Long.toHexString(a.when)
1643 + " whenElapsed=" + a.whenElapsed
1644 + " maxWhenElapsed=" + a.maxWhenElapsed
1645 + " interval=" + a.repeatInterval + " op=" + a.operation
1646 + " flags=0x" + Integer.toHexString(a.flags));
1647 rebatchAllAlarmsLocked(false);
1648 needRebatch = false;
1649 }
1650 }
1651
1652 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001653 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001654 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001655
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001656 rescheduleKernelAlarmsLocked();
1657 updateNextAlarmClockLocked();
1658 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001659 }
1660
Christopher Tate1d99c392017-12-07 16:54:04 -08001661 /**
1662 * System-process internal API
1663 */
1664 private final class LocalService implements AlarmManagerInternal {
1665 @Override
1666 public void removeAlarmsForUid(int uid) {
1667 synchronized (mLock) {
1668 removeLocked(uid);
1669 }
1670 }
1671 }
1672
1673 /**
1674 * Public-facing binder interface
1675 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001676 private final IBinder mService = new IAlarmManager.Stub() {
1677 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001678 public void set(String callingPackage,
1679 int type, long triggerAtTime, long windowLength, long interval, int flags,
1680 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1681 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001682 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001683
1684 // make sure the caller is not lying about which package should be blamed for
1685 // wakelock time spent in alarm delivery
1686 mAppOps.checkPackage(callingUid, callingPackage);
1687
1688 // Repeating alarms must use PendingIntent, not direct listener
1689 if (interval != 0) {
1690 if (directReceiver != null) {
1691 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1692 }
1693 }
1694
Adam Lesinski182f73f2013-12-05 16:48:06 -08001695 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001696 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001697 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001698 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001699 }
1700
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001701 // No incoming callers can request either WAKE_FROM_IDLE or
1702 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1703 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1704 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1705
1706 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1707 // manager when to come out of idle mode, which is only for DeviceIdleController.
1708 if (callingUid != Process.SYSTEM_UID) {
1709 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1710 }
1711
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001712 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001713 if (windowLength == AlarmManager.WINDOW_EXACT) {
1714 flags |= AlarmManager.FLAG_STANDALONE;
1715 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001716
1717 // If this alarm is for an alarm clock, then it must be standalone and we will
1718 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001719 if (alarmClock != null) {
1720 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001721
1722 // If the caller is a core system component or on the user's whitelist, and not calling
1723 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1724 // This means we will allow these alarms to go off as normal even while idle, with no
1725 // timing restrictions.
1726 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001727 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001728 || ((mAppStateTracker != null)
1729 && mAppStateTracker.isUidPowerSaveWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001730 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1731 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001732 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001733
Christopher Tate14a7bb02015-10-01 10:24:31 -07001734 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1735 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001736 }
Christopher Tate89779822012-08-31 14:40:03 -07001737
Adam Lesinski182f73f2013-12-05 16:48:06 -08001738 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001739 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001740 getContext().enforceCallingOrSelfPermission(
1741 "android.permission.SET_TIME",
1742 "setTime");
1743
Greg Hackmann0cab8962014-02-21 16:35:52 -08001744 if (mNativeData == 0) {
1745 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1746 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001747 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001748
1749 synchronized (mLock) {
1750 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001753
1754 @Override
1755 public void setTimeZone(String tz) {
1756 getContext().enforceCallingOrSelfPermission(
1757 "android.permission.SET_TIME_ZONE",
1758 "setTimeZone");
1759
1760 final long oldId = Binder.clearCallingIdentity();
1761 try {
1762 setTimeZoneImpl(tz);
1763 } finally {
1764 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
1766 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001767
Adam Lesinski182f73f2013-12-05 16:48:06 -08001768 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001769 public void remove(PendingIntent operation, IAlarmListener listener) {
1770 if (operation == null && listener == null) {
1771 Slog.w(TAG, "remove() with no intent or listener");
1772 return;
1773 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001774
Christopher Tate14a7bb02015-10-01 10:24:31 -07001775 synchronized (mLock) {
1776 removeLocked(operation, listener);
1777 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001779
Adam Lesinski182f73f2013-12-05 16:48:06 -08001780 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001781 public long getNextWakeFromIdleTime() {
1782 return getNextWakeFromIdleTimeImpl();
1783 }
1784
1785 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001786 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001787 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1788 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1789 "getNextAlarmClock", null);
1790
1791 return getNextAlarmClockImpl(userId);
1792 }
1793
1794 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001795 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001796 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001797
1798 if (args.length > 0 && "--proto".equals(args[0])) {
1799 dumpProto(fd);
1800 } else {
1801 dumpImpl(pw);
1802 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001803 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001804 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001805
Adam Lesinski182f73f2013-12-05 16:48:06 -08001806 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 synchronized (mLock) {
1808 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001809 mConstants.dump(pw);
1810 pw.println();
1811
Makoto Onukie4918212018-02-06 11:30:15 -08001812 if (mAppStateTracker != null) {
1813 mAppStateTracker.dump(pw, " ");
1814 pw.println();
1815 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001816
Suprabh Shukla75edab12018-01-29 14:09:06 -08001817 pw.println(" App Standby Parole: " + mAppStandbyParole);
1818 pw.println();
1819
Christopher Tatee0a22b32013-07-11 14:43:13 -07001820 final long nowRTC = System.currentTimeMillis();
1821 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001822 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001823
Dianne Hackborna750a632015-06-16 17:18:23 -07001824 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001825 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001826 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001827 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001828 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001829 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001830 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1831 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001832 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001833 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1834 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001835 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1836 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001837 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001838 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001839 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001840 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1841 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001842 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001843 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1844 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001845 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001846 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1847 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001848 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001849 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1850 pw.println();
1851 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001852
1853 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1854 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001855 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001856 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001857 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001858 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001859 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001860 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1861 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1862 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001863 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001864
John Spurlock604a5ee2015-06-01 12:27:22 -04001865 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001866 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001867 final TreeSet<Integer> users = new TreeSet<>();
1868 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1869 users.add(mNextAlarmClockForUser.keyAt(i));
1870 }
1871 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1872 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1873 }
1874 for (int user : users) {
1875 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1876 final long time = next != null ? next.getTriggerTime() : 0;
1877 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001878 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001879 pw.print(" pendingSend:"); pw.print(pendingSend);
1880 pw.print(" time:"); pw.print(time);
1881 if (time > 0) {
1882 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1883 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1884 }
1885 pw.println();
1886 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001887 if (mAlarmBatches.size() > 0) {
1888 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001889 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001890 pw.println(mAlarmBatches.size());
1891 for (Batch b : mAlarmBatches) {
1892 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001893 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001894 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001895 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001896 pw.println();
1897 pw.println(" Pending user blocked background alarms: ");
1898 boolean blocked = false;
1899 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1900 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1901 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1902 blocked = true;
1903 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1904 }
1905 }
1906 if (!blocked) {
1907 pw.println(" none");
1908 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001909
Suprabh Shukla75edab12018-01-29 14:09:06 -08001910 pw.println(" mLastAlarmDeliveredForPackage:");
1911 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1912 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1913 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1914 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1915 pw.println();
1916 }
1917 pw.println();
1918
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001919 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001920 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001921 pw.println(" Idle mode state:");
1922 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001923 if (mPendingIdleUntil != null) {
1924 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001925 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001926 } else {
1927 pw.println("null");
1928 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001929 pw.println(" Pending alarms:");
1930 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001931 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001932 if (mNextWakeFromIdle != null) {
1933 pw.println();
1934 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001935 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001936 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001937
1938 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001939 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001940 if (mPendingNonWakeupAlarms.size() > 0) {
1941 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001942 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001943 } else {
1944 pw.println("(none)");
1945 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001946 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001947 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1948 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001949 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001950 pw.print(", max non-interactive time: ");
1951 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1952 pw.println();
1953
1954 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001955 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001956 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1957 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1958 pw.print(" Listener send count: "); pw.println(mListenerCount);
1959 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001960 pw.println();
1961
Christopher Tate7f2a0352015-12-08 10:24:33 -08001962 if (mInFlight.size() > 0) {
1963 pw.println("Outstanding deliveries:");
1964 for (int i = 0; i < mInFlight.size(); i++) {
1965 pw.print(" #"); pw.print(i); pw.print(": ");
1966 pw.println(mInFlight.get(i));
1967 }
1968 pw.println();
1969 }
1970
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001971 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001972 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001973 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08001974 pw.print(" UID ");
1975 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
1976 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001977 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08001978 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
1979 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
1980
1981 final long minInterval = getWhileIdleMinIntervalLocked(uid);
1982 pw.print(" Next allowed:");
1983 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
1984 pw.print(" (");
1985 TimeUtils.formatDuration(minInterval, 0, pw);
1986 pw.print(")");
1987
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001988 pw.println();
1989 }
1990 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08001991
1992 pw.print(" mUseAllowWhileIdleShortTime: [");
1993 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
1994 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
1995 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
1996 pw.print(" ");
1997 }
1998 }
1999 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002000 pw.println();
2001
Dianne Hackborn81038902012-11-26 17:04:09 -08002002 if (mLog.dump(pw, " Recent problems", " ")) {
2003 pw.println();
2004 }
2005
2006 final FilterStats[] topFilters = new FilterStats[10];
2007 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2008 @Override
2009 public int compare(FilterStats lhs, FilterStats rhs) {
2010 if (lhs.aggregateTime < rhs.aggregateTime) {
2011 return 1;
2012 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2013 return -1;
2014 }
2015 return 0;
2016 }
2017 };
2018 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002019 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002020 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2021 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2022 for (int ip=0; ip<uidStats.size(); ip++) {
2023 BroadcastStats bs = uidStats.valueAt(ip);
2024 for (int is=0; is<bs.filterStats.size(); is++) {
2025 FilterStats fs = bs.filterStats.valueAt(is);
2026 int pos = len > 0
2027 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2028 if (pos < 0) {
2029 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002030 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002031 if (pos < topFilters.length) {
2032 int copylen = topFilters.length - pos - 1;
2033 if (copylen > 0) {
2034 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2035 }
2036 topFilters[pos] = fs;
2037 if (len < topFilters.length) {
2038 len++;
2039 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002040 }
2041 }
2042 }
2043 }
2044 if (len > 0) {
2045 pw.println(" Top Alarms:");
2046 for (int i=0; i<len; i++) {
2047 FilterStats fs = topFilters[i];
2048 pw.print(" ");
2049 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2050 TimeUtils.formatDuration(fs.aggregateTime, pw);
2051 pw.print(" running, "); pw.print(fs.numWakeup);
2052 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002053 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2054 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002055 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002056 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002057 pw.println();
2058 }
2059 }
2060
2061 pw.println(" ");
2062 pw.println(" Alarm Stats:");
2063 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002064 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2065 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2066 for (int ip=0; ip<uidStats.size(); ip++) {
2067 BroadcastStats bs = uidStats.valueAt(ip);
2068 pw.print(" ");
2069 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2070 UserHandle.formatUid(pw, bs.mUid);
2071 pw.print(":");
2072 pw.print(bs.mPackageName);
2073 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2074 pw.print(" running, "); pw.print(bs.numWakeup);
2075 pw.println(" wakeups:");
2076 tmpFilters.clear();
2077 for (int is=0; is<bs.filterStats.size(); is++) {
2078 tmpFilters.add(bs.filterStats.valueAt(is));
2079 }
2080 Collections.sort(tmpFilters, comparator);
2081 for (int i=0; i<tmpFilters.size(); i++) {
2082 FilterStats fs = tmpFilters.get(i);
2083 pw.print(" ");
2084 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2085 TimeUtils.formatDuration(fs.aggregateTime, pw);
2086 pw.print(" "); pw.print(fs.numWakeup);
2087 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002088 pw.print(" alarms, last ");
2089 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2090 pw.println(":");
2091 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002092 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002093 pw.println();
2094 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002095 }
2096 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002097 pw.println();
2098 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002099
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002100 if (RECORD_DEVICE_IDLE_ALARMS) {
2101 pw.println();
2102 pw.println(" Allow while idle dispatches:");
2103 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2104 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2105 pw.print(" ");
2106 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2107 pw.print(": ");
2108 UserHandle.formatUid(pw, ent.uid);
2109 pw.print(":");
2110 pw.println(ent.pkg);
2111 if (ent.op != null) {
2112 pw.print(" ");
2113 pw.print(ent.op);
2114 pw.print(" / ");
2115 pw.print(ent.tag);
2116 if (ent.argRealtime != 0) {
2117 pw.print(" (");
2118 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2119 pw.print(")");
2120 }
2121 pw.println();
2122 }
2123 }
2124 }
2125
Christopher Tate18a75f12013-07-01 18:18:59 -07002126 if (WAKEUP_STATS) {
2127 pw.println();
2128 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002129 long last = -1;
2130 for (WakeupEvent event : mRecentWakeups) {
2131 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2132 pw.print('|');
2133 if (last < 0) {
2134 pw.print('0');
2135 } else {
2136 pw.print(event.when - last);
2137 }
2138 last = event.when;
2139 pw.print('|'); pw.print(event.uid);
2140 pw.print('|'); pw.print(event.action);
2141 pw.println();
2142 }
2143 pw.println();
2144 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002145 }
2146 }
2147
Kweku Adams61e03292017-10-19 14:27:12 -07002148 void dumpProto(FileDescriptor fd) {
2149 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2150
2151 synchronized (mLock) {
2152 final long nowRTC = System.currentTimeMillis();
2153 final long nowElapsed = SystemClock.elapsedRealtime();
2154 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
2155 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
2156 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
2157 mLastTimeChangeClockTime);
2158 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2159 mLastTimeChangeRealtime);
2160
2161 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2162
Makoto Onukie4918212018-02-06 11:30:15 -08002163 if (mAppStateTracker != null) {
2164 mAppStateTracker.dumpProto(proto,
2165 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
2166 }
Kweku Adams61e03292017-10-19 14:27:12 -07002167
2168 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2169 if (!mInteractive) {
2170 // Durations
2171 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2172 nowElapsed - mNonInteractiveStartTime);
2173 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2174 currentNonWakeupFuzzLocked(nowElapsed));
2175 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2176 nowElapsed - mLastAlarmDeliveryTime);
2177 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2178 nowElapsed - mNextNonWakeupDeliveryTime);
2179 }
2180
2181 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2182 mNextNonWakeup - nowElapsed);
2183 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2184 mNextWakeup - nowElapsed);
2185 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2186 nowElapsed - mLastWakeup);
2187 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2188 nowElapsed - mLastWakeupSet);
2189 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002190
2191 final TreeSet<Integer> users = new TreeSet<>();
2192 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2193 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2194 users.add(mNextAlarmClockForUser.keyAt(i));
2195 }
2196 final int pendingSendNextAlarmClockChangedForUserSize =
2197 mPendingSendNextAlarmClockChangedForUser.size();
2198 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2199 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2200 }
2201 for (int user : users) {
2202 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2203 final long time = next != null ? next.getTriggerTime() : 0;
2204 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2205 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2206 proto.write(AlarmClockMetadataProto.USER, user);
2207 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2208 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2209 proto.end(aToken);
2210 }
2211 for (Batch b : mAlarmBatches) {
2212 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2213 nowElapsed, nowRTC);
2214 }
2215 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2216 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2217 if (blockedAlarms != null) {
2218 for (Alarm a : blockedAlarms) {
2219 a.writeToProto(proto,
2220 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2221 nowElapsed, nowRTC);
2222 }
2223 }
2224 }
2225 if (mPendingIdleUntil != null) {
2226 mPendingIdleUntil.writeToProto(
2227 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2228 }
2229 for (Alarm a : mPendingWhileIdleAlarms) {
2230 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2231 nowElapsed, nowRTC);
2232 }
2233 if (mNextWakeFromIdle != null) {
2234 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2235 nowElapsed, nowRTC);
2236 }
2237
2238 for (Alarm a : mPendingNonWakeupAlarms) {
2239 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2240 nowElapsed, nowRTC);
2241 }
2242
2243 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2244 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2245 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2246 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2247 mNonInteractiveTime);
2248
2249 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2250 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2251 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2252 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2253 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2254
2255 for (InFlight f : mInFlight) {
2256 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2257 }
2258
Kweku Adams61e03292017-10-19 14:27:12 -07002259 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2260 final long token = proto.start(
2261 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002262 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2263 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2264
2265 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID, uid);
2266 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2267 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
2268 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002269 proto.end(token);
2270 }
2271
Makoto Onukiadb50d82018-01-29 16:20:30 -08002272 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2273 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2274 proto.write(AlarmManagerServiceProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
2275 mUseAllowWhileIdleShortTime.keyAt(i));
2276 }
2277 }
2278
Kweku Adams61e03292017-10-19 14:27:12 -07002279 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2280
2281 final FilterStats[] topFilters = new FilterStats[10];
2282 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2283 @Override
2284 public int compare(FilterStats lhs, FilterStats rhs) {
2285 if (lhs.aggregateTime < rhs.aggregateTime) {
2286 return 1;
2287 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2288 return -1;
2289 }
2290 return 0;
2291 }
2292 };
2293 int len = 0;
2294 // Get the top 10 FilterStats, ordered by aggregateTime.
2295 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2296 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2297 for (int ip = 0; ip < uidStats.size(); ++ip) {
2298 BroadcastStats bs = uidStats.valueAt(ip);
2299 for (int is = 0; is < bs.filterStats.size(); ++is) {
2300 FilterStats fs = bs.filterStats.valueAt(is);
2301 int pos = len > 0
2302 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2303 if (pos < 0) {
2304 pos = -pos - 1;
2305 }
2306 if (pos < topFilters.length) {
2307 int copylen = topFilters.length - pos - 1;
2308 if (copylen > 0) {
2309 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2310 }
2311 topFilters[pos] = fs;
2312 if (len < topFilters.length) {
2313 len++;
2314 }
2315 }
2316 }
2317 }
2318 }
2319 for (int i = 0; i < len; ++i) {
2320 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2321 FilterStats fs = topFilters[i];
2322
2323 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2324 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2325 fs.mBroadcastStats.mPackageName);
2326 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2327
2328 proto.end(token);
2329 }
2330
2331 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2332 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2333 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2334 for (int ip = 0; ip < uidStats.size(); ++ip) {
2335 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2336
2337 BroadcastStats bs = uidStats.valueAt(ip);
2338 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2339
2340 // uidStats is an ArrayMap, which we can't sort.
2341 tmpFilters.clear();
2342 for (int is = 0; is < bs.filterStats.size(); ++is) {
2343 tmpFilters.add(bs.filterStats.valueAt(is));
2344 }
2345 Collections.sort(tmpFilters, comparator);
2346 for (FilterStats fs : tmpFilters) {
2347 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2348 }
2349
2350 proto.end(token);
2351 }
2352 }
2353
2354 if (RECORD_DEVICE_IDLE_ALARMS) {
2355 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2356 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2357 final long token = proto.start(
2358 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2359
2360 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2361 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2362 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2363 proto.write(IdleDispatchEntryProto.OP, ent.op);
2364 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2365 ent.elapsedRealtime);
2366 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2367
2368 proto.end(token);
2369 }
2370 }
2371
2372 if (WAKEUP_STATS) {
2373 for (WakeupEvent event : mRecentWakeups) {
2374 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2375 proto.write(WakeupEventProto.UID, event.uid);
2376 proto.write(WakeupEventProto.ACTION, event.action);
2377 proto.write(WakeupEventProto.WHEN, event.when);
2378 proto.end(token);
2379 }
2380 }
2381 }
2382
2383 proto.flush();
2384 }
2385
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002386 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002387 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2388 PrintWriter pw = new PrintWriter(bs);
2389 final long nowRTC = System.currentTimeMillis();
2390 final long nowELAPSED = SystemClock.elapsedRealtime();
2391 final int NZ = mAlarmBatches.size();
2392 for (int iz = 0; iz < NZ; iz++) {
2393 Batch bz = mAlarmBatches.get(iz);
2394 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002395 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002396 pw.flush();
2397 Slog.v(TAG, bs.toString());
2398 bs.reset();
2399 }
2400 }
2401
2402 private boolean validateConsistencyLocked() {
2403 if (DEBUG_VALIDATE) {
2404 long lastTime = Long.MIN_VALUE;
2405 final int N = mAlarmBatches.size();
2406 for (int i = 0; i < N; i++) {
2407 Batch b = mAlarmBatches.get(i);
2408 if (b.start >= lastTime) {
2409 // duplicate start times are okay because of standalone batches
2410 lastTime = b.start;
2411 } else {
2412 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002413 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2414 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002415 return false;
2416 }
2417 }
2418 }
2419 return true;
2420 }
2421
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002422 private Batch findFirstWakeupBatchLocked() {
2423 final int N = mAlarmBatches.size();
2424 for (int i = 0; i < N; i++) {
2425 Batch b = mAlarmBatches.get(i);
2426 if (b.hasWakeups()) {
2427 return b;
2428 }
2429 }
2430 return null;
2431 }
2432
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002433 long getNextWakeFromIdleTimeImpl() {
2434 synchronized (mLock) {
2435 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2436 }
2437 }
2438
2439 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002440 synchronized (mLock) {
2441 return mNextAlarmClockForUser.get(userId);
2442 }
2443 }
2444
2445 /**
2446 * Recomputes the next alarm clock for all users.
2447 */
2448 private void updateNextAlarmClockLocked() {
2449 if (!mNextAlarmClockMayChange) {
2450 return;
2451 }
2452 mNextAlarmClockMayChange = false;
2453
Jose Lima235510e2014-08-13 12:50:01 -07002454 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002455 nextForUser.clear();
2456
2457 final int N = mAlarmBatches.size();
2458 for (int i = 0; i < N; i++) {
2459 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2460 final int M = alarms.size();
2461
2462 for (int j = 0; j < M; j++) {
2463 Alarm a = alarms.get(j);
2464 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002465 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002466 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002467
2468 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002469 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002470 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002471 " for user " + userId);
2472 }
2473
2474 // Alarms and batches are sorted by time, no need to compare times here.
2475 if (nextForUser.get(userId) == null) {
2476 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002477 } else if (a.alarmClock.equals(current)
2478 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2479 // same/earlier time and it's the one we cited before, so stick with it
2480 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002481 }
2482 }
2483 }
2484 }
2485
2486 // Update mNextAlarmForUser with new values.
2487 final int NN = nextForUser.size();
2488 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002489 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002490 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002491 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002492 if (!newAlarm.equals(currentAlarm)) {
2493 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2494 }
2495 }
2496
2497 // Remove users without any alarm clocks scheduled.
2498 final int NNN = mNextAlarmClockForUser.size();
2499 for (int i = NNN - 1; i >= 0; i--) {
2500 int userId = mNextAlarmClockForUser.keyAt(i);
2501 if (nextForUser.get(userId) == null) {
2502 updateNextAlarmInfoForUserLocked(userId, null);
2503 }
2504 }
2505 }
2506
Jose Lima235510e2014-08-13 12:50:01 -07002507 private void updateNextAlarmInfoForUserLocked(int userId,
2508 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002509 if (alarmClock != null) {
2510 if (DEBUG_ALARM_CLOCK) {
2511 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002512 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002513 }
2514 mNextAlarmClockForUser.put(userId, alarmClock);
2515 } else {
2516 if (DEBUG_ALARM_CLOCK) {
2517 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2518 }
2519 mNextAlarmClockForUser.remove(userId);
2520 }
2521
2522 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2523 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2524 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2525 }
2526
2527 /**
2528 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2529 * for which alarm clocks have changed since the last call to this.
2530 *
2531 * Do not call with a lock held. Only call from mHandler's thread.
2532 *
2533 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2534 */
2535 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002536 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002537 pendingUsers.clear();
2538
2539 synchronized (mLock) {
2540 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2541 for (int i = 0; i < N; i++) {
2542 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2543 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2544 }
2545 mPendingSendNextAlarmClockChangedForUser.clear();
2546 }
2547
2548 final int N = pendingUsers.size();
2549 for (int i = 0; i < N; i++) {
2550 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002551 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002552 Settings.System.putStringForUser(getContext().getContentResolver(),
2553 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002554 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002555 userId);
2556
2557 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2558 new UserHandle(userId));
2559 }
2560 }
2561
2562 /**
2563 * Formats an alarm like platform/packages/apps/DeskClock used to.
2564 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002565 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2566 int userId) {
2567 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002568 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2569 return (info == null) ? "" :
2570 DateFormat.format(pattern, info.getTriggerTime()).toString();
2571 }
2572
Adam Lesinski182f73f2013-12-05 16:48:06 -08002573 void rescheduleKernelAlarmsLocked() {
2574 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2575 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002576 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002577 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002578 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002579 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002580 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002581 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002582 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002583 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002584 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002585 if (firstBatch != firstWakeup) {
2586 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002587 }
2588 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002589 if (mPendingNonWakeupAlarms.size() > 0) {
2590 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2591 nextNonWakeup = mNextNonWakeupDeliveryTime;
2592 }
2593 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002594 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002595 mNextNonWakeup = nextNonWakeup;
2596 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2597 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002598 }
2599
Christopher Tate14a7bb02015-10-01 10:24:31 -07002600 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002601 if (operation == null && directReceiver == null) {
2602 if (localLOGV) {
2603 Slog.w(TAG, "requested remove() of null operation",
2604 new RuntimeException("here"));
2605 }
2606 return;
2607 }
2608
Adam Lesinski182f73f2013-12-05 16:48:06 -08002609 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002610 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002611 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2612 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002613 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002614 if (b.size() == 0) {
2615 mAlarmBatches.remove(i);
2616 }
2617 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002618 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002619 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002620 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2621 mPendingWhileIdleAlarms.remove(i);
2622 }
2623 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002624 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2625 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2626 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2627 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2628 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2629 alarmsForUid.remove(j);
2630 }
2631 }
2632 if (alarmsForUid.size() == 0) {
2633 mPendingBackgroundAlarms.removeAt(i);
2634 }
2635 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002636 if (didRemove) {
2637 if (DEBUG_BATCH) {
2638 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2639 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002640 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002641 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002642 mPendingIdleUntil = null;
2643 restorePending = true;
2644 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002645 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002646 mNextWakeFromIdle = null;
2647 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002648 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002649 if (restorePending) {
2650 restorePendingWhileIdleAlarmsLocked();
2651 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002652 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002653 }
2654 }
2655
Christopher Tate1d99c392017-12-07 16:54:04 -08002656 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002657 if (uid == Process.SYSTEM_UID) {
2658 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2659 return;
2660 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002661 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002662 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002663 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2664 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002665 didRemove |= b.remove(whichAlarms);
2666 if (b.size() == 0) {
2667 mAlarmBatches.remove(i);
2668 }
2669 }
2670 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2671 final Alarm a = mPendingWhileIdleAlarms.get(i);
2672 if (a.uid == uid) {
2673 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2674 mPendingWhileIdleAlarms.remove(i);
2675 }
2676 }
2677 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2678 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2679 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2680 if (alarmsForUid.get(j).uid == uid) {
2681 alarmsForUid.remove(j);
2682 }
2683 }
2684 if (alarmsForUid.size() == 0) {
2685 mPendingBackgroundAlarms.removeAt(i);
2686 }
2687 }
2688 if (didRemove) {
2689 if (DEBUG_BATCH) {
2690 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2691 }
2692 rebatchAllAlarmsLocked(true);
2693 rescheduleKernelAlarmsLocked();
2694 updateNextAlarmClockLocked();
2695 }
2696 }
2697
2698 void removeLocked(final String packageName) {
2699 if (packageName == null) {
2700 if (localLOGV) {
2701 Slog.w(TAG, "requested remove() of null packageName",
2702 new RuntimeException("here"));
2703 }
2704 return;
2705 }
2706
2707 boolean didRemove = false;
2708 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002709 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002710 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2711 Batch b = mAlarmBatches.get(i);
2712 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002713 if (b.size() == 0) {
2714 mAlarmBatches.remove(i);
2715 }
2716 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002717 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2718 if (oldHasTick != newHasTick) {
2719 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2720 }
2721
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002722 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002723 final Alarm a = mPendingWhileIdleAlarms.get(i);
2724 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002725 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2726 mPendingWhileIdleAlarms.remove(i);
2727 }
2728 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002729 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2730 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2731 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2732 if (alarmsForUid.get(j).matches(packageName)) {
2733 alarmsForUid.remove(j);
2734 }
2735 }
2736 if (alarmsForUid.size() == 0) {
2737 mPendingBackgroundAlarms.removeAt(i);
2738 }
2739 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002740 if (didRemove) {
2741 if (DEBUG_BATCH) {
2742 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2743 }
2744 rebatchAllAlarmsLocked(true);
2745 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002746 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002747 }
2748 }
2749
Christopher Tate1d99c392017-12-07 16:54:04 -08002750 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002751 if (uid == Process.SYSTEM_UID) {
2752 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2753 return;
2754 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002755 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002756 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2757 try {
2758 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2759 uid, a.packageName)) {
2760 return true;
2761 }
2762 } catch (RemoteException e) { /* fall through */}
2763 return false;
2764 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002765 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2766 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002767 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002768 if (b.size() == 0) {
2769 mAlarmBatches.remove(i);
2770 }
2771 }
2772 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2773 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002774 if (a.uid == uid) {
2775 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2776 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002777 }
2778 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002779 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2780 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2781 mPendingBackgroundAlarms.removeAt(i);
2782 }
2783 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002784 if (didRemove) {
2785 if (DEBUG_BATCH) {
2786 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2787 }
2788 rebatchAllAlarmsLocked(true);
2789 rescheduleKernelAlarmsLocked();
2790 updateNextAlarmClockLocked();
2791 }
2792 }
2793
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002795 if (userHandle == UserHandle.USER_SYSTEM) {
2796 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2797 return;
2798 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002799 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002800 final Predicate<Alarm> whichAlarms =
2801 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002802 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2803 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002804 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002805 if (b.size() == 0) {
2806 mAlarmBatches.remove(i);
2807 }
2808 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002809 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002810 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002811 == userHandle) {
2812 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2813 mPendingWhileIdleAlarms.remove(i);
2814 }
2815 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002816 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2817 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2818 mPendingBackgroundAlarms.removeAt(i);
2819 }
2820 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002821 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2822 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2823 mLastAllowWhileIdleDispatch.removeAt(i);
2824 }
2825 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002826
2827 if (didRemove) {
2828 if (DEBUG_BATCH) {
2829 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2830 }
2831 rebatchAllAlarmsLocked(true);
2832 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002833 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002834 }
2835 }
2836
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002837 void interactiveStateChangedLocked(boolean interactive) {
2838 if (mInteractive != interactive) {
2839 mInteractive = interactive;
2840 final long nowELAPSED = SystemClock.elapsedRealtime();
2841 if (interactive) {
2842 if (mPendingNonWakeupAlarms.size() > 0) {
2843 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2844 mTotalDelayTime += thisDelayTime;
2845 if (mMaxDelayTime < thisDelayTime) {
2846 mMaxDelayTime = thisDelayTime;
2847 }
2848 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2849 mPendingNonWakeupAlarms.clear();
2850 }
2851 if (mNonInteractiveStartTime > 0) {
2852 long dur = nowELAPSED - mNonInteractiveStartTime;
2853 if (dur > mNonInteractiveTime) {
2854 mNonInteractiveTime = dur;
2855 }
2856 }
2857 } else {
2858 mNonInteractiveStartTime = nowELAPSED;
2859 }
2860 }
2861 }
2862
Adam Lesinski182f73f2013-12-05 16:48:06 -08002863 boolean lookForPackageLocked(String packageName) {
2864 for (int i = 0; i < mAlarmBatches.size(); i++) {
2865 Batch b = mAlarmBatches.get(i);
2866 if (b.hasPackage(packageName)) {
2867 return true;
2868 }
2869 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002870 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002871 final Alarm a = mPendingWhileIdleAlarms.get(i);
2872 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002873 return true;
2874 }
2875 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002876 return false;
2877 }
2878
2879 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002880 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002881 // The kernel never triggers alarms with negative wakeup times
2882 // so we ensure they are positive.
2883 long alarmSeconds, alarmNanoseconds;
2884 if (when < 0) {
2885 alarmSeconds = 0;
2886 alarmNanoseconds = 0;
2887 } else {
2888 alarmSeconds = when / 1000;
2889 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2890 }
Kweku Adams61e03292017-10-19 14:27:12 -07002891
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002892 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002893 } else {
2894 Message msg = Message.obtain();
2895 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002896
Adam Lesinski182f73f2013-12-05 16:48:06 -08002897 mHandler.removeMessages(ALARM_EVENT);
2898 mHandler.sendMessageAtTime(msg, when);
2899 }
2900 }
2901
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002902 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002903 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 for (int i=list.size()-1; i>=0; i--) {
2905 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002906 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2907 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002908 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
2910 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002911
2912 private static final String labelForType(int type) {
2913 switch (type) {
2914 case RTC: return "RTC";
2915 case RTC_WAKEUP : return "RTC_WAKEUP";
2916 case ELAPSED_REALTIME : return "ELAPSED";
2917 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002918 }
2919 return "--unknown--";
2920 }
2921
2922 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002923 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002924 for (int i=list.size()-1; i>=0; i--) {
2925 Alarm a = list.get(i);
2926 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002927 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2928 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002929 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002930 }
2931 }
2932
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002933 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002934 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002935 if (alarm.alarmClock != null) {
2936 // Don't block alarm clocks
2937 return false;
2938 }
2939 if (alarm.operation != null
2940 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2941 // Don't block starting foreground components
2942 return false;
2943 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002944 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002945 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08002946 return (mAppStateTracker != null) &&
2947 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage, allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002948 }
2949
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002950 private native long init();
2951 private native void close(long nativeData);
2952 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2953 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002954 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002955 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956
Makoto Onukiadb50d82018-01-29 16:20:30 -08002957 private long getWhileIdleMinIntervalLocked(int uid) {
2958 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08002959 final boolean ebs = (mAppStateTracker != null)
2960 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08002961 if (!dozing && !ebs) {
2962 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2963 }
2964 if (dozing) {
2965 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2966 }
2967 if (mUseAllowWhileIdleShortTime.get(uid)) {
2968 // if the last allow-while-idle went off while uid was fg, or the uid
2969 // recently came into fg, don't block the alarm for long.
2970 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2971 }
2972 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2973 }
2974
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002975 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002976 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002977 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002978 // batches are temporally sorted, so we need only pull from the
2979 // start of the list until we either empty it or hit a batch
2980 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002981 while (mAlarmBatches.size() > 0) {
2982 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002983 if (batch.start > nowELAPSED) {
2984 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 break;
2986 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002987
Christopher Tatee0a22b32013-07-11 14:43:13 -07002988 // We will (re)schedule some alarms now; don't let that interfere
2989 // with delivery of this current batch
2990 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002991
Christopher Tatee0a22b32013-07-11 14:43:13 -07002992 final int N = batch.size();
2993 for (int i = 0; i < N; i++) {
2994 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002995
2996 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2997 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2998 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002999 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003000 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003001 if (nowELAPSED < minTime) {
3002 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3003 // alarm went off for this app. Reschedule the alarm to be in the
3004 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003005 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003006 if (alarm.maxWhenElapsed < minTime) {
3007 alarm.maxWhenElapsed = minTime;
3008 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003009 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003010 if (RECORD_DEVICE_IDLE_ALARMS) {
3011 IdleDispatchEntry ent = new IdleDispatchEntry();
3012 ent.uid = alarm.uid;
3013 ent.pkg = alarm.operation.getCreatorPackage();
3014 ent.tag = alarm.operation.getTag("");
3015 ent.op = "RESCHEDULE";
3016 ent.elapsedRealtime = nowELAPSED;
3017 ent.argRealtime = lastTime;
3018 mAllowWhileIdleDispatches.add(ent);
3019 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003020 setImplLocked(alarm, true, false);
3021 continue;
3022 }
3023 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003024 if (isBackgroundRestricted(alarm)) {
3025 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3026 if (DEBUG_BG_LIMIT) {
3027 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3028 }
3029 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3030 if (alarmsForUid == null) {
3031 alarmsForUid = new ArrayList<>();
3032 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3033 }
3034 alarmsForUid.add(alarm);
3035 continue;
3036 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003037
Christopher Tatee0a22b32013-07-11 14:43:13 -07003038 alarm.count = 1;
3039 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003040 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3041 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003042 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003043 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003044 if (mPendingIdleUntil == alarm) {
3045 mPendingIdleUntil = null;
3046 rebatchAllAlarmsLocked(false);
3047 restorePendingWhileIdleAlarmsLocked();
3048 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003049 if (mNextWakeFromIdle == alarm) {
3050 mNextWakeFromIdle = null;
3051 rebatchAllAlarmsLocked(false);
3052 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003053
3054 // Recurring alarms may have passed several alarm intervals while the
3055 // phone was asleep or off, so pass a trigger count when sending them.
3056 if (alarm.repeatInterval > 0) {
3057 // this adjustment will be zero if we're late by
3058 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003059 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003060
3061 // Also schedule its next recurrence
3062 final long delta = alarm.count * alarm.repeatInterval;
3063 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003064 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003065 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003066 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3067 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003069
Christopher Tate864d42e2014-12-02 11:48:53 -08003070 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003071 hasWakeup = true;
3072 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003073
3074 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3075 if (alarm.alarmClock != null) {
3076 mNextAlarmClockMayChange = true;
3077 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003079 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003080
Christopher Tate1590f1e2014-10-02 17:27:57 -07003081 // This is a new alarm delivery set; bump the sequence number to indicate that
3082 // all apps' alarm delivery classes should be recalculated.
3083 mCurrentSeq++;
3084 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003085 Collections.sort(triggerList, mAlarmDispatchComparator);
3086
3087 if (localLOGV) {
3088 for (int i=0; i<triggerList.size(); i++) {
3089 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3090 }
3091 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003092
3093 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003094 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003095
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003096 /**
3097 * This Comparator sorts Alarms into increasing time order.
3098 */
3099 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3100 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003101 long when1 = a1.whenElapsed;
3102 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003103 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 return 1;
3105 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003106 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003107 return -1;
3108 }
3109 return 0;
3110 }
3111 }
Kweku Adams61e03292017-10-19 14:27:12 -07003112
Makoto Onuki2206af32017-11-21 16:25:35 -08003113 @VisibleForTesting
3114 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003115 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003116 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003117 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003118 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003119 public final IAlarmListener listener;
3120 public final String listenerTag;
3121 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003122 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003123 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003124 public final AlarmManager.AlarmClockInfo alarmClock;
3125 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003126 public final int creatorUid;
3127 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003128 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003129 public int count;
3130 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003131 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003132 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003133 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003134 // Expected alarm expiry time before app standby deferring is applied.
3135 public long expectedWhenElapsed;
3136 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003137 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003138 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003139
Christopher Tate3e04b472013-10-21 17:51:31 -07003140 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003141 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3142 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3143 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003144 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003145 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003146 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3147 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003148 when = _when;
3149 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003150 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003151 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003152 maxWhenElapsed = _maxWhen;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003153 expectedMaxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003154 repeatInterval = _interval;
3155 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003156 listener = _rec;
3157 listenerTag = _listenerTag;
3158 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003159 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003160 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003161 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003162 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003163 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003164 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003165 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003167
Christopher Tate14a7bb02015-10-01 10:24:31 -07003168 public static String makeTag(PendingIntent pi, String tag, int type) {
3169 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3170 ? "*walarm*:" : "*alarm*:";
3171 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3172 }
3173
3174 public WakeupEvent makeWakeupEvent(long nowRTC) {
3175 return new WakeupEvent(nowRTC, creatorUid,
3176 (operation != null)
3177 ? operation.getIntent().getAction()
3178 : ("<listener>:" + listenerTag));
3179 }
3180
3181 // Returns true if either matches
3182 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3183 return (operation != null)
3184 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003185 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003186 }
3187
3188 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003189 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003190 }
3191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003192 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003193 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003194 StringBuilder sb = new StringBuilder(128);
3195 sb.append("Alarm{");
3196 sb.append(Integer.toHexString(System.identityHashCode(this)));
3197 sb.append(" type ");
3198 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003199 sb.append(" when ");
3200 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003201 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003202 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003203 sb.append('}');
3204 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003205 }
3206
Kweku Adams61e03292017-10-19 14:27:12 -07003207 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003208 SimpleDateFormat sdf) {
3209 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003210 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003211 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003212 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3213 expectedWhenElapsed, nowELAPSED, pw);
3214 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3215 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003216 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3217 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003218 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003219 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003220 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003221 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003222 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003223 }
3224 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003225 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003226 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003227 pw.print(" count="); pw.print(count);
3228 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003229 if (alarmClock != null) {
3230 pw.print(prefix); pw.println("Alarm clock:");
3231 pw.print(prefix); pw.print(" triggerTime=");
3232 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3233 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3234 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003235 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003236 if (listener != null) {
3237 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 }
Kweku Adams61e03292017-10-19 14:27:12 -07003240
3241 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3242 long nowRTC) {
3243 final long token = proto.start(fieldId);
3244
3245 proto.write(AlarmProto.TAG, statsTag);
3246 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003247 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003248 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3249 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3250 proto.write(AlarmProto.COUNT, count);
3251 proto.write(AlarmProto.FLAGS, flags);
3252 if (alarmClock != null) {
3253 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3254 }
3255 if (operation != null) {
3256 operation.writeToProto(proto, AlarmProto.OPERATION);
3257 }
3258 if (listener != null) {
3259 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3260 }
3261
3262 proto.end(token);
3263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003265
Christopher Tatee0a22b32013-07-11 14:43:13 -07003266 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3267 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003268 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3269 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003270 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003271 break;
3272 }
3273
Christopher Tatee0a22b32013-07-11 14:43:13 -07003274 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003275 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3276 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003277 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003278 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003279 }
3280 }
3281
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003282 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3283 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3284 if (timeSinceOn < 5*60*1000) {
3285 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3286 return 2*60*1000;
3287 } else if (timeSinceOn < 30*60*1000) {
3288 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3289 return 15*60*1000;
3290 } else {
3291 // Otherwise, we will delay by at most an hour.
3292 return 60*60*1000;
3293 }
3294 }
3295
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003296 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003297 if (duration < 15*60*1000) {
3298 // If the duration until the time is less than 15 minutes, the maximum fuzz
3299 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003300 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003301 } else if (duration < 90*60*1000) {
3302 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3303 return 15*60*1000;
3304 } else {
3305 // Otherwise, we will fuzz by at most half an hour.
3306 return 30*60*1000;
3307 }
3308 }
3309
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003310 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3311 if (mInteractive) {
3312 return false;
3313 }
3314 if (mLastAlarmDeliveryTime <= 0) {
3315 return false;
3316 }
minho.choo649acab2014-12-12 16:13:55 +09003317 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003318 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3319 // and the next delivery time is in the past, then just deliver them all. This
3320 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3321 return false;
3322 }
3323 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3324 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3325 }
3326
3327 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3328 mLastAlarmDeliveryTime = nowELAPSED;
3329 for (int i=0; i<triggerList.size(); i++) {
3330 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003331 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003332 if (alarm.wakeup) {
3333 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3334 } else {
3335 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3336 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003337 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003338 if (localLOGV) {
3339 Slog.v(TAG, "sending alarm " + alarm);
3340 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003341 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003342 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3343 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003344 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003345 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003346 } catch (RuntimeException e) {
3347 Slog.w(TAG, "Failure sending alarm.", e);
3348 }
Tim Murray175c0f92017-11-28 15:01:04 -08003349 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003350 }
3351 }
3352
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003353 private boolean isExemptFromAppStandby(Alarm a) {
3354 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3355 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3356 }
3357
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003358 private class AlarmThread extends Thread
3359 {
3360 public AlarmThread()
3361 {
3362 super("AlarmManager");
3363 }
Kweku Adams61e03292017-10-19 14:27:12 -07003364
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003365 public void run()
3366 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003367 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3368
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 while (true)
3370 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003371 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003372 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003373
3374 triggerList.clear();
3375
Dianne Hackbornc3527222015-05-13 14:03:20 -07003376 final long nowRTC = System.currentTimeMillis();
3377 final long nowELAPSED = SystemClock.elapsedRealtime();
3378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003380 // The kernel can give us spurious time change notifications due to
3381 // small adjustments it makes internally; we want to filter those out.
3382 final long lastTimeChangeClockTime;
3383 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003384 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003385 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3386 expectedClockTime = lastTimeChangeClockTime
3387 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003388 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003389 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3390 || nowRTC > (expectedClockTime+1000)) {
3391 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003392 // let's do it!
3393 if (DEBUG_BATCH) {
3394 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3395 }
3396 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003397 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003398 rebatchAllAlarms();
3399 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003400 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003401 synchronized (mLock) {
3402 mNumTimeChanged++;
3403 mLastTimeChangeClockTime = nowRTC;
3404 mLastTimeChangeRealtime = nowELAPSED;
3405 }
3406 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3407 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003408 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003409 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3410 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003411 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3412
3413 // The world has changed on us, so we need to re-evaluate alarms
3414 // regardless of whether the kernel has told us one went off.
3415 result |= IS_WAKEUP_MASK;
3416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003418
Dianne Hackbornc3527222015-05-13 14:03:20 -07003419 if (result != TIME_CHANGED_MASK) {
3420 // If this was anything besides just a time change, then figure what if
3421 // anything to do about alarms.
3422 synchronized (mLock) {
3423 if (localLOGV) Slog.v(
3424 TAG, "Checking for alarms... rtc=" + nowRTC
3425 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003426
Dianne Hackbornc3527222015-05-13 14:03:20 -07003427 if (WAKEUP_STATS) {
3428 if ((result & IS_WAKEUP_MASK) != 0) {
3429 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3430 int n = 0;
3431 for (WakeupEvent event : mRecentWakeups) {
3432 if (event.when > newEarliest) break;
3433 n++; // number of now-stale entries at the list head
3434 }
3435 for (int i = 0; i < n; i++) {
3436 mRecentWakeups.remove();
3437 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003438
Dianne Hackbornc3527222015-05-13 14:03:20 -07003439 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003440 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003441 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003442
3443 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3444 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3445 // if there are no wakeup alarms and the screen is off, we can
3446 // delay what we have so far until the future.
3447 if (mPendingNonWakeupAlarms.size() == 0) {
3448 mStartCurrentDelayTime = nowELAPSED;
3449 mNextNonWakeupDeliveryTime = nowELAPSED
3450 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3451 }
3452 mPendingNonWakeupAlarms.addAll(triggerList);
3453 mNumDelayedAlarms += triggerList.size();
3454 rescheduleKernelAlarmsLocked();
3455 updateNextAlarmClockLocked();
3456 } else {
3457 // now deliver the alarm intents; if there are pending non-wakeup
3458 // alarms, we need to merge them in to the list. note we don't
3459 // just deliver them first because we generally want non-wakeup
3460 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003461 if (mPendingNonWakeupAlarms.size() > 0) {
3462 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3463 triggerList.addAll(mPendingNonWakeupAlarms);
3464 Collections.sort(triggerList, mAlarmDispatchComparator);
3465 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3466 mTotalDelayTime += thisDelayTime;
3467 if (mMaxDelayTime < thisDelayTime) {
3468 mMaxDelayTime = thisDelayTime;
3469 }
3470 mPendingNonWakeupAlarms.clear();
3471 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003472 final ArraySet<Pair<String, Integer>> triggerPackages =
3473 new ArraySet<>();
3474 for (int i = 0; i < triggerList.size(); i++) {
3475 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003476 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003477 triggerPackages.add(Pair.create(
3478 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003479 }
3480 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003481 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003482 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3483 rescheduleKernelAlarmsLocked();
3484 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003485 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003486 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003487
3488 } else {
3489 // Just in case -- even though no wakeup flag was set, make sure
3490 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003491 synchronized (mLock) {
3492 rescheduleKernelAlarmsLocked();
3493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 }
3495 }
3496 }
3497 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003498
David Christieebe51fc2013-07-26 13:23:29 -07003499 /**
3500 * Attribute blame for a WakeLock.
3501 * @param pi PendingIntent to attribute blame to if ws is null.
3502 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003503 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003504 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003505 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003506 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003507 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003508 final boolean unimportant = pi == mTimeTickSender;
3509 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003510 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003511 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003512 } else {
3513 mWakeLock.setHistoryTag(null);
3514 }
3515 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003516 if (ws != null) {
3517 mWakeLock.setWorkSource(ws);
3518 return;
3519 }
3520
Christopher Tate14a7bb02015-10-01 10:24:31 -07003521 final int uid = (knownUid >= 0)
3522 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003523 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003524 if (uid >= 0) {
3525 mWakeLock.setWorkSource(new WorkSource(uid));
3526 return;
3527 }
3528 } catch (Exception e) {
3529 }
3530
3531 // Something went wrong; fall back to attributing the lock to the OS
3532 mWakeLock.setWorkSource(null);
3533 }
3534
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003535 private class AlarmHandler extends Handler {
3536 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003537 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3538 public static final int LISTENER_TIMEOUT = 3;
3539 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003540 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3541 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003542 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 public AlarmHandler() {
3545 }
Kweku Adams61e03292017-10-19 14:27:12 -07003546
Makoto Onuki4d298b52018-02-05 10:54:58 -08003547 public void postRemoveForStopped(int uid) {
3548 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3549 }
3550
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003552 switch (msg.what) {
3553 case ALARM_EVENT: {
3554 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3555 synchronized (mLock) {
3556 final long nowRTC = System.currentTimeMillis();
3557 final long nowELAPSED = SystemClock.elapsedRealtime();
3558 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3559 updateNextAlarmClockLocked();
3560 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003561
Christopher Tate14a7bb02015-10-01 10:24:31 -07003562 // now trigger the alarms without the lock held
3563 for (int i=0; i<triggerList.size(); i++) {
3564 Alarm alarm = triggerList.get(i);
3565 try {
3566 alarm.operation.send();
3567 } catch (PendingIntent.CanceledException e) {
3568 if (alarm.repeatInterval > 0) {
3569 // This IntentSender is no longer valid, but this
3570 // is a repeating alarm, so toss the hoser.
3571 removeImpl(alarm.operation);
3572 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003573 }
3574 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003575 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003577
3578 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3579 sendNextAlarmClockChanged();
3580 break;
3581
3582 case LISTENER_TIMEOUT:
3583 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3584 break;
3585
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003586 case REPORT_ALARMS_ACTIVE:
3587 if (mLocalDeviceIdleController != null) {
3588 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3589 }
3590 break;
3591
Suprabh Shukla75edab12018-01-29 14:09:06 -08003592 case APP_STANDBY_PAROLE_CHANGED:
3593 synchronized (mLock) {
3594 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003595 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3596 rescheduleKernelAlarmsLocked();
3597 updateNextAlarmClockLocked();
3598 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003599 }
3600 break;
3601
3602 case APP_STANDBY_BUCKET_CHANGED:
3603 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003604 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3605 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3606 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3607 rescheduleKernelAlarmsLocked();
3608 updateNextAlarmClockLocked();
3609 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003610 }
3611 break;
3612
Makoto Onuki4d298b52018-02-05 10:54:58 -08003613 case REMOVE_FOR_STOPPED:
3614 synchronized (mLock) {
3615 removeForStoppedLocked(msg.arg1);
3616 }
3617 break;
3618
Christopher Tate14a7bb02015-10-01 10:24:31 -07003619 default:
3620 // nope, just ignore it
3621 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 }
3623 }
3624 }
Kweku Adams61e03292017-10-19 14:27:12 -07003625
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 class ClockReceiver extends BroadcastReceiver {
3627 public ClockReceiver() {
3628 IntentFilter filter = new IntentFilter();
3629 filter.addAction(Intent.ACTION_TIME_TICK);
3630 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003631 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003632 }
Kweku Adams61e03292017-10-19 14:27:12 -07003633
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003634 @Override
3635 public void onReceive(Context context, Intent intent) {
3636 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003637 if (DEBUG_BATCH) {
3638 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3639 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003640 synchronized (mLock) {
3641 mLastTickReceived = System.currentTimeMillis();
3642 }
Christopher Tate385e4982013-07-23 18:22:29 -07003643 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3645 // Since the kernel does not keep track of DST, we need to
3646 // reset the TZ information at the beginning of each day
3647 // based off of the current Zone gmt offset + userspace tracked
3648 // daylight savings information.
3649 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003650 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003651 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003652 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003653 }
3654 }
Kweku Adams61e03292017-10-19 14:27:12 -07003655
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003656 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003657 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003658 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003659
3660 // Schedule this event for the amount of time that it would take to get to
3661 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003662 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003663
David Christieebe51fc2013-07-26 13:23:29 -07003664 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003665 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003666 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3667 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003668
3669 // Finally, remember when we set the tick alarm
3670 synchronized (mLock) {
3671 mLastTickSet = currentTime;
3672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 }
Christopher Tate385e4982013-07-23 18:22:29 -07003674
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003675 public void scheduleDateChangedEvent() {
3676 Calendar calendar = Calendar.getInstance();
3677 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003678 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003679 calendar.set(Calendar.MINUTE, 0);
3680 calendar.set(Calendar.SECOND, 0);
3681 calendar.set(Calendar.MILLISECOND, 0);
3682 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003683
3684 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003685 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3686 AlarmManager.FLAG_STANDALONE, workSource, null,
3687 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003688 }
3689 }
Kweku Adams61e03292017-10-19 14:27:12 -07003690
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003691 class InteractiveStateReceiver extends BroadcastReceiver {
3692 public InteractiveStateReceiver() {
3693 IntentFilter filter = new IntentFilter();
3694 filter.addAction(Intent.ACTION_SCREEN_OFF);
3695 filter.addAction(Intent.ACTION_SCREEN_ON);
3696 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3697 getContext().registerReceiver(this, filter);
3698 }
3699
3700 @Override
3701 public void onReceive(Context context, Intent intent) {
3702 synchronized (mLock) {
3703 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3704 }
3705 }
3706 }
3707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 class UninstallReceiver extends BroadcastReceiver {
3709 public UninstallReceiver() {
3710 IntentFilter filter = new IntentFilter();
3711 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3712 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003713 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003715 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003716 // Register for events related to sdcard installation.
3717 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003718 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003719 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003720 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003721 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003722 }
Kweku Adams61e03292017-10-19 14:27:12 -07003723
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 @Override
3725 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003726 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003728 String action = intent.getAction();
3729 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003730 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3731 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3732 for (String packageName : pkgList) {
3733 if (lookForPackageLocked(packageName)) {
3734 setResultCode(Activity.RESULT_OK);
3735 return;
3736 }
3737 }
3738 return;
3739 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003740 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003741 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3742 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3743 if (userHandle >= 0) {
3744 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003745 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3746 final Pair<String, Integer> packageUser =
3747 mLastAlarmDeliveredForPackage.keyAt(i);
3748 if (packageUser.second == userHandle) {
3749 mLastAlarmDeliveredForPackage.removeAt(i);
3750 }
3751 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003752 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003753 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003754 if (uid >= 0) {
3755 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003756 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003757 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003758 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003759 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3760 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3761 // This package is being updated; don't kill its alarms.
3762 return;
3763 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003764 Uri data = intent.getData();
3765 if (data != null) {
3766 String pkg = data.getSchemeSpecificPart();
3767 if (pkg != null) {
3768 pkgList = new String[]{pkg};
3769 }
3770 }
3771 }
3772 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003773 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3774 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3775 if (ArrayUtils.contains(pkgList, packageUser.first)
3776 && packageUser.second == UserHandle.getUserId(uid)) {
3777 mLastAlarmDeliveredForPackage.removeAt(i);
3778 }
3779 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003780 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003781 if (uid >= 0) {
3782 // package-removed case
3783 removeLocked(uid);
3784 } else {
3785 // external-applications-unavailable etc case
3786 removeLocked(pkg);
3787 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003788 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003789 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3790 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3791 if (uidStats.remove(pkg) != null) {
3792 if (uidStats.size() <= 0) {
3793 mBroadcastStats.removeAt(i);
3794 }
3795 }
3796 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003797 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 }
3799 }
3800 }
3801 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003802
3803 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003804 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003805 }
3806
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003807 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003808 if (disabled) {
3809 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003810 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003811 }
3812
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003813 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003814 }
3815
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003816 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003817 if (disabled) {
3818 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003819 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003820 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003821
3822 @Override public void onUidCachedChanged(int uid, boolean cached) {
3823 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003824 };
3825
Suprabh Shukla75edab12018-01-29 14:09:06 -08003826 /**
3827 * Tracking of app assignments to standby buckets
3828 */
3829 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3830 @Override
3831 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
3832 boolean idle, int bucket) {
3833 if (DEBUG_STANDBY) {
3834 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3835 bucket);
3836 }
3837 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003838 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3839 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003840 }
3841
3842 @Override
3843 public void onParoleStateChanged(boolean isParoleOn) {
3844 if (DEBUG_STANDBY) {
3845 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3846 }
3847 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3848 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3849 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3850 Boolean.valueOf(isParoleOn)).sendToTarget();
3851 }
3852 };
3853
Makoto Onuki2206af32017-11-21 16:25:35 -08003854 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003855 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003856 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003857 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003858 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003859 }
3860 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003861
3862 @Override
3863 public void unblockAlarmsForUid(int uid) {
3864 synchronized (mLock) {
3865 sendPendingBackgroundAlarmsLocked(uid, null);
3866 }
3867 }
3868
3869 @Override
3870 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3871 synchronized (mLock) {
3872 sendPendingBackgroundAlarmsLocked(uid, packageName);
3873 }
3874 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003875
3876 @Override
3877 public void onUidForeground(int uid, boolean foreground) {
3878 synchronized (mLock) {
3879 if (foreground) {
3880 mUseAllowWhileIdleShortTime.put(uid, true);
3881
3882 // Note we don't have to drain the pending while-idle alarms here, because
3883 // this event should coincide with unblockAlarmsForUid().
3884 }
3885 }
3886 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003887 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003888
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003890 String pkg = pi.getCreatorPackage();
3891 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003892 return getStatsLocked(uid, pkg);
3893 }
3894
3895 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003896 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3897 if (uidStats == null) {
3898 uidStats = new ArrayMap<String, BroadcastStats>();
3899 mBroadcastStats.put(uid, uidStats);
3900 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003901 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003902 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003903 bs = new BroadcastStats(uid, pkgName);
3904 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
3906 return bs;
3907 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003908
Christopher Tate21e9f192017-08-08 13:49:11 -07003909 /**
3910 * Canonical count of (operation.send() - onSendFinished()) and
3911 * listener send/complete/timeout invocations.
3912 * Guarded by the usual lock.
3913 */
3914 @GuardedBy("mLock")
3915 private int mSendCount = 0;
3916 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003917 private int mSendFinishCount = 0;
3918 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003919 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003920 @GuardedBy("mLock")
3921 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003922
Christopher Tate14a7bb02015-10-01 10:24:31 -07003923 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003924
Christopher Tate14a7bb02015-10-01 10:24:31 -07003925 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3926 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003927 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003928 return mInFlight.remove(i);
3929 }
3930 }
3931 mLog.w("No in-flight alarm for " + pi + " " + intent);
3932 return null;
3933 }
3934
3935 private InFlight removeLocked(IBinder listener) {
3936 for (int i = 0; i < mInFlight.size(); i++) {
3937 if (mInFlight.get(i).mListener == listener) {
3938 return mInFlight.remove(i);
3939 }
3940 }
3941 mLog.w("No in-flight alarm for listener " + listener);
3942 return null;
3943 }
3944
3945 private void updateStatsLocked(InFlight inflight) {
3946 final long nowELAPSED = SystemClock.elapsedRealtime();
3947 BroadcastStats bs = inflight.mBroadcastStats;
3948 bs.nesting--;
3949 if (bs.nesting <= 0) {
3950 bs.nesting = 0;
3951 bs.aggregateTime += nowELAPSED - bs.startTime;
3952 }
3953 FilterStats fs = inflight.mFilterStats;
3954 fs.nesting--;
3955 if (fs.nesting <= 0) {
3956 fs.nesting = 0;
3957 fs.aggregateTime += nowELAPSED - fs.startTime;
3958 }
3959 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003960 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3961 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003962 }
3963 }
3964
3965 private void updateTrackingLocked(InFlight inflight) {
3966 if (inflight != null) {
3967 updateStatsLocked(inflight);
3968 }
3969 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003970 if (DEBUG_WAKELOCK) {
3971 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3972 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003973 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003974 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003975 mWakeLock.release();
3976 if (mInFlight.size() > 0) {
3977 mLog.w("Finished all dispatches with " + mInFlight.size()
3978 + " remaining inflights");
3979 for (int i=0; i<mInFlight.size(); i++) {
3980 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3981 }
3982 mInFlight.clear();
3983 }
3984 } else {
3985 // the next of our alarms is now in flight. reattribute the wakelock.
3986 if (mInFlight.size() > 0) {
3987 InFlight inFlight = mInFlight.get(0);
3988 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3989 inFlight.mAlarmType, inFlight.mTag, -1, false);
3990 } else {
3991 // should never happen
3992 mLog.w("Alarm wakelock still held but sent queue empty");
3993 mWakeLock.setWorkSource(null);
3994 }
3995 }
3996 }
3997
3998 /**
3999 * Callback that arrives when a direct-call alarm reports that delivery has finished
4000 */
4001 @Override
4002 public void alarmComplete(IBinder who) {
4003 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004004 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004005 + " pid=" + Binder.getCallingPid());
4006 return;
4007 }
4008
4009 final long ident = Binder.clearCallingIdentity();
4010 try {
4011 synchronized (mLock) {
4012 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4013 InFlight inflight = removeLocked(who);
4014 if (inflight != null) {
4015 if (DEBUG_LISTENER_CALLBACK) {
4016 Slog.i(TAG, "alarmComplete() from " + who);
4017 }
4018 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004019 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004020 } else {
4021 // Delivery timed out, and the timeout handling already took care of
4022 // updating our tracking here, so we needn't do anything further.
4023 if (DEBUG_LISTENER_CALLBACK) {
4024 Slog.i(TAG, "Late alarmComplete() from " + who);
4025 }
4026 }
4027 }
4028 } finally {
4029 Binder.restoreCallingIdentity(ident);
4030 }
4031 }
4032
4033 /**
4034 * Callback that arrives when a PendingIntent alarm has finished delivery
4035 */
4036 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004037 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4038 String resultData, Bundle resultExtras) {
4039 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004040 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004041 updateTrackingLocked(removeLocked(pi, intent));
4042 }
4043 }
4044
4045 /**
4046 * Timeout of a direct-call alarm delivery
4047 */
4048 public void alarmTimedOut(IBinder who) {
4049 synchronized (mLock) {
4050 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004051 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004052 // TODO: implement ANR policy for the target
4053 if (DEBUG_LISTENER_CALLBACK) {
4054 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004055 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004056 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004057 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004058 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004059 if (DEBUG_LISTENER_CALLBACK) {
4060 Slog.i(TAG, "Spurious timeout of listener " + who);
4061 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004062 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004064 }
4065 }
4066
4067 /**
4068 * Deliver an alarm and set up the post-delivery handling appropriately
4069 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004070 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004071 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4072 if (alarm.operation != null) {
4073 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004074 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004075
4076 if (alarm.priorityClass.priority == PRIO_TICK) {
4077 mLastTickIssued = nowELAPSED;
4078 }
4079
Christopher Tate14a7bb02015-10-01 10:24:31 -07004080 try {
4081 alarm.operation.send(getContext(), 0,
4082 mBackgroundIntent.putExtra(
4083 Intent.EXTRA_ALARM_COUNT, alarm.count),
4084 mDeliveryTracker, mHandler, null,
4085 allowWhileIdle ? mIdleOptions : null);
4086 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004087 if (alarm.operation == mTimeTickSender) {
4088 Slog.wtf(TAG, "mTimeTickSender canceled");
4089 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004090 if (alarm.repeatInterval > 0) {
4091 // This IntentSender is no longer valid, but this
4092 // is a repeating alarm, so toss it
4093 removeImpl(alarm.operation);
4094 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004095 // No actual delivery was possible, so the delivery tracker's
4096 // 'finished' callback won't be invoked. We also don't need
4097 // to do any wakelock or stats tracking, so we have nothing
4098 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004099 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004100 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004101 }
4102 } else {
4103 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004104 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004105 try {
4106 if (DEBUG_LISTENER_CALLBACK) {
4107 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4108 + " listener=" + alarm.listener.asBinder());
4109 }
4110 alarm.listener.doAlarm(this);
4111 mHandler.sendMessageDelayed(
4112 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4113 alarm.listener.asBinder()),
4114 mConstants.LISTENER_TIMEOUT);
4115 } catch (Exception e) {
4116 if (DEBUG_LISTENER_CALLBACK) {
4117 Slog.i(TAG, "Alarm undeliverable to listener "
4118 + alarm.listener.asBinder(), e);
4119 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004120 // As in the PendingIntent.CanceledException case, delivery of the
4121 // alarm was not possible, so we have no wakelock or timeout or
4122 // stats management to do. It threw before we posted the delayed
4123 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004124 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004125 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004126 }
4127 }
4128
4129 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004130 if (DEBUG_WAKELOCK) {
4131 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4132 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004133 if (mBroadcastRefCount == 0) {
4134 setWakelockWorkSource(alarm.operation, alarm.workSource,
4135 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4136 true);
4137 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004138 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004139 }
4140 final InFlight inflight = new InFlight(AlarmManagerService.this,
4141 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4142 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4143 mInFlight.add(inflight);
4144 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004145 if (allowWhileIdle) {
4146 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004147 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004148 if ((mAppStateTracker == null)
4149 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004150 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4151 } else {
4152 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4153 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004154 if (RECORD_DEVICE_IDLE_ALARMS) {
4155 IdleDispatchEntry ent = new IdleDispatchEntry();
4156 ent.uid = alarm.uid;
4157 ent.pkg = alarm.packageName;
4158 ent.tag = alarm.statsTag;
4159 ent.op = "DELIVER";
4160 ent.elapsedRealtime = nowELAPSED;
4161 mAllowWhileIdleDispatches.add(ent);
4162 }
4163 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004164 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004165 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4166 UserHandle.getUserId(alarm.creatorUid));
4167 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4168 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004169
4170 final BroadcastStats bs = inflight.mBroadcastStats;
4171 bs.count++;
4172 if (bs.nesting == 0) {
4173 bs.nesting = 1;
4174 bs.startTime = nowELAPSED;
4175 } else {
4176 bs.nesting++;
4177 }
4178 final FilterStats fs = inflight.mFilterStats;
4179 fs.count++;
4180 if (fs.nesting == 0) {
4181 fs.nesting = 1;
4182 fs.startTime = nowELAPSED;
4183 } else {
4184 fs.nesting++;
4185 }
4186 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4187 || alarm.type == RTC_WAKEUP) {
4188 bs.numWakeup++;
4189 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004190 ActivityManager.noteWakeupAlarm(
4191 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4192 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004193 }
4194 }
4195 }
4196}