blob: c0b2818bcdd63a01531c7f142513eedb2b553ff4 [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 Onuki2f0b0312018-02-08 02:30:27 +0000102import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -0800103
Makoto Onuki2206af32017-11-21 16:25:35 -0800104/**
105 * Alarm manager implementaion.
106 *
107 * Unit test:
108 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
109 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800110class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700111 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
112 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800113 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700114 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 static final int TIME_CHANGED_MASK = 1 << 16;
116 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800117
Christopher Tatee0a22b32013-07-11 14:43:13 -0700118 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800119 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800120
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 static final boolean localLOGV = false;
123 static final boolean DEBUG_BATCH = localLOGV || false;
124 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200125 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700126 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800127 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700128 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800129 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700130 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700131 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 static final int ALARM_EVENT = 1;
133 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200134
Christopher Tate14a7bb02015-10-01 10:24:31 -0700135 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700138
Adam Lesinski182f73f2013-12-05 16:48:06 -0800139 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700140
Christopher Tate24cd46f2016-02-02 14:28:01 -0800141 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
142 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700143 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
144 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200145
Adam Lesinski182f73f2013-12-05 16:48:06 -0800146 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800147
Christopher Tate14a7bb02015-10-01 10:24:31 -0700148 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800149 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800150 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700151
Adam Lesinski182f73f2013-12-05 16:48:06 -0800152 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800153
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700154 // List of alarms per uid deferred due to user applied background restrictions on the source app
155 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800156 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800157 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700158 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700159 private long mLastWakeupSet;
160 private long mLastWakeup;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800161 private long mLastTickSet;
162 private long mLastTickIssued; // elapsed
163 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800164 private long mLastTickAdded;
165 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800166 int mBroadcastRefCount = 0;
167 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700168 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700169 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
170 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800171 final AlarmHandler mHandler = new AlarmHandler();
172 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700173 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700175 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800176 PendingIntent mTimeTickSender;
177 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700178 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700179 boolean mInteractive = true;
180 long mNonInteractiveStartTime;
181 long mNonInteractiveTime;
182 long mLastAlarmDeliveryTime;
183 long mStartCurrentDelayTime;
184 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700185 long mLastTimeChangeClockTime;
186 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700187 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800188
Christopher Tatebb9cce52017-04-18 14:19:43 -0700189 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
190
191 /**
192 * This permission must be defined by the canonical System UI package,
193 * with protection level "signature".
194 */
195 private static final String SYSTEM_UI_SELF_PERMISSION =
196 "android.permission.systemui.IDENTITY";
197
198 /**
199 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
200 */
201 int mSystemUiUid;
202
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700203 /**
204 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700205 * used to determine the earliest we can dispatch the next such alarm. Times are in the
206 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700207 */
208 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
209
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800210 /**
211 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
212 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
213 */
214 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
215
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700216 final static class IdleDispatchEntry {
217 int uid;
218 String pkg;
219 String tag;
220 String op;
221 long elapsedRealtime;
222 long argRealtime;
223 }
224 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
225
Suprabh Shukla75edab12018-01-29 14:09:06 -0800226 interface Stats {
227 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800228 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800229 }
230
231 private final StatLogger mStatLogger = new StatLogger(new String[] {
232 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800233 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800234 });
235
Dianne Hackborna750a632015-06-16 17:18:23 -0700236 /**
237 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
238 */
239 Bundle mIdleOptions;
240
Jose Lima235510e2014-08-13 12:50:01 -0700241 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
242 new SparseArray<>();
243 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
244 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200245 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
246 new SparseBooleanArray();
247 private boolean mNextAlarmClockMayChange;
248
249 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700250 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
251 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200252
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000253 private final ForceAppStandbyTracker mForceAppStandbyTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800254 private boolean mAppStandbyParole;
255 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800256
Dianne Hackborna750a632015-06-16 17:18:23 -0700257 /**
258 * All times are in milliseconds. These constants are kept synchronized with the system
259 * global Settings. Any access to this class or its fields should be done while
260 * holding the AlarmManagerService.mLock lock.
261 */
262 private final class Constants extends ContentObserver {
263 // Key names stored in the settings value.
264 private static final String KEY_MIN_FUTURITY = "min_futurity";
265 private static final String KEY_MIN_INTERVAL = "min_interval";
266 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
267 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
268 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
269 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700270 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700271
Suprabh Shukla75edab12018-01-29 14:09:06 -0800272 // Keys for specifying throttling delay based on app standby bucketing
273 private final String[] KEYS_APP_STANDBY_DELAY = {
274 "standby_active_delay",
275 "standby_working_delay",
276 "standby_frequent_delay",
277 "standby_rare_delay",
278 "standby_never_delay",
279 };
280
Dianne Hackborna750a632015-06-16 17:18:23 -0700281 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
282 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700283 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700284 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700285 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700286 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800287 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
288 0, // Active
289 6 * 60_000, // Working
290 30 * 60_000, // Frequent
291 2 * 60 * 60_000, // Rare
292 10 * 24 * 60 * 60_000 // Never
293 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700294
Dianne Hackborna750a632015-06-16 17:18:23 -0700295 // Minimum futurity of a new alarm
296 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
297
298 // Minimum alarm recurrence interval
299 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
300
301 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
302 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
303
304 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
305 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
306
307 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
308 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
309 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
310
Christopher Tate14a7bb02015-10-01 10:24:31 -0700311 // Direct alarm listener callback timeout
312 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
313
Suprabh Shukla75edab12018-01-29 14:09:06 -0800314 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
315
Dianne Hackborna750a632015-06-16 17:18:23 -0700316 private ContentResolver mResolver;
317 private final KeyValueListParser mParser = new KeyValueListParser(',');
318 private long mLastAllowWhileIdleWhitelistDuration = -1;
319
320 public Constants(Handler handler) {
321 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700322 updateAllowWhileIdleWhitelistDurationLocked();
323 }
324
325 public void start(ContentResolver resolver) {
326 mResolver = resolver;
327 mResolver.registerContentObserver(Settings.Global.getUriFor(
328 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
329 updateConstants();
330 }
331
Dianne Hackborna750a632015-06-16 17:18:23 -0700332 public void updateAllowWhileIdleWhitelistDurationLocked() {
333 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
334 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
335 BroadcastOptions opts = BroadcastOptions.makeBasic();
336 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
337 mIdleOptions = opts.toBundle();
338 }
339 }
340
341 @Override
342 public void onChange(boolean selfChange, Uri uri) {
343 updateConstants();
344 }
345
346 private void updateConstants() {
347 synchronized (mLock) {
348 try {
349 mParser.setString(Settings.Global.getString(mResolver,
350 Settings.Global.ALARM_MANAGER_CONSTANTS));
351 } catch (IllegalArgumentException e) {
352 // Failed to parse the settings string, log this and move on
353 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800354 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700355 }
356
357 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
358 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
359 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
360 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
361 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
362 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
363 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
364 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
365 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700366 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
367 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800368 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
369 DEFAULT_APP_STANDBY_DELAYS[0]);
370 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
371 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
372 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
373 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700374 updateAllowWhileIdleWhitelistDurationLocked();
375 }
376 }
377
378 void dump(PrintWriter pw) {
379 pw.println(" Settings:");
380
381 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
382 TimeUtils.formatDuration(MIN_FUTURITY, pw);
383 pw.println();
384
385 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
386 TimeUtils.formatDuration(MIN_INTERVAL, pw);
387 pw.println();
388
Christopher Tate14a7bb02015-10-01 10:24:31 -0700389 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
390 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
391 pw.println();
392
Dianne Hackborna750a632015-06-16 17:18:23 -0700393 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
394 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
395 pw.println();
396
397 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
398 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
399 pw.println();
400
401 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
402 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
403 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800404
405 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
406 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
407 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
408 pw.println();
409 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700410 }
Kweku Adams61e03292017-10-19 14:27:12 -0700411
412 void dumpProto(ProtoOutputStream proto, long fieldId) {
413 final long token = proto.start(fieldId);
414
415 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
416 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
417 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
418 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
419 ALLOW_WHILE_IDLE_SHORT_TIME);
420 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
421 ALLOW_WHILE_IDLE_LONG_TIME);
422 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
423 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
424
425 proto.end(token);
426 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700427 }
428
429 final Constants mConstants;
430
Christopher Tate1590f1e2014-10-02 17:27:57 -0700431 // Alarm delivery ordering bookkeeping
432 static final int PRIO_TICK = 0;
433 static final int PRIO_WAKEUP = 1;
434 static final int PRIO_NORMAL = 2;
435
Dianne Hackborna750a632015-06-16 17:18:23 -0700436 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700437 int seq;
438 int priority;
439
440 PriorityClass() {
441 seq = mCurrentSeq - 1;
442 priority = PRIO_NORMAL;
443 }
444 }
445
Dianne Hackborna750a632015-06-16 17:18:23 -0700446 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700447 int mCurrentSeq = 0;
448
Dianne Hackborna750a632015-06-16 17:18:23 -0700449 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700450 public long when;
451 public int uid;
452 public String action;
453
454 public WakeupEvent(long theTime, int theUid, String theAction) {
455 when = theTime;
456 uid = theUid;
457 action = theAction;
458 }
459 }
460
Adam Lesinski182f73f2013-12-05 16:48:06 -0800461 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
462 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700463
Adrian Roosc42a1e12014-07-07 23:35:53 +0200464 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465 long start; // These endpoints are always in ELAPSED
466 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700467 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700468
469 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
470
471 Batch() {
472 start = 0;
473 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700474 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475 }
476
477 Batch(Alarm seed) {
478 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700479 end = seed.maxWhenElapsed;
480 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700481 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800482 if (seed.operation == mTimeTickSender) {
483 mLastTickAdded = System.currentTimeMillis();
484 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485 }
486
487 int size() {
488 return alarms.size();
489 }
490
491 Alarm get(int index) {
492 return alarms.get(index);
493 }
494
495 boolean canHold(long whenElapsed, long maxWhen) {
496 return (end >= whenElapsed) && (start <= maxWhen);
497 }
498
499 boolean add(Alarm alarm) {
500 boolean newStart = false;
501 // narrows the batch if necessary; presumes that canHold(alarm) is true
502 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
503 if (index < 0) {
504 index = 0 - index - 1;
505 }
506 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800507 if (alarm.operation == mTimeTickSender) {
508 mLastTickAdded = System.currentTimeMillis();
509 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700510 if (DEBUG_BATCH) {
511 Slog.v(TAG, "Adding " + alarm + " to " + this);
512 }
513 if (alarm.whenElapsed > start) {
514 start = alarm.whenElapsed;
515 newStart = true;
516 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700517 if (alarm.maxWhenElapsed < end) {
518 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700519 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700520 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700521
522 if (DEBUG_BATCH) {
523 Slog.v(TAG, " => now " + this);
524 }
525 return newStart;
526 }
527
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800528 boolean remove(Alarm alarm) {
529 return remove(a -> (a == alarm));
530 }
531
Christopher Tate1d99c392017-12-07 16:54:04 -0800532 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700533 boolean didRemove = false;
534 long newStart = 0; // recalculate endpoints as we go
535 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700536 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700537 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700538 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800539 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 alarms.remove(i);
541 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200542 if (alarm.alarmClock != null) {
543 mNextAlarmClockMayChange = true;
544 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800545 if (alarm.operation == mTimeTickSender) {
546 mLastTickRemoved = System.currentTimeMillis();
547 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700548 } else {
549 if (alarm.whenElapsed > newStart) {
550 newStart = alarm.whenElapsed;
551 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700552 if (alarm.maxWhenElapsed < newEnd) {
553 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700554 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700555 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700556 i++;
557 }
558 }
559 if (didRemove) {
560 // commit the new batch bounds
561 start = newStart;
562 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700563 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 }
565 return didRemove;
566 }
567
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 boolean hasPackage(final String packageName) {
569 final int N = alarms.size();
570 for (int i = 0; i < N; i++) {
571 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700572 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 return true;
574 }
575 }
576 return false;
577 }
578
579 boolean hasWakeups() {
580 final int N = alarms.size();
581 for (int i = 0; i < N; i++) {
582 Alarm a = alarms.get(i);
583 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
584 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
585 return true;
586 }
587 }
588 return false;
589 }
590
591 @Override
592 public String toString() {
593 StringBuilder b = new StringBuilder(40);
594 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
595 b.append(" num="); b.append(size());
596 b.append(" start="); b.append(start);
597 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700598 if (flags != 0) {
599 b.append(" flgs=0x");
600 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700601 }
602 b.append('}');
603 return b.toString();
604 }
Kweku Adams61e03292017-10-19 14:27:12 -0700605
606 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
607 long nowRTC) {
608 final long token = proto.start(fieldId);
609
610 proto.write(BatchProto.START_REALTIME, start);
611 proto.write(BatchProto.END_REALTIME, end);
612 proto.write(BatchProto.FLAGS, flags);
613 for (Alarm a : alarms) {
614 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
615 }
616
617 proto.end(token);
618 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700619 }
620
621 static class BatchTimeOrder implements Comparator<Batch> {
622 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800623 long when1 = b1.start;
624 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800625 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700626 return 1;
627 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800628 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700629 return -1;
630 }
631 return 0;
632 }
633 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800634
635 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
636 @Override
637 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700638 // priority class trumps everything. TICK < WAKEUP < NORMAL
639 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
640 return -1;
641 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
642 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800643 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700644
645 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800646 if (lhs.whenElapsed < rhs.whenElapsed) {
647 return -1;
648 } else if (lhs.whenElapsed > rhs.whenElapsed) {
649 return 1;
650 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700651
652 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800653 return 0;
654 }
655 };
656
Christopher Tate1590f1e2014-10-02 17:27:57 -0700657 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
658 final int N = alarms.size();
659 for (int i = 0; i < N; i++) {
660 Alarm a = alarms.get(i);
661
662 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700663 if (a.operation != null
664 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700665 alarmPrio = PRIO_TICK;
666 } else if (a.wakeup) {
667 alarmPrio = PRIO_WAKEUP;
668 } else {
669 alarmPrio = PRIO_NORMAL;
670 }
671
672 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800673 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700674 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700675 if (packagePrio == null) {
676 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700677 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700678 }
679 a.priorityClass = packagePrio;
680
681 if (packagePrio.seq != mCurrentSeq) {
682 // first alarm we've seen in the current delivery generation from this package
683 packagePrio.priority = alarmPrio;
684 packagePrio.seq = mCurrentSeq;
685 } else {
686 // Multiple alarms from this package being delivered in this generation;
687 // bump the package's delivery class if it's warranted.
688 // TICK < WAKEUP < NORMAL
689 if (alarmPrio < packagePrio.priority) {
690 packagePrio.priority = alarmPrio;
691 }
692 }
693 }
694 }
695
Christopher Tatee0a22b32013-07-11 14:43:13 -0700696 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800697 static final long MIN_FUZZABLE_INTERVAL = 10000;
698 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700699 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
700
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700701 // 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 -0700702 // to run during this time are placed in mPendingWhileIdleAlarms
703 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700704 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700705 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700706
Jeff Brownb880d882014-02-10 19:47:07 -0800707 public AlarmManagerService(Context context) {
708 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700709 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800710
Makoto Onuki2f0b0312018-02-08 02:30:27 +0000711 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
712 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
713
Christopher Tate1d99c392017-12-07 16:54:04 -0800714 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800715 }
716
Christopher Tatee0a22b32013-07-11 14:43:13 -0700717 static long convertToElapsed(long when, int type) {
718 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
719 if (isRtc) {
720 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
721 }
722 return when;
723 }
724
725 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
726 // calculate the end of our nominal delivery window for the alarm.
727 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
728 // Current heuristic: batchable window is 75% of either the recurrence interval
729 // [for a periodic alarm] or of the time from now to the desired delivery time,
730 // with a minimum delay/interval of 10 seconds, under which we will simply not
731 // defer the alarm.
732 long futurity = (interval == 0)
733 ? (triggerAtTime - now)
734 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700735 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736 futurity = 0;
737 }
738 return triggerAtTime + (long)(.75 * futurity);
739 }
740
741 // returns true if the batch was added at the head
742 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
743 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
744 if (index < 0) {
745 index = 0 - index - 1;
746 }
747 list.add(index, newBatch);
748 return (index == 0);
749 }
750
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800751 private void insertAndBatchAlarmLocked(Alarm alarm) {
752 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
753 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
754
755 if (whichBatch < 0) {
756 addBatchLocked(mAlarmBatches, new Batch(alarm));
757 } else {
758 final Batch batch = mAlarmBatches.get(whichBatch);
759 if (batch.add(alarm)) {
760 // The start time of this batch advanced, so batch ordering may
761 // have just been broken. Move it to where it now belongs.
762 mAlarmBatches.remove(whichBatch);
763 addBatchLocked(mAlarmBatches, batch);
764 }
765 }
766 }
767
Christopher Tate385e4982013-07-23 18:22:29 -0700768 // Return the index of the matching batch, or -1 if none found.
769 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700770 final int N = mAlarmBatches.size();
771 for (int i = 0; i < N; i++) {
772 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700773 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700774 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700775 }
776 }
Christopher Tate385e4982013-07-23 18:22:29 -0700777 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700778 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800779 /** @return total count of the alarms in a set of alarm batches. */
780 static int getAlarmCount(ArrayList<Batch> batches) {
781 int ret = 0;
782
783 final int size = batches.size();
784 for (int i = 0; i < size; i++) {
785 ret += batches.get(i).size();
786 }
787 return ret;
788 }
789
790 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
791 if (alarms.size() == 0) {
792 return false;
793 }
794 final int batchSize = alarms.size();
795 for (int j = 0; j < batchSize; j++) {
796 if (alarms.get(j).operation == mTimeTickSender) {
797 return true;
798 }
799 }
800 return false;
801 }
802
803 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
804 final int numBatches = batches.size();
805 for (int i = 0; i < numBatches; i++) {
806 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
807 return true;
808 }
809 }
810 return false;
811 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700812
813 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
814 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700815 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700816 rebatchAllAlarmsLocked(true);
817 }
818 }
819
820 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800821 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800822 final int oldCount =
823 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
824 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
825 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
826
Christopher Tate4cb338d2013-07-26 13:11:31 -0700827 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
828 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700829 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700830 final long nowElapsed = SystemClock.elapsedRealtime();
831 final int oldBatches = oldSet.size();
832 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
833 Batch batch = oldSet.get(batchNum);
834 final int N = batch.size();
835 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700836 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700837 }
838 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700839 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
840 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
841 + " to " + mPendingIdleUntil);
842 if (mPendingIdleUntil == null) {
843 // Somehow we lost this... we need to restore all of the pending alarms.
844 restorePendingWhileIdleAlarmsLocked();
845 }
846 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800847 final int newCount =
848 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
849 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
850 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
851
852 if (oldCount != newCount) {
853 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
854 }
855 if (oldHasTick != newHasTick) {
856 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
857 }
858
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700859 rescheduleKernelAlarmsLocked();
860 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800861 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700862 }
863
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800864 /**
865 * Re-orders the alarm batches based on newly evaluated send times based on the current
866 * app-standby buckets
867 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
868 * null indicates all
869 * @return True if there was any reordering done to the current list.
870 */
871 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
872 final long start = mStatLogger.getTime();
873 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
874
875 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
876 final Batch batch = mAlarmBatches.get(batchIndex);
877 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
878 final Alarm alarm = batch.get(alarmIndex);
879 final Pair<String, Integer> packageUser =
880 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
881 if (targetPackages != null && !targetPackages.contains(packageUser)) {
882 continue;
883 }
884 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
885 batch.remove(alarm);
886 rescheduledAlarms.add(alarm);
887 }
888 }
889 if (batch.size() == 0) {
890 mAlarmBatches.remove(batchIndex);
891 }
892 }
893 for (int i = 0; i < rescheduledAlarms.size(); i++) {
894 final Alarm a = rescheduledAlarms.get(i);
895 insertAndBatchAlarmLocked(a);
896 }
897
898 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
899 return rescheduledAlarms.size() > 0;
900 }
901
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700902 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
903 a.when = a.origWhen;
904 long whenElapsed = convertToElapsed(a.when, a.type);
905 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700906 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700907 // Exact
908 maxElapsed = whenElapsed;
909 } else {
910 // Not exact. Preserve any explicit window, otherwise recalculate
911 // the window based on the alarm's new futurity. Note that this
912 // reflects a policy of preferring timely to deferred delivery.
913 maxElapsed = (a.windowLength > 0)
914 ? (whenElapsed + a.windowLength)
915 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
916 }
917 a.whenElapsed = whenElapsed;
918 a.maxWhenElapsed = maxElapsed;
919 setImplLocked(a, true, doValidate);
920 }
921
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700922 /**
923 * Sends alarms that were blocked due to user applied background restrictions - either because
924 * the user lifted those or the uid came to foreground.
925 *
926 * @param uid uid to filter on
927 * @param packageName package to filter on, or null for all packages in uid
928 */
929 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
930 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
931 if (alarmsForUid == null || alarmsForUid.size() == 0) {
932 return;
933 }
934 final ArrayList<Alarm> alarmsToDeliver;
935 if (packageName != null) {
936 if (DEBUG_BG_LIMIT) {
937 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
938 }
939 alarmsToDeliver = new ArrayList<>();
940 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
941 final Alarm a = alarmsForUid.get(i);
942 if (a.matches(packageName)) {
943 alarmsToDeliver.add(alarmsForUid.remove(i));
944 }
945 }
946 if (alarmsForUid.size() == 0) {
947 mPendingBackgroundAlarms.remove(uid);
948 }
949 } else {
950 if (DEBUG_BG_LIMIT) {
951 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
952 }
953 alarmsToDeliver = alarmsForUid;
954 mPendingBackgroundAlarms.remove(uid);
955 }
956 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
957 }
958
Makoto Onuki2206af32017-11-21 16:25:35 -0800959 /**
960 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
961 * restricted.
962 *
963 * This is only called when the global "force all apps-standby" flag changes or when the
964 * power save whitelist changes, so it's okay to be slow.
965 */
966 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700967 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800968
969 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
970 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
971
972 if (alarmsToDeliver.size() > 0) {
973 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
974 }
975 }
976
977 @VisibleForTesting
978 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
979 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
980 Predicate<Alarm> isBackgroundRestricted) {
981
982 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
983 final int uid = pendingAlarms.keyAt(uidIndex);
984 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
985
986 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
987 final Alarm alarm = alarmsForUid.get(alarmIndex);
988
989 if (isBackgroundRestricted.test(alarm)) {
990 continue;
991 }
992
993 unrestrictedAlarms.add(alarm);
994 alarmsForUid.remove(alarmIndex);
995 }
996
997 if (alarmsForUid.size() == 0) {
998 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700999 }
1000 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001001 }
1002
1003 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1004 final int N = alarms.size();
1005 boolean hasWakeup = false;
1006 for (int i = 0; i < N; i++) {
1007 final Alarm alarm = alarms.get(i);
1008 if (alarm.wakeup) {
1009 hasWakeup = true;
1010 }
1011 alarm.count = 1;
1012 // Recurring alarms may have passed several alarm intervals while the
1013 // alarm was kept pending. Send the appropriate trigger count.
1014 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001015 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001016 // Also schedule its next recurrence
1017 final long delta = alarm.count * alarm.repeatInterval;
1018 final long nextElapsed = alarm.whenElapsed + delta;
1019 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1020 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1021 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1022 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1023 // Kernel alarms will be rescheduled as needed in setImplLocked
1024 }
1025 }
1026 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1027 // No need to wakeup for non wakeup alarms
1028 if (mPendingNonWakeupAlarms.size() == 0) {
1029 mStartCurrentDelayTime = nowELAPSED;
1030 mNextNonWakeupDeliveryTime = nowELAPSED
1031 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1032 }
1033 mPendingNonWakeupAlarms.addAll(alarms);
1034 mNumDelayedAlarms += alarms.size();
1035 } else {
1036 if (DEBUG_BG_LIMIT) {
1037 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1038 }
1039 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1040 if (mPendingNonWakeupAlarms.size() > 0) {
1041 alarms.addAll(mPendingNonWakeupAlarms);
1042 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1043 mTotalDelayTime += thisDelayTime;
1044 if (mMaxDelayTime < thisDelayTime) {
1045 mMaxDelayTime = thisDelayTime;
1046 }
1047 mPendingNonWakeupAlarms.clear();
1048 }
1049 calculateDeliveryPriorities(alarms);
1050 Collections.sort(alarms, mAlarmDispatchComparator);
1051 deliverAlarmsLocked(alarms, nowELAPSED);
1052 }
1053 }
1054
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001055 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001056 if (RECORD_DEVICE_IDLE_ALARMS) {
1057 IdleDispatchEntry ent = new IdleDispatchEntry();
1058 ent.uid = 0;
1059 ent.pkg = "FINISH IDLE";
1060 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1061 mAllowWhileIdleDispatches.add(ent);
1062 }
1063
Dianne Hackborn35d54032015-04-23 10:30:43 -07001064 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001065 if (mPendingWhileIdleAlarms.size() > 0) {
1066 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1067 mPendingWhileIdleAlarms = new ArrayList<>();
1068 final long nowElapsed = SystemClock.elapsedRealtime();
1069 for (int i=alarms.size() - 1; i >= 0; i--) {
1070 Alarm a = alarms.get(i);
1071 reAddAlarmLocked(a, nowElapsed, false);
1072 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001073 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001074
1075 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001076 rescheduleKernelAlarmsLocked();
1077 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001078
1079 // And send a TIME_TICK right now, since it is important to get the UI updated.
1080 try {
1081 mTimeTickSender.send();
1082 } catch (PendingIntent.CanceledException e) {
1083 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001084 }
1085
Christopher Tate14a7bb02015-10-01 10:24:31 -07001086 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001087 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001088 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001089 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001090 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001091 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001092 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001093 final BroadcastStats mBroadcastStats;
1094 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001095 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001096
Christopher Tate14a7bb02015-10-01 10:24:31 -07001097 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1098 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1099 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001100 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001101 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001102 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001103 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001104 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001105 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001106 mBroadcastStats = (pendingIntent != null)
1107 ? service.getStatsLocked(pendingIntent)
1108 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001109 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001110 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001111 fs = new FilterStats(mBroadcastStats, mTag);
1112 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001113 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001114 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001115 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001116 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001117 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001118
1119 @Override
1120 public String toString() {
1121 return "InFlight{"
1122 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001123 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001124 + ", workSource=" + mWorkSource
1125 + ", uid=" + mUid
1126 + ", tag=" + mTag
1127 + ", broadcastStats=" + mBroadcastStats
1128 + ", filterStats=" + mFilterStats
1129 + ", alarmType=" + mAlarmType
1130 + "}";
1131 }
Kweku Adams61e03292017-10-19 14:27:12 -07001132
1133 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1134 final long token = proto.start(fieldId);
1135
1136 proto.write(InFlightProto.UID, mUid);
1137 proto.write(InFlightProto.TAG, mTag);
1138 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1139 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1140 if (mPendingIntent != null) {
1141 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1142 }
1143 if (mBroadcastStats != null) {
1144 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1145 }
1146 if (mFilterStats != null) {
1147 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1148 }
1149 if (mWorkSource != null) {
1150 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1151 }
1152
1153 proto.end(token);
1154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001156
Adam Lesinski182f73f2013-12-05 16:48:06 -08001157 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001158 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001159 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001160
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001161 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001163 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001164 int numWakeup;
1165 long startTime;
1166 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001167
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001168 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001169 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001170 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001171 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001172
1173 @Override
1174 public String toString() {
1175 return "FilterStats{"
1176 + "tag=" + mTag
1177 + ", lastTime=" + lastTime
1178 + ", aggregateTime=" + aggregateTime
1179 + ", count=" + count
1180 + ", numWakeup=" + numWakeup
1181 + ", startTime=" + startTime
1182 + ", nesting=" + nesting
1183 + "}";
1184 }
Kweku Adams61e03292017-10-19 14:27:12 -07001185
1186 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1187 final long token = proto.start(fieldId);
1188
1189 proto.write(FilterStatsProto.TAG, mTag);
1190 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1191 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1192 proto.write(FilterStatsProto.COUNT, count);
1193 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1194 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1195 proto.write(FilterStatsProto.NESTING, nesting);
1196
1197 proto.end(token);
1198 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001199 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001200
Adam Lesinski182f73f2013-12-05 16:48:06 -08001201 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001202 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001203 final String mPackageName;
1204
1205 long aggregateTime;
1206 int count;
1207 int numWakeup;
1208 long startTime;
1209 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001210 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001211
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001212 BroadcastStats(int uid, String packageName) {
1213 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001214 mPackageName = packageName;
1215 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001216
1217 @Override
1218 public String toString() {
1219 return "BroadcastStats{"
1220 + "uid=" + mUid
1221 + ", packageName=" + mPackageName
1222 + ", aggregateTime=" + aggregateTime
1223 + ", count=" + count
1224 + ", numWakeup=" + numWakeup
1225 + ", startTime=" + startTime
1226 + ", nesting=" + nesting
1227 + "}";
1228 }
Kweku Adams61e03292017-10-19 14:27:12 -07001229
1230 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1231 final long token = proto.start(fieldId);
1232
1233 proto.write(BroadcastStatsProto.UID, mUid);
1234 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1235 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1236 proto.write(BroadcastStatsProto.COUNT, count);
1237 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1238 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1239 proto.write(BroadcastStatsProto.NESTING, nesting);
1240
1241 proto.end(token);
1242 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001244
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001245 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1246 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001247
1248 int mNumDelayedAlarms = 0;
1249 long mTotalDelayTime = 0;
1250 long mMaxDelayTime = 0;
1251
Adam Lesinski182f73f2013-12-05 16:48:06 -08001252 @Override
1253 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001254 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001255 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001256
1257 // We have to set current TimeZone info to kernel
1258 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001259 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001260
Christopher Tate247571462017-04-10 11:45:05 -07001261 // Also sure that we're booting with a halfway sensible current time
1262 if (mNativeData != 0) {
1263 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1264 if (System.currentTimeMillis() < systemBuildTime) {
1265 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1266 + ", advancing to build time " + systemBuildTime);
1267 setKernelTime(mNativeData, systemBuildTime);
1268 }
1269 }
1270
Christopher Tatebb9cce52017-04-18 14:19:43 -07001271 // Determine SysUI's uid
1272 final PackageManager packMan = getContext().getPackageManager();
1273 try {
1274 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1275 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1276 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1277 mSystemUiUid = sysUi.uid;
1278 } else {
1279 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1280 + " defined by non-privileged app " + sysUi.packageName
1281 + " - ignoring");
1282 }
1283 } catch (NameNotFoundException e) {
1284 }
1285
1286 if (mSystemUiUid <= 0) {
1287 Slog.wtf(TAG, "SysUI package not found!");
1288 }
1289
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001291 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001292
Adam Lesinski182f73f2013-12-05 16:48:06 -08001293 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001295 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001296 | Intent.FLAG_RECEIVER_FOREGROUND
1297 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001298 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001299 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001300 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1301 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001302 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001303 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001306 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 mClockReceiver.scheduleTimeTickEvent();
1308 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001309 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001311
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001312 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001313 AlarmThread waitThread = new AlarmThread();
1314 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001316 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001318
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001319 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001320 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001321 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1322 | ActivityManager.UID_OBSERVER_ACTIVE,
1323 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001324 } catch (RemoteException e) {
1325 // ignored; both services live in system_server
1326 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001329
1330 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001331 public void onBootPhase(int phase) {
1332 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001333 mForceAppStandbyTracker.start();
Dianne Hackborna750a632015-06-16 17:18:23 -07001334 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001335 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001336 mLocalDeviceIdleController
1337 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001338 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1339 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
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 Onuki2f0b0312018-02-08 02:30:27 +00001728 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001729 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1730 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001731 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001732
Christopher Tate14a7bb02015-10-01 10:24:31 -07001733 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1734 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001735 }
Christopher Tate89779822012-08-31 14:40:03 -07001736
Adam Lesinski182f73f2013-12-05 16:48:06 -08001737 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001738 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001739 getContext().enforceCallingOrSelfPermission(
1740 "android.permission.SET_TIME",
1741 "setTime");
1742
Greg Hackmann0cab8962014-02-21 16:35:52 -08001743 if (mNativeData == 0) {
1744 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1745 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001746 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001747
1748 synchronized (mLock) {
1749 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001752
1753 @Override
1754 public void setTimeZone(String tz) {
1755 getContext().enforceCallingOrSelfPermission(
1756 "android.permission.SET_TIME_ZONE",
1757 "setTimeZone");
1758
1759 final long oldId = Binder.clearCallingIdentity();
1760 try {
1761 setTimeZoneImpl(tz);
1762 } finally {
1763 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001766
Adam Lesinski182f73f2013-12-05 16:48:06 -08001767 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001768 public void remove(PendingIntent operation, IAlarmListener listener) {
1769 if (operation == null && listener == null) {
1770 Slog.w(TAG, "remove() with no intent or listener");
1771 return;
1772 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001773
Christopher Tate14a7bb02015-10-01 10:24:31 -07001774 synchronized (mLock) {
1775 removeLocked(operation, listener);
1776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001778
Adam Lesinski182f73f2013-12-05 16:48:06 -08001779 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001780 public long getNextWakeFromIdleTime() {
1781 return getNextWakeFromIdleTimeImpl();
1782 }
1783
1784 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001785 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001786 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1787 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1788 "getNextAlarmClock", null);
1789
1790 return getNextAlarmClockImpl(userId);
1791 }
1792
1793 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001794 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001795 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001796
1797 if (args.length > 0 && "--proto".equals(args[0])) {
1798 dumpProto(fd);
1799 } else {
1800 dumpImpl(pw);
1801 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001802 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001803 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001804
Adam Lesinski182f73f2013-12-05 16:48:06 -08001805 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 synchronized (mLock) {
1807 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001808 mConstants.dump(pw);
1809 pw.println();
1810
Makoto Onuki2f0b0312018-02-08 02:30:27 +00001811 mForceAppStandbyTracker.dump(pw, " ");
1812 pw.println();
Makoto Onuki2206af32017-11-21 16:25:35 -08001813
Suprabh Shukla75edab12018-01-29 14:09:06 -08001814 pw.println(" App Standby Parole: " + mAppStandbyParole);
1815 pw.println();
1816
Christopher Tatee0a22b32013-07-11 14:43:13 -07001817 final long nowRTC = System.currentTimeMillis();
1818 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001819 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001820
Dianne Hackborna750a632015-06-16 17:18:23 -07001821 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001822 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001823 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001824 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001825 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001826 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001827 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1828 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001829 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001830 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1831 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001832 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1833 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001834 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001835 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001836 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001837 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1838 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001839 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001840 pw.print(" Max wakeup delay: ");
1841 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1842 pw.println();
1843 pw.print(" Time since last dispatch: ");
1844 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1845 pw.println();
1846 pw.print(" Next non-wakeup delivery time: ");
1847 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1848 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001849
1850 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1851 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001852 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001853 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001854 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001855 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001856 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001857 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1858 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1859 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001860 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001861
John Spurlock604a5ee2015-06-01 12:27:22 -04001862 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001863 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001864 final TreeSet<Integer> users = new TreeSet<>();
1865 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1866 users.add(mNextAlarmClockForUser.keyAt(i));
1867 }
1868 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1869 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1870 }
1871 for (int user : users) {
1872 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1873 final long time = next != null ? next.getTriggerTime() : 0;
1874 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001875 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001876 pw.print(" pendingSend:"); pw.print(pendingSend);
1877 pw.print(" time:"); pw.print(time);
1878 if (time > 0) {
1879 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1880 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1881 }
1882 pw.println();
1883 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001884 if (mAlarmBatches.size() > 0) {
1885 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001886 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001887 pw.println(mAlarmBatches.size());
1888 for (Batch b : mAlarmBatches) {
1889 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001890 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001891 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001892 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001893 pw.println();
1894 pw.println(" Pending user blocked background alarms: ");
1895 boolean blocked = false;
1896 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1897 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1898 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1899 blocked = true;
1900 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1901 }
1902 }
1903 if (!blocked) {
1904 pw.println(" none");
1905 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001906
Suprabh Shukla75edab12018-01-29 14:09:06 -08001907 pw.println(" mLastAlarmDeliveredForPackage:");
1908 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1909 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1910 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1911 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1912 pw.println();
1913 }
1914 pw.println();
1915
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001916 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001917 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001918 pw.println(" Idle mode state:");
1919 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001920 if (mPendingIdleUntil != null) {
1921 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001922 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001923 } else {
1924 pw.println("null");
1925 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001926 pw.println(" Pending alarms:");
1927 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001928 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001929 if (mNextWakeFromIdle != null) {
1930 pw.println();
1931 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001932 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001933 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001934
1935 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001936 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001937 if (mPendingNonWakeupAlarms.size() > 0) {
1938 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001939 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001940 } else {
1941 pw.println("(none)");
1942 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001943 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001944 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1945 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001946 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001947 pw.print(", max non-interactive time: ");
1948 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1949 pw.println();
1950
1951 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001952 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001953 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1954 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1955 pw.print(" Listener send count: "); pw.println(mListenerCount);
1956 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001957 pw.println();
1958
Christopher Tate7f2a0352015-12-08 10:24:33 -08001959 if (mInFlight.size() > 0) {
1960 pw.println("Outstanding deliveries:");
1961 for (int i = 0; i < mInFlight.size(); i++) {
1962 pw.print(" #"); pw.print(i); pw.print(": ");
1963 pw.println(mInFlight.get(i));
1964 }
1965 pw.println();
1966 }
1967
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001968 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001969 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001970 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08001971 pw.print(" UID ");
1972 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
1973 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001974 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08001975 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
1976 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
1977
1978 final long minInterval = getWhileIdleMinIntervalLocked(uid);
1979 pw.print(" Next allowed:");
1980 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
1981 pw.print(" (");
1982 TimeUtils.formatDuration(minInterval, 0, pw);
1983 pw.print(")");
1984
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001985 pw.println();
1986 }
1987 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08001988
1989 pw.print(" mUseAllowWhileIdleShortTime: [");
1990 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
1991 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
1992 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
1993 pw.print(" ");
1994 }
1995 }
1996 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001997 pw.println();
1998
Dianne Hackborn81038902012-11-26 17:04:09 -08001999 if (mLog.dump(pw, " Recent problems", " ")) {
2000 pw.println();
2001 }
2002
2003 final FilterStats[] topFilters = new FilterStats[10];
2004 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2005 @Override
2006 public int compare(FilterStats lhs, FilterStats rhs) {
2007 if (lhs.aggregateTime < rhs.aggregateTime) {
2008 return 1;
2009 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2010 return -1;
2011 }
2012 return 0;
2013 }
2014 };
2015 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002016 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002017 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2018 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2019 for (int ip=0; ip<uidStats.size(); ip++) {
2020 BroadcastStats bs = uidStats.valueAt(ip);
2021 for (int is=0; is<bs.filterStats.size(); is++) {
2022 FilterStats fs = bs.filterStats.valueAt(is);
2023 int pos = len > 0
2024 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2025 if (pos < 0) {
2026 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002027 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002028 if (pos < topFilters.length) {
2029 int copylen = topFilters.length - pos - 1;
2030 if (copylen > 0) {
2031 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2032 }
2033 topFilters[pos] = fs;
2034 if (len < topFilters.length) {
2035 len++;
2036 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002037 }
2038 }
2039 }
2040 }
2041 if (len > 0) {
2042 pw.println(" Top Alarms:");
2043 for (int i=0; i<len; i++) {
2044 FilterStats fs = topFilters[i];
2045 pw.print(" ");
2046 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2047 TimeUtils.formatDuration(fs.aggregateTime, pw);
2048 pw.print(" running, "); pw.print(fs.numWakeup);
2049 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002050 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2051 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002052 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002053 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002054 pw.println();
2055 }
2056 }
2057
2058 pw.println(" ");
2059 pw.println(" Alarm Stats:");
2060 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002061 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2062 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2063 for (int ip=0; ip<uidStats.size(); ip++) {
2064 BroadcastStats bs = uidStats.valueAt(ip);
2065 pw.print(" ");
2066 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2067 UserHandle.formatUid(pw, bs.mUid);
2068 pw.print(":");
2069 pw.print(bs.mPackageName);
2070 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2071 pw.print(" running, "); pw.print(bs.numWakeup);
2072 pw.println(" wakeups:");
2073 tmpFilters.clear();
2074 for (int is=0; is<bs.filterStats.size(); is++) {
2075 tmpFilters.add(bs.filterStats.valueAt(is));
2076 }
2077 Collections.sort(tmpFilters, comparator);
2078 for (int i=0; i<tmpFilters.size(); i++) {
2079 FilterStats fs = tmpFilters.get(i);
2080 pw.print(" ");
2081 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2082 TimeUtils.formatDuration(fs.aggregateTime, pw);
2083 pw.print(" "); pw.print(fs.numWakeup);
2084 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002085 pw.print(" alarms, last ");
2086 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2087 pw.println(":");
2088 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002089 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002090 pw.println();
2091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002094 pw.println();
2095 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002096
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002097 if (RECORD_DEVICE_IDLE_ALARMS) {
2098 pw.println();
2099 pw.println(" Allow while idle dispatches:");
2100 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2101 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2102 pw.print(" ");
2103 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2104 pw.print(": ");
2105 UserHandle.formatUid(pw, ent.uid);
2106 pw.print(":");
2107 pw.println(ent.pkg);
2108 if (ent.op != null) {
2109 pw.print(" ");
2110 pw.print(ent.op);
2111 pw.print(" / ");
2112 pw.print(ent.tag);
2113 if (ent.argRealtime != 0) {
2114 pw.print(" (");
2115 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2116 pw.print(")");
2117 }
2118 pw.println();
2119 }
2120 }
2121 }
2122
Christopher Tate18a75f12013-07-01 18:18:59 -07002123 if (WAKEUP_STATS) {
2124 pw.println();
2125 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002126 long last = -1;
2127 for (WakeupEvent event : mRecentWakeups) {
2128 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2129 pw.print('|');
2130 if (last < 0) {
2131 pw.print('0');
2132 } else {
2133 pw.print(event.when - last);
2134 }
2135 last = event.when;
2136 pw.print('|'); pw.print(event.uid);
2137 pw.print('|'); pw.print(event.action);
2138 pw.println();
2139 }
2140 pw.println();
2141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002142 }
2143 }
2144
Kweku Adams61e03292017-10-19 14:27:12 -07002145 void dumpProto(FileDescriptor fd) {
2146 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2147
2148 synchronized (mLock) {
2149 final long nowRTC = System.currentTimeMillis();
2150 final long nowElapsed = SystemClock.elapsedRealtime();
2151 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
2152 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
2153 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
2154 mLastTimeChangeClockTime);
2155 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2156 mLastTimeChangeRealtime);
2157
2158 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2159
Makoto Onuki2f0b0312018-02-08 02:30:27 +00002160 mForceAppStandbyTracker.dumpProto(proto,
2161 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07002162
2163 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2164 if (!mInteractive) {
2165 // Durations
2166 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2167 nowElapsed - mNonInteractiveStartTime);
2168 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2169 currentNonWakeupFuzzLocked(nowElapsed));
2170 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2171 nowElapsed - mLastAlarmDeliveryTime);
2172 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2173 nowElapsed - mNextNonWakeupDeliveryTime);
2174 }
2175
2176 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2177 mNextNonWakeup - nowElapsed);
2178 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2179 mNextWakeup - nowElapsed);
2180 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2181 nowElapsed - mLastWakeup);
2182 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2183 nowElapsed - mLastWakeupSet);
2184 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002185
2186 final TreeSet<Integer> users = new TreeSet<>();
2187 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2188 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2189 users.add(mNextAlarmClockForUser.keyAt(i));
2190 }
2191 final int pendingSendNextAlarmClockChangedForUserSize =
2192 mPendingSendNextAlarmClockChangedForUser.size();
2193 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2194 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2195 }
2196 for (int user : users) {
2197 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2198 final long time = next != null ? next.getTriggerTime() : 0;
2199 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2200 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2201 proto.write(AlarmClockMetadataProto.USER, user);
2202 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2203 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2204 proto.end(aToken);
2205 }
2206 for (Batch b : mAlarmBatches) {
2207 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2208 nowElapsed, nowRTC);
2209 }
2210 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2211 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2212 if (blockedAlarms != null) {
2213 for (Alarm a : blockedAlarms) {
2214 a.writeToProto(proto,
2215 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2216 nowElapsed, nowRTC);
2217 }
2218 }
2219 }
2220 if (mPendingIdleUntil != null) {
2221 mPendingIdleUntil.writeToProto(
2222 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2223 }
2224 for (Alarm a : mPendingWhileIdleAlarms) {
2225 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2226 nowElapsed, nowRTC);
2227 }
2228 if (mNextWakeFromIdle != null) {
2229 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2230 nowElapsed, nowRTC);
2231 }
2232
2233 for (Alarm a : mPendingNonWakeupAlarms) {
2234 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2235 nowElapsed, nowRTC);
2236 }
2237
2238 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2239 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2240 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2241 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2242 mNonInteractiveTime);
2243
2244 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2245 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2246 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2247 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2248 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2249
2250 for (InFlight f : mInFlight) {
2251 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2252 }
2253
Kweku Adams61e03292017-10-19 14:27:12 -07002254 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2255 final long token = proto.start(
2256 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002257 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2258 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2259
2260 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID, uid);
2261 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2262 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
2263 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002264 proto.end(token);
2265 }
2266
Makoto Onukiadb50d82018-01-29 16:20:30 -08002267 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2268 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2269 proto.write(AlarmManagerServiceProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
2270 mUseAllowWhileIdleShortTime.keyAt(i));
2271 }
2272 }
2273
Kweku Adams61e03292017-10-19 14:27:12 -07002274 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2275
2276 final FilterStats[] topFilters = new FilterStats[10];
2277 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2278 @Override
2279 public int compare(FilterStats lhs, FilterStats rhs) {
2280 if (lhs.aggregateTime < rhs.aggregateTime) {
2281 return 1;
2282 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2283 return -1;
2284 }
2285 return 0;
2286 }
2287 };
2288 int len = 0;
2289 // Get the top 10 FilterStats, ordered by aggregateTime.
2290 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2291 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2292 for (int ip = 0; ip < uidStats.size(); ++ip) {
2293 BroadcastStats bs = uidStats.valueAt(ip);
2294 for (int is = 0; is < bs.filterStats.size(); ++is) {
2295 FilterStats fs = bs.filterStats.valueAt(is);
2296 int pos = len > 0
2297 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2298 if (pos < 0) {
2299 pos = -pos - 1;
2300 }
2301 if (pos < topFilters.length) {
2302 int copylen = topFilters.length - pos - 1;
2303 if (copylen > 0) {
2304 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2305 }
2306 topFilters[pos] = fs;
2307 if (len < topFilters.length) {
2308 len++;
2309 }
2310 }
2311 }
2312 }
2313 }
2314 for (int i = 0; i < len; ++i) {
2315 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2316 FilterStats fs = topFilters[i];
2317
2318 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2319 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2320 fs.mBroadcastStats.mPackageName);
2321 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2322
2323 proto.end(token);
2324 }
2325
2326 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2327 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2328 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2329 for (int ip = 0; ip < uidStats.size(); ++ip) {
2330 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2331
2332 BroadcastStats bs = uidStats.valueAt(ip);
2333 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2334
2335 // uidStats is an ArrayMap, which we can't sort.
2336 tmpFilters.clear();
2337 for (int is = 0; is < bs.filterStats.size(); ++is) {
2338 tmpFilters.add(bs.filterStats.valueAt(is));
2339 }
2340 Collections.sort(tmpFilters, comparator);
2341 for (FilterStats fs : tmpFilters) {
2342 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2343 }
2344
2345 proto.end(token);
2346 }
2347 }
2348
2349 if (RECORD_DEVICE_IDLE_ALARMS) {
2350 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2351 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2352 final long token = proto.start(
2353 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2354
2355 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2356 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2357 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2358 proto.write(IdleDispatchEntryProto.OP, ent.op);
2359 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2360 ent.elapsedRealtime);
2361 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2362
2363 proto.end(token);
2364 }
2365 }
2366
2367 if (WAKEUP_STATS) {
2368 for (WakeupEvent event : mRecentWakeups) {
2369 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2370 proto.write(WakeupEventProto.UID, event.uid);
2371 proto.write(WakeupEventProto.ACTION, event.action);
2372 proto.write(WakeupEventProto.WHEN, event.when);
2373 proto.end(token);
2374 }
2375 }
2376 }
2377
2378 proto.flush();
2379 }
2380
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002381 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002382 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2383 PrintWriter pw = new PrintWriter(bs);
2384 final long nowRTC = System.currentTimeMillis();
2385 final long nowELAPSED = SystemClock.elapsedRealtime();
2386 final int NZ = mAlarmBatches.size();
2387 for (int iz = 0; iz < NZ; iz++) {
2388 Batch bz = mAlarmBatches.get(iz);
2389 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002390 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002391 pw.flush();
2392 Slog.v(TAG, bs.toString());
2393 bs.reset();
2394 }
2395 }
2396
2397 private boolean validateConsistencyLocked() {
2398 if (DEBUG_VALIDATE) {
2399 long lastTime = Long.MIN_VALUE;
2400 final int N = mAlarmBatches.size();
2401 for (int i = 0; i < N; i++) {
2402 Batch b = mAlarmBatches.get(i);
2403 if (b.start >= lastTime) {
2404 // duplicate start times are okay because of standalone batches
2405 lastTime = b.start;
2406 } else {
2407 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002408 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2409 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002410 return false;
2411 }
2412 }
2413 }
2414 return true;
2415 }
2416
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002417 private Batch findFirstWakeupBatchLocked() {
2418 final int N = mAlarmBatches.size();
2419 for (int i = 0; i < N; i++) {
2420 Batch b = mAlarmBatches.get(i);
2421 if (b.hasWakeups()) {
2422 return b;
2423 }
2424 }
2425 return null;
2426 }
2427
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002428 long getNextWakeFromIdleTimeImpl() {
2429 synchronized (mLock) {
2430 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2431 }
2432 }
2433
2434 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002435 synchronized (mLock) {
2436 return mNextAlarmClockForUser.get(userId);
2437 }
2438 }
2439
2440 /**
2441 * Recomputes the next alarm clock for all users.
2442 */
2443 private void updateNextAlarmClockLocked() {
2444 if (!mNextAlarmClockMayChange) {
2445 return;
2446 }
2447 mNextAlarmClockMayChange = false;
2448
Jose Lima235510e2014-08-13 12:50:01 -07002449 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002450 nextForUser.clear();
2451
2452 final int N = mAlarmBatches.size();
2453 for (int i = 0; i < N; i++) {
2454 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2455 final int M = alarms.size();
2456
2457 for (int j = 0; j < M; j++) {
2458 Alarm a = alarms.get(j);
2459 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002460 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002461 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002462
2463 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002464 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002465 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002466 " for user " + userId);
2467 }
2468
2469 // Alarms and batches are sorted by time, no need to compare times here.
2470 if (nextForUser.get(userId) == null) {
2471 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002472 } else if (a.alarmClock.equals(current)
2473 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2474 // same/earlier time and it's the one we cited before, so stick with it
2475 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002476 }
2477 }
2478 }
2479 }
2480
2481 // Update mNextAlarmForUser with new values.
2482 final int NN = nextForUser.size();
2483 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002484 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002485 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002486 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002487 if (!newAlarm.equals(currentAlarm)) {
2488 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2489 }
2490 }
2491
2492 // Remove users without any alarm clocks scheduled.
2493 final int NNN = mNextAlarmClockForUser.size();
2494 for (int i = NNN - 1; i >= 0; i--) {
2495 int userId = mNextAlarmClockForUser.keyAt(i);
2496 if (nextForUser.get(userId) == null) {
2497 updateNextAlarmInfoForUserLocked(userId, null);
2498 }
2499 }
2500 }
2501
Jose Lima235510e2014-08-13 12:50:01 -07002502 private void updateNextAlarmInfoForUserLocked(int userId,
2503 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002504 if (alarmClock != null) {
2505 if (DEBUG_ALARM_CLOCK) {
2506 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002507 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002508 }
2509 mNextAlarmClockForUser.put(userId, alarmClock);
2510 } else {
2511 if (DEBUG_ALARM_CLOCK) {
2512 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2513 }
2514 mNextAlarmClockForUser.remove(userId);
2515 }
2516
2517 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2518 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2519 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2520 }
2521
2522 /**
2523 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2524 * for which alarm clocks have changed since the last call to this.
2525 *
2526 * Do not call with a lock held. Only call from mHandler's thread.
2527 *
2528 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2529 */
2530 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002531 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002532 pendingUsers.clear();
2533
2534 synchronized (mLock) {
2535 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2536 for (int i = 0; i < N; i++) {
2537 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2538 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2539 }
2540 mPendingSendNextAlarmClockChangedForUser.clear();
2541 }
2542
2543 final int N = pendingUsers.size();
2544 for (int i = 0; i < N; i++) {
2545 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002546 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002547 Settings.System.putStringForUser(getContext().getContentResolver(),
2548 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002549 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002550 userId);
2551
2552 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2553 new UserHandle(userId));
2554 }
2555 }
2556
2557 /**
2558 * Formats an alarm like platform/packages/apps/DeskClock used to.
2559 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002560 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2561 int userId) {
2562 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002563 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2564 return (info == null) ? "" :
2565 DateFormat.format(pattern, info.getTriggerTime()).toString();
2566 }
2567
Adam Lesinski182f73f2013-12-05 16:48:06 -08002568 void rescheduleKernelAlarmsLocked() {
2569 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2570 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002571 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002572 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002573 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002574 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002575 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002576 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002577 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002578 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002579 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002580 if (firstBatch != firstWakeup) {
2581 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002582 }
2583 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002584 if (mPendingNonWakeupAlarms.size() > 0) {
2585 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2586 nextNonWakeup = mNextNonWakeupDeliveryTime;
2587 }
2588 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002589 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002590 mNextNonWakeup = nextNonWakeup;
2591 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2592 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002593 }
2594
Christopher Tate14a7bb02015-10-01 10:24:31 -07002595 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002596 if (operation == null && directReceiver == null) {
2597 if (localLOGV) {
2598 Slog.w(TAG, "requested remove() of null operation",
2599 new RuntimeException("here"));
2600 }
2601 return;
2602 }
2603
Adam Lesinski182f73f2013-12-05 16:48:06 -08002604 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002605 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002606 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2607 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002608 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002609 if (b.size() == 0) {
2610 mAlarmBatches.remove(i);
2611 }
2612 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002613 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002614 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002615 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2616 mPendingWhileIdleAlarms.remove(i);
2617 }
2618 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002619 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2620 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2621 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2622 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2623 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2624 alarmsForUid.remove(j);
2625 }
2626 }
2627 if (alarmsForUid.size() == 0) {
2628 mPendingBackgroundAlarms.removeAt(i);
2629 }
2630 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002631 if (didRemove) {
2632 if (DEBUG_BATCH) {
2633 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2634 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002635 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002636 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002637 mPendingIdleUntil = null;
2638 restorePending = true;
2639 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002640 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002641 mNextWakeFromIdle = null;
2642 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002643 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002644 if (restorePending) {
2645 restorePendingWhileIdleAlarmsLocked();
2646 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002647 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002648 }
2649 }
2650
Christopher Tate1d99c392017-12-07 16:54:04 -08002651 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002652 if (uid == Process.SYSTEM_UID) {
2653 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2654 return;
2655 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002656 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002657 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002658 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2659 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002660 didRemove |= b.remove(whichAlarms);
2661 if (b.size() == 0) {
2662 mAlarmBatches.remove(i);
2663 }
2664 }
2665 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2666 final Alarm a = mPendingWhileIdleAlarms.get(i);
2667 if (a.uid == uid) {
2668 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2669 mPendingWhileIdleAlarms.remove(i);
2670 }
2671 }
2672 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2673 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2674 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2675 if (alarmsForUid.get(j).uid == uid) {
2676 alarmsForUid.remove(j);
2677 }
2678 }
2679 if (alarmsForUid.size() == 0) {
2680 mPendingBackgroundAlarms.removeAt(i);
2681 }
2682 }
2683 if (didRemove) {
2684 if (DEBUG_BATCH) {
2685 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2686 }
2687 rebatchAllAlarmsLocked(true);
2688 rescheduleKernelAlarmsLocked();
2689 updateNextAlarmClockLocked();
2690 }
2691 }
2692
2693 void removeLocked(final String packageName) {
2694 if (packageName == null) {
2695 if (localLOGV) {
2696 Slog.w(TAG, "requested remove() of null packageName",
2697 new RuntimeException("here"));
2698 }
2699 return;
2700 }
2701
2702 boolean didRemove = false;
2703 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002704 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002705 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2706 Batch b = mAlarmBatches.get(i);
2707 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002708 if (b.size() == 0) {
2709 mAlarmBatches.remove(i);
2710 }
2711 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002712 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2713 if (oldHasTick != newHasTick) {
2714 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2715 }
2716
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002717 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002718 final Alarm a = mPendingWhileIdleAlarms.get(i);
2719 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002720 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2721 mPendingWhileIdleAlarms.remove(i);
2722 }
2723 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002724 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2725 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2726 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2727 if (alarmsForUid.get(j).matches(packageName)) {
2728 alarmsForUid.remove(j);
2729 }
2730 }
2731 if (alarmsForUid.size() == 0) {
2732 mPendingBackgroundAlarms.removeAt(i);
2733 }
2734 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002735 if (didRemove) {
2736 if (DEBUG_BATCH) {
2737 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2738 }
2739 rebatchAllAlarmsLocked(true);
2740 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002741 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002742 }
2743 }
2744
Christopher Tate1d99c392017-12-07 16:54:04 -08002745 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002746 if (uid == Process.SYSTEM_UID) {
2747 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2748 return;
2749 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002750 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002751 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2752 try {
2753 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2754 uid, a.packageName)) {
2755 return true;
2756 }
2757 } catch (RemoteException e) { /* fall through */}
2758 return false;
2759 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002760 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2761 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002762 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002763 if (b.size() == 0) {
2764 mAlarmBatches.remove(i);
2765 }
2766 }
2767 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2768 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002769 if (a.uid == uid) {
2770 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2771 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002772 }
2773 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002774 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2775 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2776 mPendingBackgroundAlarms.removeAt(i);
2777 }
2778 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002779 if (didRemove) {
2780 if (DEBUG_BATCH) {
2781 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2782 }
2783 rebatchAllAlarmsLocked(true);
2784 rescheduleKernelAlarmsLocked();
2785 updateNextAlarmClockLocked();
2786 }
2787 }
2788
Adam Lesinski182f73f2013-12-05 16:48:06 -08002789 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002790 if (userHandle == UserHandle.USER_SYSTEM) {
2791 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2792 return;
2793 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002795 final Predicate<Alarm> whichAlarms =
2796 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002797 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2798 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002799 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002800 if (b.size() == 0) {
2801 mAlarmBatches.remove(i);
2802 }
2803 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002804 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002805 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002806 == userHandle) {
2807 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2808 mPendingWhileIdleAlarms.remove(i);
2809 }
2810 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002811 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2812 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2813 mPendingBackgroundAlarms.removeAt(i);
2814 }
2815 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002816 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2817 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2818 mLastAllowWhileIdleDispatch.removeAt(i);
2819 }
2820 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002821
2822 if (didRemove) {
2823 if (DEBUG_BATCH) {
2824 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2825 }
2826 rebatchAllAlarmsLocked(true);
2827 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002828 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002829 }
2830 }
2831
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002832 void interactiveStateChangedLocked(boolean interactive) {
2833 if (mInteractive != interactive) {
2834 mInteractive = interactive;
2835 final long nowELAPSED = SystemClock.elapsedRealtime();
2836 if (interactive) {
2837 if (mPendingNonWakeupAlarms.size() > 0) {
2838 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2839 mTotalDelayTime += thisDelayTime;
2840 if (mMaxDelayTime < thisDelayTime) {
2841 mMaxDelayTime = thisDelayTime;
2842 }
2843 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2844 mPendingNonWakeupAlarms.clear();
2845 }
2846 if (mNonInteractiveStartTime > 0) {
2847 long dur = nowELAPSED - mNonInteractiveStartTime;
2848 if (dur > mNonInteractiveTime) {
2849 mNonInteractiveTime = dur;
2850 }
2851 }
2852 } else {
2853 mNonInteractiveStartTime = nowELAPSED;
2854 }
2855 }
2856 }
2857
Adam Lesinski182f73f2013-12-05 16:48:06 -08002858 boolean lookForPackageLocked(String packageName) {
2859 for (int i = 0; i < mAlarmBatches.size(); i++) {
2860 Batch b = mAlarmBatches.get(i);
2861 if (b.hasPackage(packageName)) {
2862 return true;
2863 }
2864 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002865 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002866 final Alarm a = mPendingWhileIdleAlarms.get(i);
2867 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002868 return true;
2869 }
2870 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002871 return false;
2872 }
2873
2874 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002875 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002876 // The kernel never triggers alarms with negative wakeup times
2877 // so we ensure they are positive.
2878 long alarmSeconds, alarmNanoseconds;
2879 if (when < 0) {
2880 alarmSeconds = 0;
2881 alarmNanoseconds = 0;
2882 } else {
2883 alarmSeconds = when / 1000;
2884 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2885 }
Kweku Adams61e03292017-10-19 14:27:12 -07002886
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002887 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002888 } else {
2889 Message msg = Message.obtain();
2890 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002891
Adam Lesinski182f73f2013-12-05 16:48:06 -08002892 mHandler.removeMessages(ALARM_EVENT);
2893 mHandler.sendMessageAtTime(msg, when);
2894 }
2895 }
2896
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002897 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002898 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002899 for (int i=list.size()-1; i>=0; i--) {
2900 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002901 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2902 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002903 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002904 }
2905 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002906
2907 private static final String labelForType(int type) {
2908 switch (type) {
2909 case RTC: return "RTC";
2910 case RTC_WAKEUP : return "RTC_WAKEUP";
2911 case ELAPSED_REALTIME : return "ELAPSED";
2912 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002913 }
2914 return "--unknown--";
2915 }
2916
2917 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002918 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002919 for (int i=list.size()-1; i>=0; i--) {
2920 Alarm a = list.get(i);
2921 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002922 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2923 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002924 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002925 }
2926 }
2927
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002928 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002929 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002930 if (alarm.alarmClock != null) {
2931 // Don't block alarm clocks
2932 return false;
2933 }
2934 if (alarm.operation != null
2935 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2936 // Don't block starting foreground components
2937 return false;
2938 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002939 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002940 final int sourceUid = alarm.creatorUid;
Makoto Onuki2f0b0312018-02-08 02:30:27 +00002941 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage,
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002942 allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002943 }
2944
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002945 private native long init();
2946 private native void close(long nativeData);
2947 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2948 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002949 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002950 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951
Makoto Onukiadb50d82018-01-29 16:20:30 -08002952 private long getWhileIdleMinIntervalLocked(int uid) {
2953 final boolean dozing = mPendingIdleUntil != null;
Makoto Onuki2f0b0312018-02-08 02:30:27 +00002954 final boolean ebs = mForceAppStandbyTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08002955 if (!dozing && !ebs) {
2956 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2957 }
2958 if (dozing) {
2959 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2960 }
2961 if (mUseAllowWhileIdleShortTime.get(uid)) {
2962 // if the last allow-while-idle went off while uid was fg, or the uid
2963 // recently came into fg, don't block the alarm for long.
2964 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2965 }
2966 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2967 }
2968
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002969 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002970 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002971 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002972 // batches are temporally sorted, so we need only pull from the
2973 // start of the list until we either empty it or hit a batch
2974 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002975 while (mAlarmBatches.size() > 0) {
2976 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002977 if (batch.start > nowELAPSED) {
2978 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002979 break;
2980 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002981
Christopher Tatee0a22b32013-07-11 14:43:13 -07002982 // We will (re)schedule some alarms now; don't let that interfere
2983 // with delivery of this current batch
2984 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002985
Christopher Tatee0a22b32013-07-11 14:43:13 -07002986 final int N = batch.size();
2987 for (int i = 0; i < N; i++) {
2988 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002989
2990 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2991 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2992 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002993 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002994 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002995 if (nowELAPSED < minTime) {
2996 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2997 // alarm went off for this app. Reschedule the alarm to be in the
2998 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08002999 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003000 if (alarm.maxWhenElapsed < minTime) {
3001 alarm.maxWhenElapsed = minTime;
3002 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003003 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003004 if (RECORD_DEVICE_IDLE_ALARMS) {
3005 IdleDispatchEntry ent = new IdleDispatchEntry();
3006 ent.uid = alarm.uid;
3007 ent.pkg = alarm.operation.getCreatorPackage();
3008 ent.tag = alarm.operation.getTag("");
3009 ent.op = "RESCHEDULE";
3010 ent.elapsedRealtime = nowELAPSED;
3011 ent.argRealtime = lastTime;
3012 mAllowWhileIdleDispatches.add(ent);
3013 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003014 setImplLocked(alarm, true, false);
3015 continue;
3016 }
3017 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003018 if (isBackgroundRestricted(alarm)) {
3019 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3020 if (DEBUG_BG_LIMIT) {
3021 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3022 }
3023 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3024 if (alarmsForUid == null) {
3025 alarmsForUid = new ArrayList<>();
3026 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3027 }
3028 alarmsForUid.add(alarm);
3029 continue;
3030 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003031
Christopher Tatee0a22b32013-07-11 14:43:13 -07003032 alarm.count = 1;
3033 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003034 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3035 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003036 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003037 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003038 if (mPendingIdleUntil == alarm) {
3039 mPendingIdleUntil = null;
3040 rebatchAllAlarmsLocked(false);
3041 restorePendingWhileIdleAlarmsLocked();
3042 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003043 if (mNextWakeFromIdle == alarm) {
3044 mNextWakeFromIdle = null;
3045 rebatchAllAlarmsLocked(false);
3046 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003047
3048 // Recurring alarms may have passed several alarm intervals while the
3049 // phone was asleep or off, so pass a trigger count when sending them.
3050 if (alarm.repeatInterval > 0) {
3051 // this adjustment will be zero if we're late by
3052 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003053 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003054
3055 // Also schedule its next recurrence
3056 final long delta = alarm.count * alarm.repeatInterval;
3057 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003058 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003059 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003060 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3061 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003062 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003063
Christopher Tate864d42e2014-12-02 11:48:53 -08003064 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003065 hasWakeup = true;
3066 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003067
3068 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3069 if (alarm.alarmClock != null) {
3070 mNextAlarmClockMayChange = true;
3071 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003073 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003074
Christopher Tate1590f1e2014-10-02 17:27:57 -07003075 // This is a new alarm delivery set; bump the sequence number to indicate that
3076 // all apps' alarm delivery classes should be recalculated.
3077 mCurrentSeq++;
3078 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003079 Collections.sort(triggerList, mAlarmDispatchComparator);
3080
3081 if (localLOGV) {
3082 for (int i=0; i<triggerList.size(); i++) {
3083 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3084 }
3085 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003086
3087 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003089
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090 /**
3091 * This Comparator sorts Alarms into increasing time order.
3092 */
3093 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3094 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003095 long when1 = a1.whenElapsed;
3096 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003097 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 return 1;
3099 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003100 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003101 return -1;
3102 }
3103 return 0;
3104 }
3105 }
Kweku Adams61e03292017-10-19 14:27:12 -07003106
Makoto Onuki2206af32017-11-21 16:25:35 -08003107 @VisibleForTesting
3108 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003109 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003110 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003111 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003112 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003113 public final IAlarmListener listener;
3114 public final String listenerTag;
3115 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003116 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003117 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003118 public final AlarmManager.AlarmClockInfo alarmClock;
3119 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003120 public final int creatorUid;
3121 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003122 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003123 public int count;
3124 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003125 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003126 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003127 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003128 // Expected alarm expiry time before app standby deferring is applied.
3129 public long expectedWhenElapsed;
3130 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003131 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003132 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003133
Christopher Tate3e04b472013-10-21 17:51:31 -07003134 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003135 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3136 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3137 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003138 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003139 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003140 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3141 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003142 when = _when;
3143 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003144 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003145 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003146 maxWhenElapsed = _maxWhen;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003147 expectedMaxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003148 repeatInterval = _interval;
3149 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003150 listener = _rec;
3151 listenerTag = _listenerTag;
3152 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003153 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003154 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003155 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003156 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003157 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003158 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003159 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003161
Christopher Tate14a7bb02015-10-01 10:24:31 -07003162 public static String makeTag(PendingIntent pi, String tag, int type) {
3163 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3164 ? "*walarm*:" : "*alarm*:";
3165 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3166 }
3167
3168 public WakeupEvent makeWakeupEvent(long nowRTC) {
3169 return new WakeupEvent(nowRTC, creatorUid,
3170 (operation != null)
3171 ? operation.getIntent().getAction()
3172 : ("<listener>:" + listenerTag));
3173 }
3174
3175 // Returns true if either matches
3176 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3177 return (operation != null)
3178 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003179 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003180 }
3181
3182 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003183 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003184 }
3185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003186 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003187 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003188 StringBuilder sb = new StringBuilder(128);
3189 sb.append("Alarm{");
3190 sb.append(Integer.toHexString(System.identityHashCode(this)));
3191 sb.append(" type ");
3192 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003193 sb.append(" when ");
3194 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003195 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003196 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003197 sb.append('}');
3198 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 }
3200
Kweku Adams61e03292017-10-19 14:27:12 -07003201 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003202 SimpleDateFormat sdf) {
3203 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003204 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003205 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003206 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3207 expectedWhenElapsed, nowELAPSED, pw);
3208 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3209 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003210 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3211 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003212 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003213 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003214 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003215 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003216 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003217 }
3218 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003219 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003220 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003221 pw.print(" count="); pw.print(count);
3222 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003223 if (alarmClock != null) {
3224 pw.print(prefix); pw.println("Alarm clock:");
3225 pw.print(prefix); pw.print(" triggerTime=");
3226 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3227 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3228 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003229 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003230 if (listener != null) {
3231 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3232 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 }
Kweku Adams61e03292017-10-19 14:27:12 -07003234
3235 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3236 long nowRTC) {
3237 final long token = proto.start(fieldId);
3238
3239 proto.write(AlarmProto.TAG, statsTag);
3240 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003241 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003242 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3243 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3244 proto.write(AlarmProto.COUNT, count);
3245 proto.write(AlarmProto.FLAGS, flags);
3246 if (alarmClock != null) {
3247 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3248 }
3249 if (operation != null) {
3250 operation.writeToProto(proto, AlarmProto.OPERATION);
3251 }
3252 if (listener != null) {
3253 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3254 }
3255
3256 proto.end(token);
3257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003259
Christopher Tatee0a22b32013-07-11 14:43:13 -07003260 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3261 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003262 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3263 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003264 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003265 break;
3266 }
3267
Christopher Tatee0a22b32013-07-11 14:43:13 -07003268 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003269 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3270 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003271 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003272 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003273 }
3274 }
3275
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003276 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3277 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3278 if (timeSinceOn < 5*60*1000) {
3279 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3280 return 2*60*1000;
3281 } else if (timeSinceOn < 30*60*1000) {
3282 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3283 return 15*60*1000;
3284 } else {
3285 // Otherwise, we will delay by at most an hour.
3286 return 60*60*1000;
3287 }
3288 }
3289
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003290 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003291 if (duration < 15*60*1000) {
3292 // If the duration until the time is less than 15 minutes, the maximum fuzz
3293 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003294 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003295 } else if (duration < 90*60*1000) {
3296 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3297 return 15*60*1000;
3298 } else {
3299 // Otherwise, we will fuzz by at most half an hour.
3300 return 30*60*1000;
3301 }
3302 }
3303
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003304 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3305 if (mInteractive) {
3306 return false;
3307 }
3308 if (mLastAlarmDeliveryTime <= 0) {
3309 return false;
3310 }
minho.choo649acab2014-12-12 16:13:55 +09003311 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003312 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3313 // and the next delivery time is in the past, then just deliver them all. This
3314 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3315 return false;
3316 }
3317 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3318 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3319 }
3320
3321 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3322 mLastAlarmDeliveryTime = nowELAPSED;
3323 for (int i=0; i<triggerList.size(); i++) {
3324 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003325 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003326 if (alarm.wakeup) {
3327 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3328 } else {
3329 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3330 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003331 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003332 if (localLOGV) {
3333 Slog.v(TAG, "sending alarm " + alarm);
3334 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003335 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003336 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3337 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003338 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003339 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003340 } catch (RuntimeException e) {
3341 Slog.w(TAG, "Failure sending alarm.", e);
3342 }
Tim Murray175c0f92017-11-28 15:01:04 -08003343 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003344 }
3345 }
3346
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003347 private boolean isExemptFromAppStandby(Alarm a) {
3348 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3349 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3350 }
3351
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003352 private class AlarmThread extends Thread
3353 {
3354 public AlarmThread()
3355 {
3356 super("AlarmManager");
3357 }
Kweku Adams61e03292017-10-19 14:27:12 -07003358
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 public void run()
3360 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003361 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 while (true)
3364 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003365 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003366 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003367
3368 triggerList.clear();
3369
Dianne Hackbornc3527222015-05-13 14:03:20 -07003370 final long nowRTC = System.currentTimeMillis();
3371 final long nowELAPSED = SystemClock.elapsedRealtime();
3372
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003373 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003374 // The kernel can give us spurious time change notifications due to
3375 // small adjustments it makes internally; we want to filter those out.
3376 final long lastTimeChangeClockTime;
3377 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003378 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003379 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3380 expectedClockTime = lastTimeChangeClockTime
3381 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003382 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003383 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3384 || nowRTC > (expectedClockTime+1000)) {
3385 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003386 // let's do it!
3387 if (DEBUG_BATCH) {
3388 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3389 }
3390 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003391 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003392 rebatchAllAlarms();
3393 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003394 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003395 synchronized (mLock) {
3396 mNumTimeChanged++;
3397 mLastTimeChangeClockTime = nowRTC;
3398 mLastTimeChangeRealtime = nowELAPSED;
3399 }
3400 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3401 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003402 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003403 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3404 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003405 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3406
3407 // The world has changed on us, so we need to re-evaluate alarms
3408 // regardless of whether the kernel has told us one went off.
3409 result |= IS_WAKEUP_MASK;
3410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412
Dianne Hackbornc3527222015-05-13 14:03:20 -07003413 if (result != TIME_CHANGED_MASK) {
3414 // If this was anything besides just a time change, then figure what if
3415 // anything to do about alarms.
3416 synchronized (mLock) {
3417 if (localLOGV) Slog.v(
3418 TAG, "Checking for alarms... rtc=" + nowRTC
3419 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003420
Dianne Hackbornc3527222015-05-13 14:03:20 -07003421 if (WAKEUP_STATS) {
3422 if ((result & IS_WAKEUP_MASK) != 0) {
3423 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3424 int n = 0;
3425 for (WakeupEvent event : mRecentWakeups) {
3426 if (event.when > newEarliest) break;
3427 n++; // number of now-stale entries at the list head
3428 }
3429 for (int i = 0; i < n; i++) {
3430 mRecentWakeups.remove();
3431 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003432
Dianne Hackbornc3527222015-05-13 14:03:20 -07003433 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003434 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003435 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003436
3437 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3438 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3439 // if there are no wakeup alarms and the screen is off, we can
3440 // delay what we have so far until the future.
3441 if (mPendingNonWakeupAlarms.size() == 0) {
3442 mStartCurrentDelayTime = nowELAPSED;
3443 mNextNonWakeupDeliveryTime = nowELAPSED
3444 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3445 }
3446 mPendingNonWakeupAlarms.addAll(triggerList);
3447 mNumDelayedAlarms += triggerList.size();
3448 rescheduleKernelAlarmsLocked();
3449 updateNextAlarmClockLocked();
3450 } else {
3451 // now deliver the alarm intents; if there are pending non-wakeup
3452 // alarms, we need to merge them in to the list. note we don't
3453 // just deliver them first because we generally want non-wakeup
3454 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003455 if (mPendingNonWakeupAlarms.size() > 0) {
3456 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3457 triggerList.addAll(mPendingNonWakeupAlarms);
3458 Collections.sort(triggerList, mAlarmDispatchComparator);
3459 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3460 mTotalDelayTime += thisDelayTime;
3461 if (mMaxDelayTime < thisDelayTime) {
3462 mMaxDelayTime = thisDelayTime;
3463 }
3464 mPendingNonWakeupAlarms.clear();
3465 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003466 final ArraySet<Pair<String, Integer>> triggerPackages =
3467 new ArraySet<>();
3468 for (int i = 0; i < triggerList.size(); i++) {
3469 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003470 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003471 triggerPackages.add(Pair.create(
3472 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003473 }
3474 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003475 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003476 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3477 rescheduleKernelAlarmsLocked();
3478 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003479 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003480 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003481
3482 } else {
3483 // Just in case -- even though no wakeup flag was set, make sure
3484 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003485 synchronized (mLock) {
3486 rescheduleKernelAlarmsLocked();
3487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488 }
3489 }
3490 }
3491 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003492
David Christieebe51fc2013-07-26 13:23:29 -07003493 /**
3494 * Attribute blame for a WakeLock.
3495 * @param pi PendingIntent to attribute blame to if ws is null.
3496 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003497 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003498 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003499 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003500 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003501 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003502 final boolean unimportant = pi == mTimeTickSender;
3503 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003504 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003505 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003506 } else {
3507 mWakeLock.setHistoryTag(null);
3508 }
3509 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003510 if (ws != null) {
3511 mWakeLock.setWorkSource(ws);
3512 return;
3513 }
3514
Christopher Tate14a7bb02015-10-01 10:24:31 -07003515 final int uid = (knownUid >= 0)
3516 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003517 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003518 if (uid >= 0) {
3519 mWakeLock.setWorkSource(new WorkSource(uid));
3520 return;
3521 }
3522 } catch (Exception e) {
3523 }
3524
3525 // Something went wrong; fall back to attributing the lock to the OS
3526 mWakeLock.setWorkSource(null);
3527 }
3528
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003529 private class AlarmHandler extends Handler {
3530 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003531 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3532 public static final int LISTENER_TIMEOUT = 3;
3533 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003534 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3535 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003536 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003537
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003538 public AlarmHandler() {
3539 }
Kweku Adams61e03292017-10-19 14:27:12 -07003540
Makoto Onuki4d298b52018-02-05 10:54:58 -08003541 public void postRemoveForStopped(int uid) {
3542 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3543 }
3544
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003546 switch (msg.what) {
3547 case ALARM_EVENT: {
3548 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3549 synchronized (mLock) {
3550 final long nowRTC = System.currentTimeMillis();
3551 final long nowELAPSED = SystemClock.elapsedRealtime();
3552 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3553 updateNextAlarmClockLocked();
3554 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003555
Christopher Tate14a7bb02015-10-01 10:24:31 -07003556 // now trigger the alarms without the lock held
3557 for (int i=0; i<triggerList.size(); i++) {
3558 Alarm alarm = triggerList.get(i);
3559 try {
3560 alarm.operation.send();
3561 } catch (PendingIntent.CanceledException e) {
3562 if (alarm.repeatInterval > 0) {
3563 // This IntentSender is no longer valid, but this
3564 // is a repeating alarm, so toss the hoser.
3565 removeImpl(alarm.operation);
3566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 }
3568 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003569 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003570 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003571
3572 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3573 sendNextAlarmClockChanged();
3574 break;
3575
3576 case LISTENER_TIMEOUT:
3577 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3578 break;
3579
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003580 case REPORT_ALARMS_ACTIVE:
3581 if (mLocalDeviceIdleController != null) {
3582 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3583 }
3584 break;
3585
Suprabh Shukla75edab12018-01-29 14:09:06 -08003586 case APP_STANDBY_PAROLE_CHANGED:
3587 synchronized (mLock) {
3588 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003589 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3590 rescheduleKernelAlarmsLocked();
3591 updateNextAlarmClockLocked();
3592 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003593 }
3594 break;
3595
3596 case APP_STANDBY_BUCKET_CHANGED:
3597 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003598 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3599 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3600 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3601 rescheduleKernelAlarmsLocked();
3602 updateNextAlarmClockLocked();
3603 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003604 }
3605 break;
3606
Makoto Onuki4d298b52018-02-05 10:54:58 -08003607 case REMOVE_FOR_STOPPED:
3608 synchronized (mLock) {
3609 removeForStoppedLocked(msg.arg1);
3610 }
3611 break;
3612
Christopher Tate14a7bb02015-10-01 10:24:31 -07003613 default:
3614 // nope, just ignore it
3615 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 }
3617 }
3618 }
Kweku Adams61e03292017-10-19 14:27:12 -07003619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 class ClockReceiver extends BroadcastReceiver {
3621 public ClockReceiver() {
3622 IntentFilter filter = new IntentFilter();
3623 filter.addAction(Intent.ACTION_TIME_TICK);
3624 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003625 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 }
Kweku Adams61e03292017-10-19 14:27:12 -07003627
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 @Override
3629 public void onReceive(Context context, Intent intent) {
3630 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003631 if (DEBUG_BATCH) {
3632 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3633 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003634 synchronized (mLock) {
3635 mLastTickReceived = System.currentTimeMillis();
3636 }
Christopher Tate385e4982013-07-23 18:22:29 -07003637 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3639 // Since the kernel does not keep track of DST, we need to
3640 // reset the TZ information at the beginning of each day
3641 // based off of the current Zone gmt offset + userspace tracked
3642 // daylight savings information.
3643 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003644 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003645 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003646 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 }
3648 }
Kweku Adams61e03292017-10-19 14:27:12 -07003649
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003651 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003652 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003653
3654 // Schedule this event for the amount of time that it would take to get to
3655 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003656 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003657
David Christieebe51fc2013-07-26 13:23:29 -07003658 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003659 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003660 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3661 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003662
3663 // Finally, remember when we set the tick alarm
3664 synchronized (mLock) {
3665 mLastTickSet = currentTime;
3666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 }
Christopher Tate385e4982013-07-23 18:22:29 -07003668
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003669 public void scheduleDateChangedEvent() {
3670 Calendar calendar = Calendar.getInstance();
3671 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003672 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 calendar.set(Calendar.MINUTE, 0);
3674 calendar.set(Calendar.SECOND, 0);
3675 calendar.set(Calendar.MILLISECOND, 0);
3676 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003677
3678 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003679 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3680 AlarmManager.FLAG_STANDALONE, workSource, null,
3681 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 }
3683 }
Kweku Adams61e03292017-10-19 14:27:12 -07003684
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003685 class InteractiveStateReceiver extends BroadcastReceiver {
3686 public InteractiveStateReceiver() {
3687 IntentFilter filter = new IntentFilter();
3688 filter.addAction(Intent.ACTION_SCREEN_OFF);
3689 filter.addAction(Intent.ACTION_SCREEN_ON);
3690 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3691 getContext().registerReceiver(this, filter);
3692 }
3693
3694 @Override
3695 public void onReceive(Context context, Intent intent) {
3696 synchronized (mLock) {
3697 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3698 }
3699 }
3700 }
3701
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003702 class UninstallReceiver extends BroadcastReceiver {
3703 public UninstallReceiver() {
3704 IntentFilter filter = new IntentFilter();
3705 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3706 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003707 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003709 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003710 // Register for events related to sdcard installation.
3711 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003712 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003713 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003714 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003715 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003716 }
Kweku Adams61e03292017-10-19 14:27:12 -07003717
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 @Override
3719 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003720 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003722 String action = intent.getAction();
3723 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003724 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3725 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3726 for (String packageName : pkgList) {
3727 if (lookForPackageLocked(packageName)) {
3728 setResultCode(Activity.RESULT_OK);
3729 return;
3730 }
3731 }
3732 return;
3733 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003734 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003735 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3736 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3737 if (userHandle >= 0) {
3738 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003739 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3740 final Pair<String, Integer> packageUser =
3741 mLastAlarmDeliveredForPackage.keyAt(i);
3742 if (packageUser.second == userHandle) {
3743 mLastAlarmDeliveredForPackage.removeAt(i);
3744 }
3745 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003746 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003747 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003748 if (uid >= 0) {
3749 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003750 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003751 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003752 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003753 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3754 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3755 // This package is being updated; don't kill its alarms.
3756 return;
3757 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003758 Uri data = intent.getData();
3759 if (data != null) {
3760 String pkg = data.getSchemeSpecificPart();
3761 if (pkg != null) {
3762 pkgList = new String[]{pkg};
3763 }
3764 }
3765 }
3766 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003767 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3768 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3769 if (ArrayUtils.contains(pkgList, packageUser.first)
3770 && packageUser.second == UserHandle.getUserId(uid)) {
3771 mLastAlarmDeliveredForPackage.removeAt(i);
3772 }
3773 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003774 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003775 if (uid >= 0) {
3776 // package-removed case
3777 removeLocked(uid);
3778 } else {
3779 // external-applications-unavailable etc case
3780 removeLocked(pkg);
3781 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003782 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003783 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3784 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3785 if (uidStats.remove(pkg) != null) {
3786 if (uidStats.size() <= 0) {
3787 mBroadcastStats.removeAt(i);
3788 }
3789 }
3790 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003791 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 }
3793 }
3794 }
3795 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003796
3797 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003798 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003799 }
3800
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003801 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003802 if (disabled) {
3803 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003804 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003805 }
3806
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003807 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003808 }
3809
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003810 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003811 if (disabled) {
3812 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003813 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003814 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003815
3816 @Override public void onUidCachedChanged(int uid, boolean cached) {
3817 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003818 };
3819
Suprabh Shukla75edab12018-01-29 14:09:06 -08003820 /**
3821 * Tracking of app assignments to standby buckets
3822 */
3823 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3824 @Override
3825 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
3826 boolean idle, int bucket) {
3827 if (DEBUG_STANDBY) {
3828 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3829 bucket);
3830 }
3831 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003832 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3833 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003834 }
3835
3836 @Override
3837 public void onParoleStateChanged(boolean isParoleOn) {
3838 if (DEBUG_STANDBY) {
3839 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3840 }
3841 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3842 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3843 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3844 Boolean.valueOf(isParoleOn)).sendToTarget();
3845 }
3846 };
3847
Makoto Onuki2206af32017-11-21 16:25:35 -08003848 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003849 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003850 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003851 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003852 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003853 }
3854 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003855
3856 @Override
3857 public void unblockAlarmsForUid(int uid) {
3858 synchronized (mLock) {
3859 sendPendingBackgroundAlarmsLocked(uid, null);
3860 }
3861 }
3862
3863 @Override
3864 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3865 synchronized (mLock) {
3866 sendPendingBackgroundAlarmsLocked(uid, packageName);
3867 }
3868 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003869
3870 @Override
3871 public void onUidForeground(int uid, boolean foreground) {
3872 synchronized (mLock) {
3873 if (foreground) {
3874 mUseAllowWhileIdleShortTime.put(uid, true);
3875
3876 // Note we don't have to drain the pending while-idle alarms here, because
3877 // this event should coincide with unblockAlarmsForUid().
3878 }
3879 }
3880 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003881 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003882
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003884 String pkg = pi.getCreatorPackage();
3885 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003886 return getStatsLocked(uid, pkg);
3887 }
3888
3889 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003890 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3891 if (uidStats == null) {
3892 uidStats = new ArrayMap<String, BroadcastStats>();
3893 mBroadcastStats.put(uid, uidStats);
3894 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003895 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003896 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003897 bs = new BroadcastStats(uid, pkgName);
3898 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003899 }
3900 return bs;
3901 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003902
Christopher Tate21e9f192017-08-08 13:49:11 -07003903 /**
3904 * Canonical count of (operation.send() - onSendFinished()) and
3905 * listener send/complete/timeout invocations.
3906 * Guarded by the usual lock.
3907 */
3908 @GuardedBy("mLock")
3909 private int mSendCount = 0;
3910 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003911 private int mSendFinishCount = 0;
3912 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003913 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003914 @GuardedBy("mLock")
3915 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003916
Christopher Tate14a7bb02015-10-01 10:24:31 -07003917 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003918
Christopher Tate14a7bb02015-10-01 10:24:31 -07003919 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3920 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003921 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003922 return mInFlight.remove(i);
3923 }
3924 }
3925 mLog.w("No in-flight alarm for " + pi + " " + intent);
3926 return null;
3927 }
3928
3929 private InFlight removeLocked(IBinder listener) {
3930 for (int i = 0; i < mInFlight.size(); i++) {
3931 if (mInFlight.get(i).mListener == listener) {
3932 return mInFlight.remove(i);
3933 }
3934 }
3935 mLog.w("No in-flight alarm for listener " + listener);
3936 return null;
3937 }
3938
3939 private void updateStatsLocked(InFlight inflight) {
3940 final long nowELAPSED = SystemClock.elapsedRealtime();
3941 BroadcastStats bs = inflight.mBroadcastStats;
3942 bs.nesting--;
3943 if (bs.nesting <= 0) {
3944 bs.nesting = 0;
3945 bs.aggregateTime += nowELAPSED - bs.startTime;
3946 }
3947 FilterStats fs = inflight.mFilterStats;
3948 fs.nesting--;
3949 if (fs.nesting <= 0) {
3950 fs.nesting = 0;
3951 fs.aggregateTime += nowELAPSED - fs.startTime;
3952 }
3953 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003954 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3955 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003956 }
3957 }
3958
3959 private void updateTrackingLocked(InFlight inflight) {
3960 if (inflight != null) {
3961 updateStatsLocked(inflight);
3962 }
3963 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003964 if (DEBUG_WAKELOCK) {
3965 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3966 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003967 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003968 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003969 mWakeLock.release();
3970 if (mInFlight.size() > 0) {
3971 mLog.w("Finished all dispatches with " + mInFlight.size()
3972 + " remaining inflights");
3973 for (int i=0; i<mInFlight.size(); i++) {
3974 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3975 }
3976 mInFlight.clear();
3977 }
3978 } else {
3979 // the next of our alarms is now in flight. reattribute the wakelock.
3980 if (mInFlight.size() > 0) {
3981 InFlight inFlight = mInFlight.get(0);
3982 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3983 inFlight.mAlarmType, inFlight.mTag, -1, false);
3984 } else {
3985 // should never happen
3986 mLog.w("Alarm wakelock still held but sent queue empty");
3987 mWakeLock.setWorkSource(null);
3988 }
3989 }
3990 }
3991
3992 /**
3993 * Callback that arrives when a direct-call alarm reports that delivery has finished
3994 */
3995 @Override
3996 public void alarmComplete(IBinder who) {
3997 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003998 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003999 + " pid=" + Binder.getCallingPid());
4000 return;
4001 }
4002
4003 final long ident = Binder.clearCallingIdentity();
4004 try {
4005 synchronized (mLock) {
4006 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4007 InFlight inflight = removeLocked(who);
4008 if (inflight != null) {
4009 if (DEBUG_LISTENER_CALLBACK) {
4010 Slog.i(TAG, "alarmComplete() from " + who);
4011 }
4012 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004013 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004014 } else {
4015 // Delivery timed out, and the timeout handling already took care of
4016 // updating our tracking here, so we needn't do anything further.
4017 if (DEBUG_LISTENER_CALLBACK) {
4018 Slog.i(TAG, "Late alarmComplete() from " + who);
4019 }
4020 }
4021 }
4022 } finally {
4023 Binder.restoreCallingIdentity(ident);
4024 }
4025 }
4026
4027 /**
4028 * Callback that arrives when a PendingIntent alarm has finished delivery
4029 */
4030 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004031 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4032 String resultData, Bundle resultExtras) {
4033 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004034 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004035 updateTrackingLocked(removeLocked(pi, intent));
4036 }
4037 }
4038
4039 /**
4040 * Timeout of a direct-call alarm delivery
4041 */
4042 public void alarmTimedOut(IBinder who) {
4043 synchronized (mLock) {
4044 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004045 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004046 // TODO: implement ANR policy for the target
4047 if (DEBUG_LISTENER_CALLBACK) {
4048 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004049 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004050 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004051 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004052 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004053 if (DEBUG_LISTENER_CALLBACK) {
4054 Slog.i(TAG, "Spurious timeout of listener " + who);
4055 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004056 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004057 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004058 }
4059 }
4060
4061 /**
4062 * Deliver an alarm and set up the post-delivery handling appropriately
4063 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004064 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004065 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4066 if (alarm.operation != null) {
4067 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004068 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004069
4070 if (alarm.priorityClass.priority == PRIO_TICK) {
4071 mLastTickIssued = nowELAPSED;
4072 }
4073
Christopher Tate14a7bb02015-10-01 10:24:31 -07004074 try {
4075 alarm.operation.send(getContext(), 0,
4076 mBackgroundIntent.putExtra(
4077 Intent.EXTRA_ALARM_COUNT, alarm.count),
4078 mDeliveryTracker, mHandler, null,
4079 allowWhileIdle ? mIdleOptions : null);
4080 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004081 if (alarm.operation == mTimeTickSender) {
4082 Slog.wtf(TAG, "mTimeTickSender canceled");
4083 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004084 if (alarm.repeatInterval > 0) {
4085 // This IntentSender is no longer valid, but this
4086 // is a repeating alarm, so toss it
4087 removeImpl(alarm.operation);
4088 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004089 // No actual delivery was possible, so the delivery tracker's
4090 // 'finished' callback won't be invoked. We also don't need
4091 // to do any wakelock or stats tracking, so we have nothing
4092 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004093 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004094 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004095 }
4096 } else {
4097 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004098 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004099 try {
4100 if (DEBUG_LISTENER_CALLBACK) {
4101 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4102 + " listener=" + alarm.listener.asBinder());
4103 }
4104 alarm.listener.doAlarm(this);
4105 mHandler.sendMessageDelayed(
4106 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4107 alarm.listener.asBinder()),
4108 mConstants.LISTENER_TIMEOUT);
4109 } catch (Exception e) {
4110 if (DEBUG_LISTENER_CALLBACK) {
4111 Slog.i(TAG, "Alarm undeliverable to listener "
4112 + alarm.listener.asBinder(), e);
4113 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004114 // As in the PendingIntent.CanceledException case, delivery of the
4115 // alarm was not possible, so we have no wakelock or timeout or
4116 // stats management to do. It threw before we posted the delayed
4117 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004118 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004119 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004120 }
4121 }
4122
4123 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004124 if (DEBUG_WAKELOCK) {
4125 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4126 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004127 if (mBroadcastRefCount == 0) {
4128 setWakelockWorkSource(alarm.operation, alarm.workSource,
4129 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4130 true);
4131 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004132 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004133 }
4134 final InFlight inflight = new InFlight(AlarmManagerService.this,
4135 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4136 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4137 mInFlight.add(inflight);
4138 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004139 if (allowWhileIdle) {
4140 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004141 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onuki2f0b0312018-02-08 02:30:27 +00004142 if (mForceAppStandbyTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004143 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4144 } else {
4145 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4146 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004147 if (RECORD_DEVICE_IDLE_ALARMS) {
4148 IdleDispatchEntry ent = new IdleDispatchEntry();
4149 ent.uid = alarm.uid;
4150 ent.pkg = alarm.packageName;
4151 ent.tag = alarm.statsTag;
4152 ent.op = "DELIVER";
4153 ent.elapsedRealtime = nowELAPSED;
4154 mAllowWhileIdleDispatches.add(ent);
4155 }
4156 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004157 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004158 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4159 UserHandle.getUserId(alarm.creatorUid));
4160 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4161 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004162
4163 final BroadcastStats bs = inflight.mBroadcastStats;
4164 bs.count++;
4165 if (bs.nesting == 0) {
4166 bs.nesting = 1;
4167 bs.startTime = nowELAPSED;
4168 } else {
4169 bs.nesting++;
4170 }
4171 final FilterStats fs = inflight.mFilterStats;
4172 fs.count++;
4173 if (fs.nesting == 0) {
4174 fs.nesting = 1;
4175 fs.startTime = nowELAPSED;
4176 } else {
4177 fs.nesting++;
4178 }
4179 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4180 || alarm.type == RTC_WAKEUP) {
4181 bs.numWakeup++;
4182 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004183 ActivityManager.noteWakeupAlarm(
4184 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4185 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 }
4187 }
4188 }
4189}