blob: e3dcb7d331cf5fc17270e5009fe15ce9cbb02a74 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey9911a282018-02-14 22:29:11 -070019import static android.app.AlarmManager.ELAPSED_REALTIME;
20import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
21import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
22import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
23import static android.app.AlarmManager.RTC;
24import static android.app.AlarmManager.RTC_WAKEUP;
25
Suprabh Shukla75edab12018-01-29 14:09:06 -080026import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080027import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020028import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070029import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070030import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070031import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070032import android.app.IAlarmCompleteListener;
33import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070035import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080037import android.app.usage.UsageStatsManager;
38import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070040import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070044import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070046import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
50import android.os.Binder;
Christopher Tate3d65d4d2018-12-11 14:55:19 -080051import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070053import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080055import android.os.IBinder;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -070056import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070058import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070060import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070061import android.os.RemoteException;
mswest463f4c99d2018-02-01 10:13:10 -080062import android.os.ResultReceiver;
63import android.os.ShellCallback;
64import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.SystemClock;
66import android.os.SystemProperties;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +000067import android.os.ThreadLocalWorkSource;
Tim Murray175c0f92017-11-28 15:01:04 -080068import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070069import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070070import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020071import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080072import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020074import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080075import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080076import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080077import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070078import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020079import android.util.Log;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -080080import android.util.LongArrayQueue;
Jeff Sharkey9911a282018-02-14 22:29:11 -070081import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080082import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080083import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080084import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020085import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070086import android.util.SparseLongArray;
Bookatz7948c872018-09-04 12:58:33 -070087import android.util.StatsLog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070088import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070089import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090
Jeff Sharkey9911a282018-02-14 22:29:11 -070091import com.android.internal.annotations.GuardedBy;
92import com.android.internal.annotations.VisibleForTesting;
93import com.android.internal.util.ArrayUtils;
94import com.android.internal.util.DumpUtils;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -080095import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey9911a282018-02-14 22:29:11 -070096import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070097import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070098import com.android.server.AppStateTracker.Listener;
99
Christopher Tate4cb338d2013-07-26 13:11:31 -0700100import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.io.FileDescriptor;
102import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700103import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700104import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800106import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107import java.util.Calendar;
108import java.util.Collections;
109import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500110import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700111import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700112import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200113import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700114import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400116import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800117import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Makoto Onuki2206af32017-11-21 16:25:35 -0800119/**
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700120 * Alarm manager implementation.
Makoto Onuki2206af32017-11-21 16:25:35 -0800121 *
122 * Unit test:
123 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
124 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700126 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
127 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800128 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700129 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final int TIME_CHANGED_MASK = 1 << 16;
131 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800132
Christopher Tatee0a22b32013-07-11 14:43:13 -0700133 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800134 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800135
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 static final boolean localLOGV = false;
138 static final boolean DEBUG_BATCH = localLOGV || false;
139 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200140 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700141 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800142 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700143 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800144 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700145 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700146 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800147 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200148
Christopher Tatec8b7f432018-09-28 16:23:10 -0700149 static final int TICK_HISTORY_DEPTH = 10;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800150 static final long MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700151
Christopher Tatef2159712018-03-27 16:04:14 -0700152 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
153 static final int ACTIVE_INDEX = 0;
154 static final int WORKING_INDEX = 1;
155 static final int FREQUENT_INDEX = 2;
156 static final int RARE_INDEX = 3;
157 static final int NEVER_INDEX = 4;
158
Christopher Tate14a7bb02015-10-01 10:24:31 -0700159 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800161 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700162
Adam Lesinski182f73f2013-12-05 16:48:06 -0800163 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700164
Christopher Tate24cd46f2016-02-02 14:28:01 -0800165 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
166 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700167 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
168 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200169
Adam Lesinski182f73f2013-12-05 16:48:06 -0800170 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800171
Christopher Tate14a7bb02015-10-01 10:24:31 -0700172 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800173 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800174 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700175
Adam Lesinski182f73f2013-12-05 16:48:06 -0800176 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800177
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700178 // List of alarms per uid deferred due to user applied background restrictions on the source app
179 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800180 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700181 private long mNextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -0700182 private long mNextWakeUpSetAt;
183 private long mNextNonWakeUpSetAt;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700184 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800185 private long mLastTrigger;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700186
Christopher Tate12cf0b62018-01-05 18:40:14 -0800187 private long mLastTickSet;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800188 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800189 private long mLastTickAdded;
190 private long mLastTickRemoved;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700191 // ring buffer of recent TIME_TICK issuance, in the elapsed timebase
192 private final long[] mTickHistory = new long[TICK_HISTORY_DEPTH];
193 private int mNextTickHistory;
194
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700195 private final Injector mInjector;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800196 int mBroadcastRefCount = 0;
197 PowerManager.WakeLock mWakeLock;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700198 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
199 ArrayList<InFlight> mInFlight = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700200 AlarmHandler mHandler;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800201 AppWakeupHistory mAppWakeupHistory;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800202 ClockReceiver mClockReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700203 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Christopher Tatec8b7f432018-09-28 16:23:10 -0700204 Intent mTimeTickIntent;
205 IAlarmListener mTimeTickTrigger;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800206 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700207 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700208 boolean mInteractive = true;
209 long mNonInteractiveStartTime;
210 long mNonInteractiveTime;
211 long mLastAlarmDeliveryTime;
212 long mStartCurrentDelayTime;
213 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700214 long mLastTimeChangeClockTime;
215 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700216 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800217
Christopher Tatebb9cce52017-04-18 14:19:43 -0700218 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
219
220 /**
221 * This permission must be defined by the canonical System UI package,
222 * with protection level "signature".
223 */
224 private static final String SYSTEM_UI_SELF_PERMISSION =
225 "android.permission.systemui.IDENTITY";
226
227 /**
228 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
229 */
230 int mSystemUiUid;
231
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700232 /**
233 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700234 * used to determine the earliest we can dispatch the next such alarm. Times are in the
235 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700236 */
237 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
238
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800239 /**
240 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
241 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
242 */
243 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
244
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700245 final static class IdleDispatchEntry {
246 int uid;
247 String pkg;
248 String tag;
249 String op;
250 long elapsedRealtime;
251 long argRealtime;
252 }
253 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
254
Suprabh Shukla75edab12018-01-29 14:09:06 -0800255 interface Stats {
256 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800257 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800258 }
259
260 private final StatLogger mStatLogger = new StatLogger(new String[] {
261 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800262 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800263 });
264
Dianne Hackborna750a632015-06-16 17:18:23 -0700265 /**
266 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
267 */
268 Bundle mIdleOptions;
269
Jose Lima235510e2014-08-13 12:50:01 -0700270 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
271 new SparseArray<>();
272 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
273 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200274 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
275 new SparseBooleanArray();
276 private boolean mNextAlarmClockMayChange;
277
278 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700279 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
280 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200281
Makoto Onukie4918212018-02-06 11:30:15 -0800282 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800283 private boolean mAppStandbyParole;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800284
285 /**
286 * A rolling window history of previous times when an alarm was sent to a package.
287 */
288 private static class AppWakeupHistory {
289 private ArrayMap<Pair<String, Integer>, LongArrayQueue> mPackageHistory =
290 new ArrayMap<>();
291 private long mWindowSize;
292
293 AppWakeupHistory(long windowSize) {
294 mWindowSize = windowSize;
295 }
296
297 void recordAlarmForPackage(String packageName, int userId, long nowElapsed) {
298 final Pair<String, Integer> packageUser = Pair.create(packageName, userId);
299 LongArrayQueue history = mPackageHistory.get(packageUser);
300 if (history == null) {
301 history = new LongArrayQueue();
302 mPackageHistory.put(packageUser, history);
303 }
304 if (history.size() == 0 || history.peekLast() < nowElapsed) {
305 history.addLast(nowElapsed);
306 }
307 snapToWindow(history);
308 }
309
310 void removeForUser(int userId) {
311 for (int i = mPackageHistory.size() - 1; i >= 0; i--) {
312 final Pair<String, Integer> packageUserKey = mPackageHistory.keyAt(i);
313 if (packageUserKey.second == userId) {
314 mPackageHistory.removeAt(i);
315 }
316 }
317 }
318
319 void removeForPackage(String packageName, int userId) {
320 final Pair<String, Integer> packageUser = Pair.create(packageName, userId);
321 mPackageHistory.remove(packageUser);
322 }
323
324 private void snapToWindow(LongArrayQueue history) {
325 while (history.peekFirst() + mWindowSize < history.peekLast()) {
326 history.removeFirst();
327 }
328 }
329
330 int getTotalWakeupsInWindow(String packageName, int userId) {
331 final LongArrayQueue history = mPackageHistory.get(Pair.create(packageName, userId));
332 return (history == null) ? 0 : history.size();
333 }
334
335 long getLastWakeupForPackage(String packageName, int userId, int positionFromEnd) {
336 final LongArrayQueue history = mPackageHistory.get(Pair.create(packageName, userId));
337 if (history == null) {
338 return 0;
339 }
340 final int i = history.size() - positionFromEnd;
341 return (i < 0) ? 0 : history.get(i);
342 }
343
344 void dump(PrintWriter pw, String prefix, long nowElapsed) {
345 dump(new IndentingPrintWriter(pw, " ").setIndent(prefix), nowElapsed);
346 }
347
348 void dump(IndentingPrintWriter pw, long nowElapsed) {
349 pw.println("App Alarm history:");
350 pw.increaseIndent();
351 for (int i = 0; i < mPackageHistory.size(); i++) {
352 final Pair<String, Integer> packageUser = mPackageHistory.keyAt(i);
353 final LongArrayQueue timestamps = mPackageHistory.valueAt(i);
354 pw.print(packageUser.first);
355 pw.print(", u");
356 pw.print(packageUser.second);
357 pw.print(": ");
358 // limit dumping to a max of 100 values
359 final int lastIdx = Math.max(0, timestamps.size() - 100);
360 for (int j = timestamps.size() - 1; j >= lastIdx; j--) {
361 TimeUtils.formatDuration(timestamps.get(j), nowElapsed, pw);
362 pw.print(", ");
363 }
364 pw.println();
365 }
366 pw.decreaseIndent();
367 }
368 }
Makoto Onuki2206af32017-11-21 16:25:35 -0800369
Dianne Hackborna750a632015-06-16 17:18:23 -0700370 /**
371 * All times are in milliseconds. These constants are kept synchronized with the system
372 * global Settings. Any access to this class or its fields should be done while
373 * holding the AlarmManagerService.mLock lock.
374 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700375 @VisibleForTesting
376 final class Constants extends ContentObserver {
Dianne Hackborna750a632015-06-16 17:18:23 -0700377 // Key names stored in the settings value.
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700378 @VisibleForTesting
379 static final String KEY_MIN_FUTURITY = "min_futurity";
380 @VisibleForTesting
381 static final String KEY_MIN_INTERVAL = "min_interval";
382 @VisibleForTesting
383 static final String KEY_MAX_INTERVAL = "max_interval";
384 @VisibleForTesting
385 static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
386 @VisibleForTesting
387 static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
388 @VisibleForTesting
389 static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
Dianne Hackborna750a632015-06-16 17:18:23 -0700390 = "allow_while_idle_whitelist_duration";
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700391 @VisibleForTesting
392 static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800393 @VisibleForTesting
394 static final String KEY_APP_STANDBY_QUOTAS_ENABLED = "app_standby_quotas_enabled";
395 private static final String KEY_APP_STANDBY_WINDOW = "app_standby_window";
396 @VisibleForTesting
397 final String[] KEYS_APP_STANDBY_QUOTAS = {
398 "standby_active_quota",
399 "standby_working_quota",
400 "standby_frequent_quota",
401 "standby_rare_quota",
402 "standby_never_quota",
403 };
Dianne Hackborna750a632015-06-16 17:18:23 -0700404
Suprabh Shukla75edab12018-01-29 14:09:06 -0800405 // Keys for specifying throttling delay based on app standby bucketing
406 private final String[] KEYS_APP_STANDBY_DELAY = {
407 "standby_active_delay",
408 "standby_working_delay",
409 "standby_frequent_delay",
410 "standby_rare_delay",
411 "standby_never_delay",
412 };
413
Dianne Hackborna750a632015-06-16 17:18:23 -0700414 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
415 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800416 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700417 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700418 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700419 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700420 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800421 private static final boolean DEFAULT_APP_STANDBY_QUOTAS_ENABLED = true;
422 private static final long DEFAULT_APP_STANDBY_WINDOW = 60 * 60 * 1000; // 1 hr
423 /**
424 * Max number of times an app can receive alarms in {@link #APP_STANDBY_WINDOW}
425 */
426 private final int[] DEFAULT_APP_STANDBY_QUOTAS = {
427 720, // Active
428 10, // Working
429 2, // Frequent
430 1, // Rare
431 0 // Never
432 };
Suprabh Shukla75edab12018-01-29 14:09:06 -0800433 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
434 0, // Active
435 6 * 60_000, // Working
436 30 * 60_000, // Frequent
437 2 * 60 * 60_000, // Rare
438 10 * 24 * 60 * 60_000 // Never
439 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700440
Dianne Hackborna750a632015-06-16 17:18:23 -0700441 // Minimum futurity of a new alarm
442 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
443
444 // Minimum alarm recurrence interval
445 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
446
Christopher Tate22e919d2018-02-16 16:16:50 -0800447 // Maximum alarm recurrence interval
448 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
449
Dianne Hackborna750a632015-06-16 17:18:23 -0700450 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
451 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
452
453 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
454 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
455
456 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
457 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
458 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
459
Christopher Tate14a7bb02015-10-01 10:24:31 -0700460 // Direct alarm listener callback timeout
461 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800462 public boolean APP_STANDBY_QUOTAS_ENABLED = DEFAULT_APP_STANDBY_QUOTAS_ENABLED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700463
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800464 public long APP_STANDBY_WINDOW = DEFAULT_APP_STANDBY_WINDOW;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800465 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800466 public int[] APP_STANDBY_QUOTAS = new int[DEFAULT_APP_STANDBY_QUOTAS.length];
Suprabh Shukla75edab12018-01-29 14:09:06 -0800467
Dianne Hackborna750a632015-06-16 17:18:23 -0700468 private ContentResolver mResolver;
469 private final KeyValueListParser mParser = new KeyValueListParser(',');
470 private long mLastAllowWhileIdleWhitelistDuration = -1;
471
472 public Constants(Handler handler) {
473 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700474 updateAllowWhileIdleWhitelistDurationLocked();
475 }
476
477 public void start(ContentResolver resolver) {
478 mResolver = resolver;
479 mResolver.registerContentObserver(Settings.Global.getUriFor(
480 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
481 updateConstants();
482 }
483
Dianne Hackborna750a632015-06-16 17:18:23 -0700484 public void updateAllowWhileIdleWhitelistDurationLocked() {
485 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
486 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
487 BroadcastOptions opts = BroadcastOptions.makeBasic();
488 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
489 mIdleOptions = opts.toBundle();
490 }
491 }
492
493 @Override
494 public void onChange(boolean selfChange, Uri uri) {
495 updateConstants();
496 }
497
498 private void updateConstants() {
499 synchronized (mLock) {
500 try {
501 mParser.setString(Settings.Global.getString(mResolver,
502 Settings.Global.ALARM_MANAGER_CONSTANTS));
503 } catch (IllegalArgumentException e) {
504 // Failed to parse the settings string, log this and move on
505 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800506 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700507 }
508
509 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
510 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800511 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700512 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
513 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
514 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
515 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
516 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
517 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
518 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700519 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
520 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700521 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
522 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
523 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
524 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800525 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800526 Math.max(APP_STANDBY_MIN_DELAYS[i - 1], DEFAULT_APP_STANDBY_DELAYS[i]));
527 }
528
529 APP_STANDBY_QUOTAS_ENABLED = mParser.getBoolean(KEY_APP_STANDBY_QUOTAS_ENABLED,
530 DEFAULT_APP_STANDBY_QUOTAS_ENABLED);
531
532 APP_STANDBY_WINDOW = mParser.getLong(KEY_APP_STANDBY_WINDOW,
533 DEFAULT_APP_STANDBY_WINDOW);
534 if (APP_STANDBY_WINDOW > DEFAULT_APP_STANDBY_WINDOW) {
535 Slog.w(TAG, "Cannot exceed the app_standby_window size of "
536 + DEFAULT_APP_STANDBY_WINDOW);
537 APP_STANDBY_WINDOW = DEFAULT_APP_STANDBY_WINDOW;
538 } else if (APP_STANDBY_WINDOW < DEFAULT_APP_STANDBY_WINDOW) {
539 // Not recommended outside of testing.
540 Slog.w(TAG, "Using a non-default app_standby_window of " + APP_STANDBY_WINDOW);
541 }
542
543 APP_STANDBY_QUOTAS[ACTIVE_INDEX] = mParser.getInt(
544 KEYS_APP_STANDBY_QUOTAS[ACTIVE_INDEX],
545 DEFAULT_APP_STANDBY_QUOTAS[ACTIVE_INDEX]);
546 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_QUOTAS.length; i++) {
547 APP_STANDBY_QUOTAS[i] = mParser.getInt(KEYS_APP_STANDBY_QUOTAS[i],
548 Math.min(APP_STANDBY_QUOTAS[i - 1], DEFAULT_APP_STANDBY_QUOTAS[i]));
Suprabh Shukla75edab12018-01-29 14:09:06 -0800549 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700550 updateAllowWhileIdleWhitelistDurationLocked();
551 }
552 }
553
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800554 void dump(PrintWriter pw, String prefix) {
555 dump(new IndentingPrintWriter(pw, " ").setIndent(prefix));
556 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700557
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800558 void dump(IndentingPrintWriter pw) {
559 pw.println("Settings:");
560
561 pw.increaseIndent();
562
563 pw.print(KEY_MIN_FUTURITY); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700564 TimeUtils.formatDuration(MIN_FUTURITY, pw);
565 pw.println();
566
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800567 pw.print(KEY_MIN_INTERVAL); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700568 TimeUtils.formatDuration(MIN_INTERVAL, pw);
569 pw.println();
570
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800571 pw.print(KEY_MAX_INTERVAL); pw.print("=");
Christopher Tate22e919d2018-02-16 16:16:50 -0800572 TimeUtils.formatDuration(MAX_INTERVAL, pw);
573 pw.println();
574
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800575 pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
Christopher Tate14a7bb02015-10-01 10:24:31 -0700576 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
577 pw.println();
578
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800579 pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700580 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
581 pw.println();
582
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800583 pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700584 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
585 pw.println();
586
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800587 pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700588 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
589 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800590
591 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800592 pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
Suprabh Shukla75edab12018-01-29 14:09:06 -0800593 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
594 pw.println();
595 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800596
597 pw.print(KEY_APP_STANDBY_QUOTAS_ENABLED); pw.print("=");
598 pw.println(APP_STANDBY_QUOTAS_ENABLED);
599
600 pw.print(KEY_APP_STANDBY_WINDOW); pw.print("=");
601 TimeUtils.formatDuration(APP_STANDBY_WINDOW, pw);
602 pw.println();
603
604 for (int i = 0; i < KEYS_APP_STANDBY_QUOTAS.length; i++) {
605 pw.print(KEYS_APP_STANDBY_QUOTAS[i]); pw.print("=");
606 pw.println(APP_STANDBY_QUOTAS[i]);
607 }
608
609 pw.decreaseIndent();
Dianne Hackborna750a632015-06-16 17:18:23 -0700610 }
Kweku Adams61e03292017-10-19 14:27:12 -0700611
612 void dumpProto(ProtoOutputStream proto, long fieldId) {
613 final long token = proto.start(fieldId);
614
615 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
616 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800617 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700618 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
619 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
620 ALLOW_WHILE_IDLE_SHORT_TIME);
621 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
622 ALLOW_WHILE_IDLE_LONG_TIME);
623 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
624 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
625
626 proto.end(token);
627 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700628 }
629
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700630 Constants mConstants;
Dianne Hackborna750a632015-06-16 17:18:23 -0700631
Christopher Tate1590f1e2014-10-02 17:27:57 -0700632 // Alarm delivery ordering bookkeeping
633 static final int PRIO_TICK = 0;
634 static final int PRIO_WAKEUP = 1;
635 static final int PRIO_NORMAL = 2;
636
Dianne Hackborna750a632015-06-16 17:18:23 -0700637 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700638 int seq;
639 int priority;
640
641 PriorityClass() {
642 seq = mCurrentSeq - 1;
643 priority = PRIO_NORMAL;
644 }
645 }
646
Dianne Hackborna750a632015-06-16 17:18:23 -0700647 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700648 int mCurrentSeq = 0;
649
Dianne Hackborna750a632015-06-16 17:18:23 -0700650 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700651 public long when;
652 public int uid;
653 public String action;
654
655 public WakeupEvent(long theTime, int theUid, String theAction) {
656 when = theTime;
657 uid = theUid;
658 action = theAction;
659 }
660 }
661
Adam Lesinski182f73f2013-12-05 16:48:06 -0800662 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
663 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700664
Adrian Roosc42a1e12014-07-07 23:35:53 +0200665 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700666 long start; // These endpoints are always in ELAPSED
667 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700668 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700669
670 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
671
672 Batch() {
673 start = 0;
674 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700675 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700676 }
677
678 Batch(Alarm seed) {
679 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800680 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700681 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700682 alarms.add(seed);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700683 if (seed.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700684 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800685 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700686 }
687
688 int size() {
689 return alarms.size();
690 }
691
692 Alarm get(int index) {
693 return alarms.get(index);
694 }
695
696 boolean canHold(long whenElapsed, long maxWhen) {
697 return (end >= whenElapsed) && (start <= maxWhen);
698 }
699
700 boolean add(Alarm alarm) {
701 boolean newStart = false;
702 // narrows the batch if necessary; presumes that canHold(alarm) is true
703 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
704 if (index < 0) {
705 index = 0 - index - 1;
706 }
707 alarms.add(index, alarm);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700708 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700709 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800710 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700711 if (DEBUG_BATCH) {
712 Slog.v(TAG, "Adding " + alarm + " to " + this);
713 }
714 if (alarm.whenElapsed > start) {
715 start = alarm.whenElapsed;
716 newStart = true;
717 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700718 if (alarm.maxWhenElapsed < end) {
719 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700720 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700721 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700722
723 if (DEBUG_BATCH) {
724 Slog.v(TAG, " => now " + this);
725 }
726 return newStart;
727 }
728
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800729 boolean remove(Alarm alarm) {
730 return remove(a -> (a == alarm));
731 }
732
Christopher Tate1d99c392017-12-07 16:54:04 -0800733 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700734 boolean didRemove = false;
735 long newStart = 0; // recalculate endpoints as we go
736 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700737 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700738 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700739 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800740 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741 alarms.remove(i);
742 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200743 if (alarm.alarmClock != null) {
744 mNextAlarmClockMayChange = true;
745 }
Christopher Tatec8b7f432018-09-28 16:23:10 -0700746 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700747 mLastTickRemoved = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800748 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700749 } else {
750 if (alarm.whenElapsed > newStart) {
751 newStart = alarm.whenElapsed;
752 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700753 if (alarm.maxWhenElapsed < newEnd) {
754 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700755 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700756 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700757 i++;
758 }
759 }
760 if (didRemove) {
761 // commit the new batch bounds
762 start = newStart;
763 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700764 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700765 }
766 return didRemove;
767 }
768
Christopher Tatee0a22b32013-07-11 14:43:13 -0700769 boolean hasPackage(final String packageName) {
770 final int N = alarms.size();
771 for (int i = 0; i < N; i++) {
772 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700773 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700774 return true;
775 }
776 }
777 return false;
778 }
779
780 boolean hasWakeups() {
781 final int N = alarms.size();
782 for (int i = 0; i < N; i++) {
783 Alarm a = alarms.get(i);
784 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
785 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
786 return true;
787 }
788 }
789 return false;
790 }
791
792 @Override
793 public String toString() {
794 StringBuilder b = new StringBuilder(40);
795 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
796 b.append(" num="); b.append(size());
797 b.append(" start="); b.append(start);
798 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700799 if (flags != 0) {
800 b.append(" flgs=0x");
801 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700802 }
803 b.append('}');
804 return b.toString();
805 }
Kweku Adams61e03292017-10-19 14:27:12 -0700806
807 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
808 long nowRTC) {
809 final long token = proto.start(fieldId);
810
811 proto.write(BatchProto.START_REALTIME, start);
812 proto.write(BatchProto.END_REALTIME, end);
813 proto.write(BatchProto.FLAGS, flags);
814 for (Alarm a : alarms) {
815 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
816 }
817
818 proto.end(token);
819 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700820 }
821
822 static class BatchTimeOrder implements Comparator<Batch> {
823 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800824 long when1 = b1.start;
825 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800826 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700827 return 1;
828 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800829 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700830 return -1;
831 }
832 return 0;
833 }
834 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800835
836 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
837 @Override
838 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700839 // priority class trumps everything. TICK < WAKEUP < NORMAL
840 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
841 return -1;
842 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
843 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800844 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700845
846 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800847 if (lhs.whenElapsed < rhs.whenElapsed) {
848 return -1;
849 } else if (lhs.whenElapsed > rhs.whenElapsed) {
850 return 1;
851 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700852
853 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800854 return 0;
855 }
856 };
857
Christopher Tate1590f1e2014-10-02 17:27:57 -0700858 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
859 final int N = alarms.size();
860 for (int i = 0; i < N; i++) {
861 Alarm a = alarms.get(i);
862
863 final int alarmPrio;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700864 if (a.listener == mTimeTickTrigger) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700865 alarmPrio = PRIO_TICK;
866 } else if (a.wakeup) {
867 alarmPrio = PRIO_WAKEUP;
868 } else {
869 alarmPrio = PRIO_NORMAL;
870 }
871
872 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800873 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700874 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700875 if (packagePrio == null) {
876 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700877 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700878 }
879 a.priorityClass = packagePrio;
880
881 if (packagePrio.seq != mCurrentSeq) {
882 // first alarm we've seen in the current delivery generation from this package
883 packagePrio.priority = alarmPrio;
884 packagePrio.seq = mCurrentSeq;
885 } else {
886 // Multiple alarms from this package being delivered in this generation;
887 // bump the package's delivery class if it's warranted.
888 // TICK < WAKEUP < NORMAL
889 if (alarmPrio < packagePrio.priority) {
890 packagePrio.priority = alarmPrio;
891 }
892 }
893 }
894 }
895
Christopher Tatee0a22b32013-07-11 14:43:13 -0700896 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800897 static final long MIN_FUZZABLE_INTERVAL = 10000;
898 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700899 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
900
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700901 // 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 -0700902 // to run during this time are placed in mPendingWhileIdleAlarms
903 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700904 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700905 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700906
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700907 @VisibleForTesting
908 AlarmManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800909 super(context);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700910 mInjector = injector;
Jeff Brownb880d882014-02-10 19:47:07 -0800911 }
912
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700913 AlarmManagerService(Context context) {
914 this(context, new Injector(context));
915 }
916
917 private long convertToElapsed(long when, int type) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700918 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
919 if (isRtc) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700920 when -= mInjector.getCurrentTimeMillis() - mInjector.getElapsedRealtime();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700921 }
922 return when;
923 }
924
925 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
926 // calculate the end of our nominal delivery window for the alarm.
927 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
928 // Current heuristic: batchable window is 75% of either the recurrence interval
929 // [for a periodic alarm] or of the time from now to the desired delivery time,
930 // with a minimum delay/interval of 10 seconds, under which we will simply not
931 // defer the alarm.
932 long futurity = (interval == 0)
933 ? (triggerAtTime - now)
934 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700935 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700936 futurity = 0;
937 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800938 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700939 }
940
941 // returns true if the batch was added at the head
942 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
943 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
944 if (index < 0) {
945 index = 0 - index - 1;
946 }
947 list.add(index, newBatch);
948 return (index == 0);
949 }
950
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800951 private void insertAndBatchAlarmLocked(Alarm alarm) {
952 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
953 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
954
955 if (whichBatch < 0) {
956 addBatchLocked(mAlarmBatches, new Batch(alarm));
957 } else {
958 final Batch batch = mAlarmBatches.get(whichBatch);
959 if (batch.add(alarm)) {
960 // The start time of this batch advanced, so batch ordering may
961 // have just been broken. Move it to where it now belongs.
962 mAlarmBatches.remove(whichBatch);
963 addBatchLocked(mAlarmBatches, batch);
964 }
965 }
966 }
967
Christopher Tate385e4982013-07-23 18:22:29 -0700968 // Return the index of the matching batch, or -1 if none found.
969 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700970 final int N = mAlarmBatches.size();
971 for (int i = 0; i < N; i++) {
972 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700973 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700974 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700975 }
976 }
Christopher Tate385e4982013-07-23 18:22:29 -0700977 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700978 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800979 /** @return total count of the alarms in a set of alarm batches. */
980 static int getAlarmCount(ArrayList<Batch> batches) {
981 int ret = 0;
982
983 final int size = batches.size();
984 for (int i = 0; i < size; i++) {
985 ret += batches.get(i).size();
986 }
987 return ret;
988 }
989
990 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
991 if (alarms.size() == 0) {
992 return false;
993 }
994 final int batchSize = alarms.size();
995 for (int j = 0; j < batchSize; j++) {
Christopher Tatec8b7f432018-09-28 16:23:10 -0700996 if (alarms.get(j).listener == mTimeTickTrigger) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800997 return true;
998 }
999 }
1000 return false;
1001 }
1002
1003 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
1004 final int numBatches = batches.size();
1005 for (int i = 0; i < numBatches; i++) {
1006 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
1007 return true;
1008 }
1009 }
1010 return false;
1011 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001012
1013 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
1014 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001015 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001016 rebatchAllAlarmsLocked(true);
1017 }
1018 }
1019
1020 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001021 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001022 final int oldCount =
1023 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
1024 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
1025 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
1026
Christopher Tate4cb338d2013-07-26 13:11:31 -07001027 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
1028 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001029 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001030 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate4cb338d2013-07-26 13:11:31 -07001031 final int oldBatches = oldSet.size();
1032 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
1033 Batch batch = oldSet.get(batchNum);
1034 final int N = batch.size();
1035 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001036 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001037 }
1038 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001039 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
1040 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
1041 + " to " + mPendingIdleUntil);
1042 if (mPendingIdleUntil == null) {
1043 // Somehow we lost this... we need to restore all of the pending alarms.
1044 restorePendingWhileIdleAlarmsLocked();
1045 }
1046 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08001047 final int newCount =
1048 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
1049 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
1050 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
1051
1052 if (oldCount != newCount) {
1053 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
1054 }
1055 if (oldHasTick != newHasTick) {
1056 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
1057 }
1058
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001059 rescheduleKernelAlarmsLocked();
1060 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -08001061 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001062 }
1063
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001064 /**
1065 * Re-orders the alarm batches based on newly evaluated send times based on the current
1066 * app-standby buckets
1067 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
1068 * null indicates all
1069 * @return True if there was any reordering done to the current list.
1070 */
1071 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
1072 final long start = mStatLogger.getTime();
1073 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
1074
1075 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
1076 final Batch batch = mAlarmBatches.get(batchIndex);
1077 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
1078 final Alarm alarm = batch.get(alarmIndex);
1079 final Pair<String, Integer> packageUser =
1080 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
1081 if (targetPackages != null && !targetPackages.contains(packageUser)) {
1082 continue;
1083 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001084 if (adjustDeliveryTimeBasedOnBucketLocked(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001085 batch.remove(alarm);
1086 rescheduledAlarms.add(alarm);
1087 }
1088 }
1089 if (batch.size() == 0) {
1090 mAlarmBatches.remove(batchIndex);
1091 }
1092 }
1093 for (int i = 0; i < rescheduledAlarms.size(); i++) {
1094 final Alarm a = rescheduledAlarms.get(i);
1095 insertAndBatchAlarmLocked(a);
1096 }
1097
1098 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
1099 return rescheduledAlarms.size() > 0;
1100 }
1101
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001102 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
1103 a.when = a.origWhen;
1104 long whenElapsed = convertToElapsed(a.when, a.type);
1105 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001106 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 // Exact
1108 maxElapsed = whenElapsed;
1109 } else {
1110 // Not exact. Preserve any explicit window, otherwise recalculate
1111 // the window based on the alarm's new futurity. Note that this
1112 // reflects a policy of preferring timely to deferred delivery.
1113 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -08001114 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001115 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
1116 }
1117 a.whenElapsed = whenElapsed;
1118 a.maxWhenElapsed = maxElapsed;
1119 setImplLocked(a, true, doValidate);
1120 }
1121
Christopher Tate22e919d2018-02-16 16:16:50 -08001122 static long clampPositive(long val) {
1123 return (val >= 0) ? val : Long.MAX_VALUE;
1124 }
1125
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001126 /**
1127 * Sends alarms that were blocked due to user applied background restrictions - either because
1128 * the user lifted those or the uid came to foreground.
1129 *
1130 * @param uid uid to filter on
1131 * @param packageName package to filter on, or null for all packages in uid
1132 */
1133 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
1134 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
1135 if (alarmsForUid == null || alarmsForUid.size() == 0) {
1136 return;
1137 }
1138 final ArrayList<Alarm> alarmsToDeliver;
1139 if (packageName != null) {
1140 if (DEBUG_BG_LIMIT) {
1141 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
1142 }
1143 alarmsToDeliver = new ArrayList<>();
1144 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
1145 final Alarm a = alarmsForUid.get(i);
1146 if (a.matches(packageName)) {
1147 alarmsToDeliver.add(alarmsForUid.remove(i));
1148 }
1149 }
1150 if (alarmsForUid.size() == 0) {
1151 mPendingBackgroundAlarms.remove(uid);
1152 }
1153 } else {
1154 if (DEBUG_BG_LIMIT) {
1155 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
1156 }
1157 alarmsToDeliver = alarmsForUid;
1158 mPendingBackgroundAlarms.remove(uid);
1159 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001160 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001161 }
1162
Makoto Onuki2206af32017-11-21 16:25:35 -08001163 /**
1164 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
1165 * restricted.
1166 *
1167 * This is only called when the global "force all apps-standby" flag changes or when the
1168 * power save whitelist changes, so it's okay to be slow.
1169 */
1170 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001171 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001172
1173 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1174 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1175
1176 if (alarmsToDeliver.size() > 0) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001177 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Makoto Onuki2206af32017-11-21 16:25:35 -08001178 }
1179 }
1180
1181 @VisibleForTesting
1182 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1183 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1184 Predicate<Alarm> isBackgroundRestricted) {
1185
1186 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1187 final int uid = pendingAlarms.keyAt(uidIndex);
1188 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1189
1190 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1191 final Alarm alarm = alarmsForUid.get(alarmIndex);
1192
1193 if (isBackgroundRestricted.test(alarm)) {
1194 continue;
1195 }
1196
1197 unrestrictedAlarms.add(alarm);
1198 alarmsForUid.remove(alarmIndex);
1199 }
1200
1201 if (alarmsForUid.size() == 0) {
1202 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001203 }
1204 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001205 }
1206
1207 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1208 final int N = alarms.size();
1209 boolean hasWakeup = false;
1210 for (int i = 0; i < N; i++) {
1211 final Alarm alarm = alarms.get(i);
1212 if (alarm.wakeup) {
1213 hasWakeup = true;
1214 }
1215 alarm.count = 1;
1216 // Recurring alarms may have passed several alarm intervals while the
1217 // alarm was kept pending. Send the appropriate trigger count.
1218 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001219 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001220 // Also schedule its next recurrence
1221 final long delta = alarm.count * alarm.repeatInterval;
1222 final long nextElapsed = alarm.whenElapsed + delta;
1223 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1224 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1225 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1226 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1227 // Kernel alarms will be rescheduled as needed in setImplLocked
1228 }
1229 }
1230 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1231 // No need to wakeup for non wakeup alarms
1232 if (mPendingNonWakeupAlarms.size() == 0) {
1233 mStartCurrentDelayTime = nowELAPSED;
1234 mNextNonWakeupDeliveryTime = nowELAPSED
1235 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1236 }
1237 mPendingNonWakeupAlarms.addAll(alarms);
1238 mNumDelayedAlarms += alarms.size();
1239 } else {
1240 if (DEBUG_BG_LIMIT) {
1241 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1242 }
1243 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1244 if (mPendingNonWakeupAlarms.size() > 0) {
1245 alarms.addAll(mPendingNonWakeupAlarms);
1246 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1247 mTotalDelayTime += thisDelayTime;
1248 if (mMaxDelayTime < thisDelayTime) {
1249 mMaxDelayTime = thisDelayTime;
1250 }
1251 mPendingNonWakeupAlarms.clear();
1252 }
1253 calculateDeliveryPriorities(alarms);
1254 Collections.sort(alarms, mAlarmDispatchComparator);
1255 deliverAlarmsLocked(alarms, nowELAPSED);
1256 }
1257 }
1258
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001259 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001260 if (RECORD_DEVICE_IDLE_ALARMS) {
1261 IdleDispatchEntry ent = new IdleDispatchEntry();
1262 ent.uid = 0;
1263 ent.pkg = "FINISH IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001264 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001265 mAllowWhileIdleDispatches.add(ent);
1266 }
1267
Dianne Hackborn35d54032015-04-23 10:30:43 -07001268 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001269 if (mPendingWhileIdleAlarms.size() > 0) {
1270 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1271 mPendingWhileIdleAlarms = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001272 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001273 for (int i=alarms.size() - 1; i >= 0; i--) {
1274 Alarm a = alarms.get(i);
1275 reAddAlarmLocked(a, nowElapsed, false);
1276 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001277 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001278
1279 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001280 rescheduleKernelAlarmsLocked();
1281 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001282
Christopher Tatee0a22b32013-07-11 14:43:13 -07001283 }
1284
Christopher Tate14a7bb02015-10-01 10:24:31 -07001285 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001286 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001287 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001288 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001289 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001290 final int mUid;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001291 final int mCreatorUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001292 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001293 final BroadcastStats mBroadcastStats;
1294 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001295 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001296
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001297 InFlight(AlarmManagerService service, Alarm alarm, long nowELAPSED) {
1298 mPendingIntent = alarm.operation;
Christopher Tateeabba732017-08-17 17:12:52 -07001299 mWhenElapsed = nowELAPSED;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001300 mListener = alarm.listener != null ? alarm.listener.asBinder() : null;
1301 mWorkSource = alarm.workSource;
1302 mUid = alarm.uid;
1303 mCreatorUid = alarm.creatorUid;
1304 mTag = alarm.statsTag;
1305 mBroadcastStats = (alarm.operation != null)
1306 ? service.getStatsLocked(alarm.operation)
1307 : service.getStatsLocked(alarm.uid, alarm.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001308 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001309 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001310 fs = new FilterStats(mBroadcastStats, mTag);
1311 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001312 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001313 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001314 mFilterStats = fs;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001315 mAlarmType = alarm.type;
Dianne Hackborn81038902012-11-26 17:04:09 -08001316 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001317
1318 @Override
1319 public String toString() {
1320 return "InFlight{"
1321 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001322 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001323 + ", workSource=" + mWorkSource
1324 + ", uid=" + mUid
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001325 + ", creatorUid=" + mCreatorUid
Makoto Onuki33955e12017-03-01 18:11:00 -08001326 + ", tag=" + mTag
1327 + ", broadcastStats=" + mBroadcastStats
1328 + ", filterStats=" + mFilterStats
1329 + ", alarmType=" + mAlarmType
1330 + "}";
1331 }
Kweku Adams61e03292017-10-19 14:27:12 -07001332
1333 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1334 final long token = proto.start(fieldId);
1335
1336 proto.write(InFlightProto.UID, mUid);
1337 proto.write(InFlightProto.TAG, mTag);
1338 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1339 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1340 if (mPendingIntent != null) {
1341 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1342 }
1343 if (mBroadcastStats != null) {
1344 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1345 }
1346 if (mFilterStats != null) {
1347 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1348 }
1349 if (mWorkSource != null) {
1350 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1351 }
1352
1353 proto.end(token);
1354 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001356
Adam Lesinski182f73f2013-12-05 16:48:06 -08001357 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001358 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001359 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001360
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001361 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001363 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 int numWakeup;
1365 long startTime;
1366 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001367
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001368 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001369 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001370 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001371 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001372
1373 @Override
1374 public String toString() {
1375 return "FilterStats{"
1376 + "tag=" + mTag
1377 + ", lastTime=" + lastTime
1378 + ", aggregateTime=" + aggregateTime
1379 + ", count=" + count
1380 + ", numWakeup=" + numWakeup
1381 + ", startTime=" + startTime
1382 + ", nesting=" + nesting
1383 + "}";
1384 }
Kweku Adams61e03292017-10-19 14:27:12 -07001385
1386 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1387 final long token = proto.start(fieldId);
1388
1389 proto.write(FilterStatsProto.TAG, mTag);
1390 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1391 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1392 proto.write(FilterStatsProto.COUNT, count);
1393 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1394 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1395 proto.write(FilterStatsProto.NESTING, nesting);
1396
1397 proto.end(token);
1398 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001399 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001400
Adam Lesinski182f73f2013-12-05 16:48:06 -08001401 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001402 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001403 final String mPackageName;
1404
1405 long aggregateTime;
1406 int count;
1407 int numWakeup;
1408 long startTime;
1409 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001410 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001411
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001412 BroadcastStats(int uid, String packageName) {
1413 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001414 mPackageName = packageName;
1415 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001416
1417 @Override
1418 public String toString() {
1419 return "BroadcastStats{"
1420 + "uid=" + mUid
1421 + ", packageName=" + mPackageName
1422 + ", aggregateTime=" + aggregateTime
1423 + ", count=" + count
1424 + ", numWakeup=" + numWakeup
1425 + ", startTime=" + startTime
1426 + ", nesting=" + nesting
1427 + "}";
1428 }
Kweku Adams61e03292017-10-19 14:27:12 -07001429
1430 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1431 final long token = proto.start(fieldId);
1432
1433 proto.write(BroadcastStatsProto.UID, mUid);
1434 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1435 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1436 proto.write(BroadcastStatsProto.COUNT, count);
1437 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1438 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1439 proto.write(BroadcastStatsProto.NESTING, nesting);
1440
1441 proto.end(token);
1442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001444
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001445 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1446 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001447
1448 int mNumDelayedAlarms = 0;
1449 long mTotalDelayTime = 0;
1450 long mMaxDelayTime = 0;
1451
Adam Lesinski182f73f2013-12-05 16:48:06 -08001452 @Override
1453 public void onStart() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001454 mInjector.init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001455
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001456 synchronized (mLock) {
Suprabh Shukla12bd0162018-11-12 18:00:18 -08001457 mHandler = new AlarmHandler();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001458 mConstants = new Constants(mHandler);
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001459 mAppWakeupHistory = new AppWakeupHistory(Constants.DEFAULT_APP_STANDBY_WINDOW);
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001460
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001461 mNextWakeup = mNextNonWakeup = 0;
1462
1463 // We have to set current TimeZone info to kernel
1464 // because kernel doesn't keep this after reboot
1465 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
1466
Christopher Tate3d65d4d2018-12-11 14:55:19 -08001467 // Ensure that we're booting with a halfway sensible current time. Use the
1468 // most recent of Build.TIME, the root file system's timestamp, and the
1469 // value of the ro.build.date.utc system property (which is in seconds).
1470 final long systemBuildTime = Long.max(
1471 1000L * SystemProperties.getLong("ro.build.date.utc", -1L),
1472 Long.max(Environment.getRootDirectory().lastModified(), Build.TIME));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001473 if (mInjector.getCurrentTimeMillis() < systemBuildTime) {
1474 Slog.i(TAG, "Current time only " + mInjector.getCurrentTimeMillis()
Christopher Tate247571462017-04-10 11:45:05 -07001475 + ", advancing to build time " + systemBuildTime);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001476 mInjector.setKernelTime(systemBuildTime);
Christopher Tate247571462017-04-10 11:45:05 -07001477 }
Christopher Tate247571462017-04-10 11:45:05 -07001478
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001479 // Determine SysUI's uid
1480 mSystemUiUid = mInjector.getSystemUiUid();
1481 if (mSystemUiUid <= 0) {
1482 Slog.wtf(TAG, "SysUI package not found!");
1483 }
1484 mWakeLock = mInjector.getAlarmWakeLock();
1485
Christopher Tatec8b7f432018-09-28 16:23:10 -07001486 mTimeTickIntent = new Intent(Intent.ACTION_TIME_TICK).addFlags(
1487 Intent.FLAG_RECEIVER_REGISTERED_ONLY
1488 | Intent.FLAG_RECEIVER_FOREGROUND
1489 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1490
1491 mTimeTickTrigger = new IAlarmListener.Stub() {
1492 @Override
1493 public void doAlarm(final IAlarmCompleteListener callback) throws RemoteException {
1494 if (DEBUG_BATCH) {
1495 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1496 }
1497
1498 // Via handler because dispatch invokes this within its lock. OnAlarmListener
1499 // takes care of this automatically, but we're using the direct internal
1500 // interface here rather than that client-side wrapper infrastructure.
1501 mHandler.post(() -> {
1502 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL);
1503
1504 try {
1505 callback.alarmComplete(this);
1506 } catch (RemoteException e) { /* local method call */ }
1507 });
1508
1509 synchronized (mLock) {
1510 mLastTickReceived = mInjector.getCurrentTimeMillis();
1511 }
1512 mClockReceiver.scheduleTimeTickEvent();
1513 }
1514 };
1515
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001516 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
1517 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1518 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1519 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
1520 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
1521
1522 mClockReceiver = mInjector.getClockReceiver(this);
1523 new InteractiveStateReceiver();
1524 new UninstallReceiver();
1525
1526 if (mInjector.isAlarmDriverPresent()) {
1527 AlarmThread waitThread = new AlarmThread();
1528 waitThread.start();
Christopher Tatebb9cce52017-04-18 14:19:43 -07001529 } else {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001530 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
Christopher Tatebb9cce52017-04-18 14:19:43 -07001531 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001532
1533 try {
1534 ActivityManager.getService().registerUidObserver(new UidObserver(),
1535 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1536 | ActivityManager.UID_OBSERVER_ACTIVE,
1537 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1538 } catch (RemoteException e) {
1539 // ignored; both services live in system_server
1540 }
Christopher Tatebb9cce52017-04-18 14:19:43 -07001541 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001542 publishLocalService(AlarmManagerInternal.class, new LocalService());
Adam Lesinski182f73f2013-12-05 16:48:06 -08001543 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001544 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001545
1546 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001547 public void onBootPhase(int phase) {
1548 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001549 synchronized (mLock) {
1550 mConstants.start(getContext().getContentResolver());
1551 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1552 mLocalDeviceIdleController =
1553 LocalServices.getService(DeviceIdleController.LocalService.class);
1554 mUsageStatsManagerInternal =
1555 LocalServices.getService(UsageStatsManagerInternal.class);
1556 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001557
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001558 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1559 mAppStateTracker.addListener(mForceAppStandbyListener);
1560
1561 mClockReceiver.scheduleTimeTickEvent();
1562 mClockReceiver.scheduleDateChangedEvent();
1563 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001564 }
1565 }
1566
1567 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 protected void finalize() throws Throwable {
1569 try {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001570 mInjector.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001571 } finally {
1572 super.finalize();
1573 }
1574 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001575
mswest463f4c99d2018-02-01 10:13:10 -08001576 boolean setTimeImpl(long millis) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001577 if (!mInjector.isAlarmDriverPresent()) {
mswest463f4c99d2018-02-01 10:13:10 -08001578 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1579 return false;
1580 }
1581
1582 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001583 final long currentTimeMillis = mInjector.getCurrentTimeMillis();
1584 mInjector.setKernelTime(millis);
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001585 final TimeZone timeZone = TimeZone.getDefault();
1586 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1587 final int newTzOffset = timeZone.getOffset(millis);
1588 if (currentTzOffset != newTzOffset) {
1589 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001590 mInjector.setKernelTimezone(-(newTzOffset / 60000));
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001591 }
1592 // The native implementation of setKernelTime can return -1 even when the kernel
1593 // time was set correctly, so assume setting kernel time was successful and always
1594 // return true.
1595 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001596 }
1597 }
1598
Adam Lesinski182f73f2013-12-05 16:48:06 -08001599 void setTimeZoneImpl(String tz) {
1600 if (TextUtils.isEmpty(tz)) {
1601 return;
David Christieebe51fc2013-07-26 13:23:29 -07001602 }
1603
Adam Lesinski182f73f2013-12-05 16:48:06 -08001604 TimeZone zone = TimeZone.getTimeZone(tz);
1605 // Prevent reentrant calls from stepping on each other when writing
1606 // the time zone property
1607 boolean timeZoneWasChanged = false;
1608 synchronized (this) {
1609 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1610 if (current == null || !current.equals(zone.getID())) {
1611 if (localLOGV) {
1612 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1613 }
1614 timeZoneWasChanged = true;
1615 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1616 }
1617
1618 // Update the kernel timezone information
1619 // Kernel tracks time offsets as 'minutes west of GMT'
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001620 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
1621 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001622 }
1623
1624 TimeZone.setDefault(null);
1625
1626 if (timeZoneWasChanged) {
Christopher Tatea4618b02018-10-11 16:22:55 -07001627 // Don't wait for broadcasts to update our midnight alarm
1628 mClockReceiver.scheduleDateChangedEvent();
1629
1630 // And now let everyone else know
Adam Lesinski182f73f2013-12-05 16:48:06 -08001631 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001632 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001633 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001634 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001635 intent.putExtra("time-zone", zone.getID());
1636 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001639
Christopher Tatec8b7f432018-09-28 16:23:10 -07001640 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001641 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001642 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001643 }
1644 }
1645
1646 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001647 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1648 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1649 int callingUid, String callingPackage) {
1650 // must be *either* PendingIntent or AlarmReceiver, but not both
1651 if ((operation == null && directReceiver == null)
1652 || (operation != null && directReceiver != null)) {
1653 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1654 // NB: previous releases failed silently here, so we are continuing to do the same
1655 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001656 return;
1657 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001658
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001659 // Sanity check the window length. This will catch people mistakenly
1660 // trying to pass an end-of-window timestamp rather than a duration.
1661 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1662 Slog.w(TAG, "Window length " + windowLength
1663 + "ms suspiciously long; limiting to 1 hour");
1664 windowLength = AlarmManager.INTERVAL_HOUR;
1665 }
1666
Christopher Tate498c6cb2014-11-17 16:09:27 -08001667 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001668 // seconds when the API expects milliseconds, or apps trying shenanigans
1669 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001670 final long minInterval = mConstants.MIN_INTERVAL;
1671 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001672 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001673 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001674 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001675 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001676 } else if (interval > mConstants.MAX_INTERVAL) {
1677 Slog.w(TAG, "Suspiciously long interval " + interval
1678 + " millis; clamping");
1679 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001680 }
1681
Christopher Tatee0a22b32013-07-11 14:43:13 -07001682 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1683 throw new IllegalArgumentException("Invalid alarm type " + type);
1684 }
1685
Christopher Tate5f221e82013-07-30 17:13:15 -07001686 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001687 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001688 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001689 + " pid=" + what);
1690 triggerAtTime = 0;
1691 }
1692
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001693 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001694 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1695 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001696 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001697 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1698
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001699 final long maxElapsed;
1700 if (windowLength == AlarmManager.WINDOW_EXACT) {
1701 maxElapsed = triggerElapsed;
1702 } else if (windowLength < 0) {
1703 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001704 // Fix this window in place, so that as time approaches we don't collapse it.
1705 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001706 } else {
1707 maxElapsed = triggerElapsed + windowLength;
1708 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001709
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001711 if (DEBUG_BATCH) {
1712 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001713 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001714 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001715 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001717 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001718 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1719 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720 }
1721 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001722
Christopher Tate3e04b472013-10-21 17:51:31 -07001723 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001724 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1725 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1726 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001727 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001728 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1729 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001730 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001731 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001732 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1733 + " -- package not allowed to start");
1734 return;
1735 }
1736 } catch (RemoteException e) {
1737 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001738 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001739 setImplLocked(a, false, doValidate);
1740 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001741
Christopher Tatef2159712018-03-27 16:04:14 -07001742 /**
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001743 * Returns the maximum alarms that an app in the specified bucket can receive in a rolling time
1744 * window given by {@link Constants#APP_STANDBY_WINDOW}
1745 */
1746 @VisibleForTesting
1747 int getQuotaForBucketLocked(int bucket) {
1748 final int index;
1749 if (bucket <= UsageStatsManager.STANDBY_BUCKET_ACTIVE) {
1750 index = ACTIVE_INDEX;
1751 } else if (bucket <= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1752 index = WORKING_INDEX;
1753 } else if (bucket <= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1754 index = FREQUENT_INDEX;
1755 } else if (bucket < UsageStatsManager.STANDBY_BUCKET_NEVER) {
1756 index = RARE_INDEX;
1757 } else {
1758 index = NEVER_INDEX;
1759 }
1760 return mConstants.APP_STANDBY_QUOTAS[index];
1761 }
1762
1763 /**
Christopher Tatef2159712018-03-27 16:04:14 -07001764 * Return the minimum time that should elapse before an app in the specified bucket
1765 * can receive alarms again
1766 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001767 @VisibleForTesting
1768 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001769 // UsageStats bucket values are treated as floors of their behavioral range.
1770 // In other words, a bucket value between WORKING and ACTIVE is treated as
1771 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1772 // values.
1773 final int index;
1774
1775 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1776 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1777 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1778 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1779 else index = ACTIVE_INDEX;
1780
1781 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001782 }
1783
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001784 /**
1785 * Adjusts the alarm delivery time based on the current app standby bucket.
1786 * @param alarm The alarm to adjust
1787 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001788 */
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001789 private boolean adjustDeliveryTimeBasedOnBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001790 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001791 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001792 }
1793 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001794 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001795 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001796 alarm.whenElapsed = alarm.expectedWhenElapsed;
1797 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1798 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001799 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001800 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001801 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001802 final long oldWhenElapsed = alarm.whenElapsed;
1803 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1804
Suprabh Shukla75edab12018-01-29 14:09:06 -08001805 final String sourcePackage = alarm.sourcePackage;
1806 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1807 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001808 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001809
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001810 if (mConstants.APP_STANDBY_QUOTAS_ENABLED) {
1811 // Quota deferring implementation:
1812 final int wakeupsInWindow = mAppWakeupHistory.getTotalWakeupsInWindow(sourcePackage,
1813 sourceUserId);
1814 final int quotaForBucket = getQuotaForBucketLocked(standbyBucket);
1815 boolean deferred = false;
1816 if (wakeupsInWindow >= quotaForBucket) {
1817 final long minElapsed;
1818 if (quotaForBucket <= 0) {
1819 // Just keep deferring for a day till the quota changes
1820 minElapsed = mInjector.getElapsedRealtime() + MILLIS_IN_DAY;
1821 } else {
1822 // Suppose the quota for window was q, and the qth last delivery time for this
1823 // package was t(q) then the next delivery must be after t(q) + <window_size>
1824 final long t = mAppWakeupHistory.getLastWakeupForPackage(sourcePackage,
1825 sourceUserId, quotaForBucket);
1826 minElapsed = t + 1 + mConstants.APP_STANDBY_WINDOW;
1827 }
1828 if (alarm.expectedWhenElapsed < minElapsed) {
1829 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1830 deferred = true;
1831 }
1832 }
1833 if (!deferred) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001834 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001835 alarm.whenElapsed = alarm.expectedWhenElapsed;
1836 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001837 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001838 } else {
1839 // Minimum delay deferring implementation:
1840 final long lastElapsed = mAppWakeupHistory.getLastWakeupForPackage(sourcePackage,
1841 sourceUserId, 1);
1842 if (lastElapsed > 0) {
1843 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
1844 if (alarm.expectedWhenElapsed < minElapsed) {
1845 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1846 } else {
1847 // app is now eligible to run alarms at the originally requested window.
1848 // Restore original requirements in case they were changed earlier.
1849 alarm.whenElapsed = alarm.expectedWhenElapsed;
1850 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1851 }
1852 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001853 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001854 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001855 }
1856
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001857 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1858 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001859 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001860 // The caller has given the time they want this to happen at, however we need
1861 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001862 // bring us out of idle at an earlier time.
1863 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001864 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001865 }
1866 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001867 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001868 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001869 if (fuzz > 0) {
1870 if (mRandom == null) {
1871 mRandom = new Random();
1872 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001873 final int delta = mRandom.nextInt(fuzz);
1874 a.whenElapsed -= delta;
1875 if (false) {
1876 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1877 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1878 Slog.d(TAG, "Applied fuzz: " + fuzz);
1879 Slog.d(TAG, "Final delta: " + delta);
1880 Slog.d(TAG, "Final when: " + a.whenElapsed);
1881 }
1882 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001883 }
1884
1885 } else if (mPendingIdleUntil != null) {
1886 // We currently have an idle until alarm scheduled; if the new alarm has
1887 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001888 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1889 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1890 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001891 == 0) {
1892 mPendingWhileIdleAlarms.add(a);
1893 return;
1894 }
1895 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001896 if (RECORD_DEVICE_IDLE_ALARMS) {
1897 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1898 IdleDispatchEntry ent = new IdleDispatchEntry();
1899 ent.uid = a.uid;
1900 ent.pkg = a.operation.getCreatorPackage();
1901 ent.tag = a.operation.getTag("");
1902 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001903 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001904 ent.argRealtime = a.whenElapsed;
1905 mAllowWhileIdleDispatches.add(ent);
1906 }
1907 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001908 adjustDeliveryTimeBasedOnBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001909 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001910
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001911 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001912 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001913 }
1914
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001915 boolean needRebatch = false;
1916
1917 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001918 if (RECORD_DEVICE_IDLE_ALARMS) {
1919 if (mPendingIdleUntil == null) {
1920 IdleDispatchEntry ent = new IdleDispatchEntry();
1921 ent.uid = 0;
1922 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001923 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001924 mAllowWhileIdleDispatches.add(ent);
1925 }
1926 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001927 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1928 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1929 + " to " + a);
1930 }
1931
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001932 mPendingIdleUntil = a;
1933 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001934 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1935 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1936 mNextWakeFromIdle = a;
1937 // If this wake from idle is earlier than whatever was previously scheduled,
1938 // and we are currently idling, then we need to rebatch alarms in case the idle
1939 // until time needs to be updated.
1940 if (mPendingIdleUntil != null) {
1941 needRebatch = true;
1942 }
1943 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001944 }
1945
1946 if (!rebatching) {
1947 if (DEBUG_VALIDATE) {
1948 if (doValidate && !validateConsistencyLocked()) {
1949 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1950 + " when(hex)=" + Long.toHexString(a.when)
1951 + " whenElapsed=" + a.whenElapsed
1952 + " maxWhenElapsed=" + a.maxWhenElapsed
1953 + " interval=" + a.repeatInterval + " op=" + a.operation
1954 + " flags=0x" + Integer.toHexString(a.flags));
1955 rebatchAllAlarmsLocked(false);
1956 needRebatch = false;
1957 }
1958 }
1959
1960 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001961 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001962 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001963
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001964 rescheduleKernelAlarmsLocked();
1965 updateNextAlarmClockLocked();
1966 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001967 }
1968
Christopher Tate1d99c392017-12-07 16:54:04 -08001969 /**
1970 * System-process internal API
1971 */
1972 private final class LocalService implements AlarmManagerInternal {
1973 @Override
1974 public void removeAlarmsForUid(int uid) {
1975 synchronized (mLock) {
1976 removeLocked(uid);
1977 }
1978 }
1979 }
1980
1981 /**
1982 * Public-facing binder interface
1983 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001984 private final IBinder mService = new IAlarmManager.Stub() {
1985 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001986 public void set(String callingPackage,
1987 int type, long triggerAtTime, long windowLength, long interval, int flags,
1988 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1989 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001990 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001991
1992 // make sure the caller is not lying about which package should be blamed for
1993 // wakelock time spent in alarm delivery
1994 mAppOps.checkPackage(callingUid, callingPackage);
1995
1996 // Repeating alarms must use PendingIntent, not direct listener
1997 if (interval != 0) {
1998 if (directReceiver != null) {
1999 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
2000 }
2001 }
2002
Adam Lesinski182f73f2013-12-05 16:48:06 -08002003 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002004 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08002005 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002006 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07002007 }
2008
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002009 // No incoming callers can request either WAKE_FROM_IDLE or
2010 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
2011 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
2012 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
2013
2014 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
2015 // manager when to come out of idle mode, which is only for DeviceIdleController.
2016 if (callingUid != Process.SYSTEM_UID) {
2017 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
2018 }
2019
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002020 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002021 if (windowLength == AlarmManager.WINDOW_EXACT) {
2022 flags |= AlarmManager.FLAG_STANDALONE;
2023 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002024
2025 // If this alarm is for an alarm clock, then it must be standalone and we will
2026 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002027 if (alarmClock != null) {
2028 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002029
2030 // If the caller is a core system component or on the user's whitelist, and not calling
2031 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
2032 // This means we will allow these alarms to go off as normal even while idle, with no
2033 // timing restrictions.
2034 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08002035 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08002036 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002037 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002038 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
2039 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002040 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002041
Christopher Tate14a7bb02015-10-01 10:24:31 -07002042 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
2043 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002044 }
Christopher Tate89779822012-08-31 14:40:03 -07002045
Adam Lesinski182f73f2013-12-05 16:48:06 -08002046 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08002047 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002048 getContext().enforceCallingOrSelfPermission(
2049 "android.permission.SET_TIME",
2050 "setTime");
2051
mswest463f4c99d2018-02-01 10:13:10 -08002052 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002054
2055 @Override
2056 public void setTimeZone(String tz) {
2057 getContext().enforceCallingOrSelfPermission(
2058 "android.permission.SET_TIME_ZONE",
2059 "setTimeZone");
2060
2061 final long oldId = Binder.clearCallingIdentity();
2062 try {
2063 setTimeZoneImpl(tz);
2064 } finally {
2065 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002066 }
2067 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07002068
Adam Lesinski182f73f2013-12-05 16:48:06 -08002069 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07002070 public void remove(PendingIntent operation, IAlarmListener listener) {
2071 if (operation == null && listener == null) {
2072 Slog.w(TAG, "remove() with no intent or listener");
2073 return;
2074 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002075
Christopher Tate14a7bb02015-10-01 10:24:31 -07002076 synchronized (mLock) {
2077 removeLocked(operation, listener);
2078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07002080
Adam Lesinski182f73f2013-12-05 16:48:06 -08002081 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002082 public long getNextWakeFromIdleTime() {
2083 return getNextWakeFromIdleTimeImpl();
2084 }
2085
2086 @Override
Jose Lima235510e2014-08-13 12:50:01 -07002087 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002088 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2089 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
2090 "getNextAlarmClock", null);
2091
2092 return getNextAlarmClockImpl(userId);
2093 }
2094
2095 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07002096 public long currentNetworkTimeMillis() {
2097 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
2098 if (time.hasCache()) {
2099 return time.currentTimeMillis();
2100 } else {
2101 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
2102 }
2103 }
2104
2105 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08002106 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002107 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07002108
2109 if (args.length > 0 && "--proto".equals(args[0])) {
2110 dumpProto(fd);
2111 } else {
2112 dumpImpl(pw);
2113 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002114 }
mswest463f4c99d2018-02-01 10:13:10 -08002115
2116 @Override
2117 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2118 FileDescriptor err, String[] args, ShellCallback callback,
2119 ResultReceiver resultReceiver) {
2120 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
2121 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002122 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07002123
Adam Lesinski182f73f2013-12-05 16:48:06 -08002124 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002125 synchronized (mLock) {
2126 pw.println("Current Alarm Manager state:");
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08002127 mConstants.dump(pw, " ");
Dianne Hackborna750a632015-06-16 17:18:23 -07002128 pw.println();
2129
Makoto Onukie4918212018-02-06 11:30:15 -08002130 if (mAppStateTracker != null) {
2131 mAppStateTracker.dump(pw, " ");
2132 pw.println();
2133 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002134
Suprabh Shukla75edab12018-01-29 14:09:06 -08002135 pw.println(" App Standby Parole: " + mAppStandbyParole);
2136 pw.println();
2137
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002138 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002139 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07002140 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08002141 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002142
Dianne Hackborna750a632015-06-16 17:18:23 -07002143 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002144 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08002145 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002146 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002147 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002148 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08002149 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08002150 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
2151 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08002152 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
2153 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002154
Christopher Tatec8b7f432018-09-28 16:23:10 -07002155 if (RECORD_ALARMS_IN_HISTORY) {
2156 pw.println();
2157 pw.println(" Recent TIME_TICK history:");
2158 int i = mNextTickHistory;
2159 do {
2160 i--;
2161 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
2162 final long time = mTickHistory[i];
2163 pw.print(" ");
2164 pw.println((time > 0)
2165 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
2166 : "-");
2167 } while (i != mNextTickHistory);
2168 pw.println();
2169 }
2170
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002171 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
2172 if (ssm != null) {
2173 pw.println();
2174 pw.print(" RuntimeStarted=");
2175 pw.print(sdf.format(
2176 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
2177 if (ssm.isRuntimeRestarted()) {
2178 pw.print(" (Runtime restarted)");
2179 }
2180 pw.println();
2181 pw.print(" Runtime uptime (elapsed): ");
2182 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
2183 pw.println();
2184 pw.print(" Runtime uptime (uptime): ");
2185 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
2186 pw.println();
2187 }
2188
Dianne Hackbornc3527222015-05-13 14:03:20 -07002189 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002190 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002191 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002192 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
2193 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002194 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08002195 pw.print(" Max wakeup delay: ");
2196 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
2197 pw.println();
2198 pw.print(" Time since last dispatch: ");
2199 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
2200 pw.println();
2201 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002202 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08002203 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002204
2205 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
2206 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07002207 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002208 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002209 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002210 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002211 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
2212 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08002213 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
2214 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002215 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002216 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002217 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07002218
2219 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002220 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002221 pw.println();
2222 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002223 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002224 pw.println();
2225
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002226 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002227 pw.print(" = "); pw.println(mLastWakeup);
2228 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2229 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002230 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002231
John Spurlock604a5ee2015-06-01 12:27:22 -04002232 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002233 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002234 final TreeSet<Integer> users = new TreeSet<>();
2235 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2236 users.add(mNextAlarmClockForUser.keyAt(i));
2237 }
2238 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2239 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2240 }
2241 for (int user : users) {
2242 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2243 final long time = next != null ? next.getTriggerTime() : 0;
2244 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002245 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002246 pw.print(" pendingSend:"); pw.print(pendingSend);
2247 pw.print(" time:"); pw.print(time);
2248 if (time > 0) {
2249 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2250 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2251 }
2252 pw.println();
2253 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002254 if (mAlarmBatches.size() > 0) {
2255 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002256 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002257 pw.println(mAlarmBatches.size());
2258 for (Batch b : mAlarmBatches) {
2259 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002260 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002261 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002262 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002263 pw.println();
2264 pw.println(" Pending user blocked background alarms: ");
2265 boolean blocked = false;
2266 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2267 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2268 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2269 blocked = true;
2270 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2271 }
2272 }
2273 if (!blocked) {
2274 pw.println(" none");
2275 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002276
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08002277 mAppWakeupHistory.dump(pw, " ", nowELAPSED);
Suprabh Shukla75edab12018-01-29 14:09:06 -08002278
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002279 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002280 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002281 pw.println(" Idle mode state:");
2282 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002283 if (mPendingIdleUntil != null) {
2284 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002285 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002286 } else {
2287 pw.println("null");
2288 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002289 pw.println(" Pending alarms:");
2290 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002291 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002292 if (mNextWakeFromIdle != null) {
2293 pw.println();
2294 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002295 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002296 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002297
2298 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002299 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002300 if (mPendingNonWakeupAlarms.size() > 0) {
2301 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002302 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002303 } else {
2304 pw.println("(none)");
2305 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002306 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002307 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2308 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002309 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002310 pw.print(", max non-interactive time: ");
2311 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2312 pw.println();
2313
2314 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002315 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002316 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2317 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2318 pw.print(" Listener send count: "); pw.println(mListenerCount);
2319 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002320 pw.println();
2321
Christopher Tate7f2a0352015-12-08 10:24:33 -08002322 if (mInFlight.size() > 0) {
2323 pw.println("Outstanding deliveries:");
2324 for (int i = 0; i < mInFlight.size(); i++) {
2325 pw.print(" #"); pw.print(i); pw.print(": ");
2326 pw.println(mInFlight.get(i));
2327 }
2328 pw.println();
2329 }
2330
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002331 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002332 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002333 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002334 pw.print(" UID ");
2335 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2336 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002337 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002338 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2339 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2340
2341 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2342 pw.print(" Next allowed:");
2343 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2344 pw.print(" (");
2345 TimeUtils.formatDuration(minInterval, 0, pw);
2346 pw.print(")");
2347
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002348 pw.println();
2349 }
2350 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002351
2352 pw.print(" mUseAllowWhileIdleShortTime: [");
2353 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2354 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2355 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2356 pw.print(" ");
2357 }
2358 }
2359 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002360 pw.println();
2361
Dianne Hackborn81038902012-11-26 17:04:09 -08002362 if (mLog.dump(pw, " Recent problems", " ")) {
2363 pw.println();
2364 }
2365
2366 final FilterStats[] topFilters = new FilterStats[10];
2367 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2368 @Override
2369 public int compare(FilterStats lhs, FilterStats rhs) {
2370 if (lhs.aggregateTime < rhs.aggregateTime) {
2371 return 1;
2372 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2373 return -1;
2374 }
2375 return 0;
2376 }
2377 };
2378 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002379 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002380 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2381 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2382 for (int ip=0; ip<uidStats.size(); ip++) {
2383 BroadcastStats bs = uidStats.valueAt(ip);
2384 for (int is=0; is<bs.filterStats.size(); is++) {
2385 FilterStats fs = bs.filterStats.valueAt(is);
2386 int pos = len > 0
2387 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2388 if (pos < 0) {
2389 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002390 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002391 if (pos < topFilters.length) {
2392 int copylen = topFilters.length - pos - 1;
2393 if (copylen > 0) {
2394 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2395 }
2396 topFilters[pos] = fs;
2397 if (len < topFilters.length) {
2398 len++;
2399 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002400 }
2401 }
2402 }
2403 }
2404 if (len > 0) {
2405 pw.println(" Top Alarms:");
2406 for (int i=0; i<len; i++) {
2407 FilterStats fs = topFilters[i];
2408 pw.print(" ");
2409 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2410 TimeUtils.formatDuration(fs.aggregateTime, pw);
2411 pw.print(" running, "); pw.print(fs.numWakeup);
2412 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002413 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2414 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002415 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002416 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002417 pw.println();
2418 }
2419 }
2420
2421 pw.println(" ");
2422 pw.println(" Alarm Stats:");
2423 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002424 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2425 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2426 for (int ip=0; ip<uidStats.size(); ip++) {
2427 BroadcastStats bs = uidStats.valueAt(ip);
2428 pw.print(" ");
2429 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2430 UserHandle.formatUid(pw, bs.mUid);
2431 pw.print(":");
2432 pw.print(bs.mPackageName);
2433 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2434 pw.print(" running, "); pw.print(bs.numWakeup);
2435 pw.println(" wakeups:");
2436 tmpFilters.clear();
2437 for (int is=0; is<bs.filterStats.size(); is++) {
2438 tmpFilters.add(bs.filterStats.valueAt(is));
2439 }
2440 Collections.sort(tmpFilters, comparator);
2441 for (int i=0; i<tmpFilters.size(); i++) {
2442 FilterStats fs = tmpFilters.get(i);
2443 pw.print(" ");
2444 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2445 TimeUtils.formatDuration(fs.aggregateTime, pw);
2446 pw.print(" "); pw.print(fs.numWakeup);
2447 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002448 pw.print(" alarms, last ");
2449 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2450 pw.println(":");
2451 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002452 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002453 pw.println();
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 }
2456 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002457 pw.println();
2458 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002459
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002460 if (RECORD_DEVICE_IDLE_ALARMS) {
2461 pw.println();
2462 pw.println(" Allow while idle dispatches:");
2463 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2464 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2465 pw.print(" ");
2466 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2467 pw.print(": ");
2468 UserHandle.formatUid(pw, ent.uid);
2469 pw.print(":");
2470 pw.println(ent.pkg);
2471 if (ent.op != null) {
2472 pw.print(" ");
2473 pw.print(ent.op);
2474 pw.print(" / ");
2475 pw.print(ent.tag);
2476 if (ent.argRealtime != 0) {
2477 pw.print(" (");
2478 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2479 pw.print(")");
2480 }
2481 pw.println();
2482 }
2483 }
2484 }
2485
Christopher Tate18a75f12013-07-01 18:18:59 -07002486 if (WAKEUP_STATS) {
2487 pw.println();
2488 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002489 long last = -1;
2490 for (WakeupEvent event : mRecentWakeups) {
2491 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2492 pw.print('|');
2493 if (last < 0) {
2494 pw.print('0');
2495 } else {
2496 pw.print(event.when - last);
2497 }
2498 last = event.when;
2499 pw.print('|'); pw.print(event.uid);
2500 pw.print('|'); pw.print(event.action);
2501 pw.println();
2502 }
2503 pw.println();
2504 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002505 }
2506 }
2507
Kweku Adams61e03292017-10-19 14:27:12 -07002508 void dumpProto(FileDescriptor fd) {
2509 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2510
2511 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002512 final long nowRTC = mInjector.getCurrentTimeMillis();
2513 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002514 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2515 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2516 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002517 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002518 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002519 mLastTimeChangeRealtime);
2520
Yi Jin2b30f322018-02-20 15:41:47 -08002521 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002522
Makoto Onukie4918212018-02-06 11:30:15 -08002523 if (mAppStateTracker != null) {
2524 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002525 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002526 }
Kweku Adams61e03292017-10-19 14:27:12 -07002527
Yi Jin2b30f322018-02-20 15:41:47 -08002528 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002529 if (!mInteractive) {
2530 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002531 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002532 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002533 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002534 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002535 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002536 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002537 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002538 nowElapsed - mNextNonWakeupDeliveryTime);
2539 }
2540
Yi Jin2b30f322018-02-20 15:41:47 -08002541 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002542 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002543 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002544 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002545 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002546 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002547 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002548 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002549 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002550
2551 final TreeSet<Integer> users = new TreeSet<>();
2552 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2553 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2554 users.add(mNextAlarmClockForUser.keyAt(i));
2555 }
2556 final int pendingSendNextAlarmClockChangedForUserSize =
2557 mPendingSendNextAlarmClockChangedForUser.size();
2558 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2559 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2560 }
2561 for (int user : users) {
2562 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2563 final long time = next != null ? next.getTriggerTime() : 0;
2564 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002565 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002566 proto.write(AlarmClockMetadataProto.USER, user);
2567 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2568 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2569 proto.end(aToken);
2570 }
2571 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002572 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002573 nowElapsed, nowRTC);
2574 }
2575 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2576 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2577 if (blockedAlarms != null) {
2578 for (Alarm a : blockedAlarms) {
2579 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002580 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002581 nowElapsed, nowRTC);
2582 }
2583 }
2584 }
2585 if (mPendingIdleUntil != null) {
2586 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002587 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002588 }
2589 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002590 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002591 nowElapsed, nowRTC);
2592 }
2593 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002594 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002595 nowElapsed, nowRTC);
2596 }
2597
2598 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002599 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002600 nowElapsed, nowRTC);
2601 }
2602
Yi Jin2b30f322018-02-20 15:41:47 -08002603 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2604 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2605 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2606 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002607 mNonInteractiveTime);
2608
Yi Jin2b30f322018-02-20 15:41:47 -08002609 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2610 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2611 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2612 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2613 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002614
2615 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002616 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002617 }
2618
Kweku Adams61e03292017-10-19 14:27:12 -07002619 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2620 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002621 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002622 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2623 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2624
Yi Jin2b30f322018-02-20 15:41:47 -08002625 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2626 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2627 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002628 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002629 proto.end(token);
2630 }
2631
Makoto Onukiadb50d82018-01-29 16:20:30 -08002632 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2633 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002634 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002635 mUseAllowWhileIdleShortTime.keyAt(i));
2636 }
2637 }
2638
Yi Jin2b30f322018-02-20 15:41:47 -08002639 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002640
2641 final FilterStats[] topFilters = new FilterStats[10];
2642 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2643 @Override
2644 public int compare(FilterStats lhs, FilterStats rhs) {
2645 if (lhs.aggregateTime < rhs.aggregateTime) {
2646 return 1;
2647 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2648 return -1;
2649 }
2650 return 0;
2651 }
2652 };
2653 int len = 0;
2654 // Get the top 10 FilterStats, ordered by aggregateTime.
2655 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2656 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2657 for (int ip = 0; ip < uidStats.size(); ++ip) {
2658 BroadcastStats bs = uidStats.valueAt(ip);
2659 for (int is = 0; is < bs.filterStats.size(); ++is) {
2660 FilterStats fs = bs.filterStats.valueAt(is);
2661 int pos = len > 0
2662 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2663 if (pos < 0) {
2664 pos = -pos - 1;
2665 }
2666 if (pos < topFilters.length) {
2667 int copylen = topFilters.length - pos - 1;
2668 if (copylen > 0) {
2669 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2670 }
2671 topFilters[pos] = fs;
2672 if (len < topFilters.length) {
2673 len++;
2674 }
2675 }
2676 }
2677 }
2678 }
2679 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002680 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002681 FilterStats fs = topFilters[i];
2682
Yi Jin2b30f322018-02-20 15:41:47 -08002683 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2684 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002685 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002686 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002687
2688 proto.end(token);
2689 }
2690
2691 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2692 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2693 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2694 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002695 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002696
2697 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002698 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002699
2700 // uidStats is an ArrayMap, which we can't sort.
2701 tmpFilters.clear();
2702 for (int is = 0; is < bs.filterStats.size(); ++is) {
2703 tmpFilters.add(bs.filterStats.valueAt(is));
2704 }
2705 Collections.sort(tmpFilters, comparator);
2706 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002707 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002708 }
2709
2710 proto.end(token);
2711 }
2712 }
2713
2714 if (RECORD_DEVICE_IDLE_ALARMS) {
2715 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2716 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2717 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002718 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002719
2720 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2721 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2722 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2723 proto.write(IdleDispatchEntryProto.OP, ent.op);
2724 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2725 ent.elapsedRealtime);
2726 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2727
2728 proto.end(token);
2729 }
2730 }
2731
2732 if (WAKEUP_STATS) {
2733 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002734 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002735 proto.write(WakeupEventProto.UID, event.uid);
2736 proto.write(WakeupEventProto.ACTION, event.action);
2737 proto.write(WakeupEventProto.WHEN, event.when);
2738 proto.end(token);
2739 }
2740 }
2741 }
2742
2743 proto.flush();
2744 }
2745
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002746 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002747 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2748 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002749 final long nowRTC = mInjector.getCurrentTimeMillis();
2750 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002751 final int NZ = mAlarmBatches.size();
2752 for (int iz = 0; iz < NZ; iz++) {
2753 Batch bz = mAlarmBatches.get(iz);
2754 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002755 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002756 pw.flush();
2757 Slog.v(TAG, bs.toString());
2758 bs.reset();
2759 }
2760 }
2761
2762 private boolean validateConsistencyLocked() {
2763 if (DEBUG_VALIDATE) {
2764 long lastTime = Long.MIN_VALUE;
2765 final int N = mAlarmBatches.size();
2766 for (int i = 0; i < N; i++) {
2767 Batch b = mAlarmBatches.get(i);
2768 if (b.start >= lastTime) {
2769 // duplicate start times are okay because of standalone batches
2770 lastTime = b.start;
2771 } else {
2772 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002773 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2774 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002775 return false;
2776 }
2777 }
2778 }
2779 return true;
2780 }
2781
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002782 private Batch findFirstWakeupBatchLocked() {
2783 final int N = mAlarmBatches.size();
2784 for (int i = 0; i < N; i++) {
2785 Batch b = mAlarmBatches.get(i);
2786 if (b.hasWakeups()) {
2787 return b;
2788 }
2789 }
2790 return null;
2791 }
2792
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002793 long getNextWakeFromIdleTimeImpl() {
2794 synchronized (mLock) {
2795 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2796 }
2797 }
2798
2799 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002800 synchronized (mLock) {
2801 return mNextAlarmClockForUser.get(userId);
2802 }
2803 }
2804
2805 /**
2806 * Recomputes the next alarm clock for all users.
2807 */
2808 private void updateNextAlarmClockLocked() {
2809 if (!mNextAlarmClockMayChange) {
2810 return;
2811 }
2812 mNextAlarmClockMayChange = false;
2813
Jose Lima235510e2014-08-13 12:50:01 -07002814 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002815 nextForUser.clear();
2816
2817 final int N = mAlarmBatches.size();
2818 for (int i = 0; i < N; i++) {
2819 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2820 final int M = alarms.size();
2821
2822 for (int j = 0; j < M; j++) {
2823 Alarm a = alarms.get(j);
2824 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002825 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002826 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002827
2828 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002829 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002830 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002831 " for user " + userId);
2832 }
2833
2834 // Alarms and batches are sorted by time, no need to compare times here.
2835 if (nextForUser.get(userId) == null) {
2836 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002837 } else if (a.alarmClock.equals(current)
2838 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2839 // same/earlier time and it's the one we cited before, so stick with it
2840 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002841 }
2842 }
2843 }
2844 }
2845
2846 // Update mNextAlarmForUser with new values.
2847 final int NN = nextForUser.size();
2848 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002849 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002850 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002851 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002852 if (!newAlarm.equals(currentAlarm)) {
2853 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2854 }
2855 }
2856
2857 // Remove users without any alarm clocks scheduled.
2858 final int NNN = mNextAlarmClockForUser.size();
2859 for (int i = NNN - 1; i >= 0; i--) {
2860 int userId = mNextAlarmClockForUser.keyAt(i);
2861 if (nextForUser.get(userId) == null) {
2862 updateNextAlarmInfoForUserLocked(userId, null);
2863 }
2864 }
2865 }
2866
Jose Lima235510e2014-08-13 12:50:01 -07002867 private void updateNextAlarmInfoForUserLocked(int userId,
2868 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002869 if (alarmClock != null) {
2870 if (DEBUG_ALARM_CLOCK) {
2871 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002872 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002873 }
2874 mNextAlarmClockForUser.put(userId, alarmClock);
2875 } else {
2876 if (DEBUG_ALARM_CLOCK) {
2877 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2878 }
2879 mNextAlarmClockForUser.remove(userId);
2880 }
2881
2882 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2883 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2884 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2885 }
2886
2887 /**
2888 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2889 * for which alarm clocks have changed since the last call to this.
2890 *
2891 * Do not call with a lock held. Only call from mHandler's thread.
2892 *
2893 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2894 */
2895 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002896 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002897 pendingUsers.clear();
2898
2899 synchronized (mLock) {
2900 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2901 for (int i = 0; i < N; i++) {
2902 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2903 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2904 }
2905 mPendingSendNextAlarmClockChangedForUser.clear();
2906 }
2907
2908 final int N = pendingUsers.size();
2909 for (int i = 0; i < N; i++) {
2910 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002911 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002912 Settings.System.putStringForUser(getContext().getContentResolver(),
2913 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002914 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002915 userId);
2916
2917 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2918 new UserHandle(userId));
2919 }
2920 }
2921
2922 /**
2923 * Formats an alarm like platform/packages/apps/DeskClock used to.
2924 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002925 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2926 int userId) {
2927 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002928 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2929 return (info == null) ? "" :
2930 DateFormat.format(pattern, info.getTriggerTime()).toString();
2931 }
2932
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002933 /**
2934 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2935 * by more than half a minute, log a wtf.
2936 */
2937 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2938 final StringBuilder errorMsg = new StringBuilder();
2939 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002940 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002941 stuck = true;
2942 errorMsg.append("[mNextNonWakeup=");
2943 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002944 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002945 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002946 errorMsg.append(", mLastWakeup=");
2947 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002948 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002949 errorMsg.append("];");
2950 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002951 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002952 stuck = true;
2953 errorMsg.append("[mNextWakeup=");
2954 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002955 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002956 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002957 errorMsg.append(", mLastWakeup=");
2958 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2959 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002960 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002961 errorMsg.append("];");
2962 }
2963 if (stuck) {
2964 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2965 }
2966 }
2967
Adam Lesinski182f73f2013-12-05 16:48:06 -08002968 void rescheduleKernelAlarmsLocked() {
2969 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2970 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002971 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002972 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002973 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002974 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002975 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002976 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002977 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002978 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002979 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002980 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002981 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002982 if (firstBatch != firstWakeup) {
2983 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002984 }
2985 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002986 if (mPendingNonWakeupAlarms.size() > 0) {
2987 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2988 nextNonWakeup = mNextNonWakeupDeliveryTime;
2989 }
2990 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002991 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002992 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002993 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002994 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2995 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002996 }
2997
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002998 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002999 if (operation == null && directReceiver == null) {
3000 if (localLOGV) {
3001 Slog.w(TAG, "requested remove() of null operation",
3002 new RuntimeException("here"));
3003 }
3004 return;
3005 }
3006
Adam Lesinski182f73f2013-12-05 16:48:06 -08003007 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003008 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003009 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3010 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003011 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003012 if (b.size() == 0) {
3013 mAlarmBatches.remove(i);
3014 }
3015 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003016 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003017 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003018 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3019 mPendingWhileIdleAlarms.remove(i);
3020 }
3021 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003022 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3023 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3024 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3025 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
3026 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3027 alarmsForUid.remove(j);
3028 }
3029 }
3030 if (alarmsForUid.size() == 0) {
3031 mPendingBackgroundAlarms.removeAt(i);
3032 }
3033 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003034 if (didRemove) {
3035 if (DEBUG_BATCH) {
3036 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
3037 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003038 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003039 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003040 mPendingIdleUntil = null;
3041 restorePending = true;
3042 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003043 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003044 mNextWakeFromIdle = null;
3045 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003046 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003047 if (restorePending) {
3048 restorePendingWhileIdleAlarmsLocked();
3049 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003050 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003051 }
3052 }
3053
Christopher Tate1d99c392017-12-07 16:54:04 -08003054 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003055 if (uid == Process.SYSTEM_UID) {
3056 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
3057 return;
3058 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003059 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003060 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003061 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3062 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003063 didRemove |= b.remove(whichAlarms);
3064 if (b.size() == 0) {
3065 mAlarmBatches.remove(i);
3066 }
3067 }
3068 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
3069 final Alarm a = mPendingWhileIdleAlarms.get(i);
3070 if (a.uid == uid) {
3071 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3072 mPendingWhileIdleAlarms.remove(i);
3073 }
3074 }
3075 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
3076 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3077 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3078 if (alarmsForUid.get(j).uid == uid) {
3079 alarmsForUid.remove(j);
3080 }
3081 }
3082 if (alarmsForUid.size() == 0) {
3083 mPendingBackgroundAlarms.removeAt(i);
3084 }
3085 }
3086 if (didRemove) {
3087 if (DEBUG_BATCH) {
3088 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
3089 }
3090 rebatchAllAlarmsLocked(true);
3091 rescheduleKernelAlarmsLocked();
3092 updateNextAlarmClockLocked();
3093 }
3094 }
3095
3096 void removeLocked(final String packageName) {
3097 if (packageName == null) {
3098 if (localLOGV) {
3099 Slog.w(TAG, "requested remove() of null packageName",
3100 new RuntimeException("here"));
3101 }
3102 return;
3103 }
3104
3105 boolean didRemove = false;
3106 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08003107 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08003108 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3109 Batch b = mAlarmBatches.get(i);
3110 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003111 if (b.size() == 0) {
3112 mAlarmBatches.remove(i);
3113 }
3114 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08003115 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
3116 if (oldHasTick != newHasTick) {
3117 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
3118 }
3119
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003120 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003121 final Alarm a = mPendingWhileIdleAlarms.get(i);
3122 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003123 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3124 mPendingWhileIdleAlarms.remove(i);
3125 }
3126 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003127 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
3128 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3129 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3130 if (alarmsForUid.get(j).matches(packageName)) {
3131 alarmsForUid.remove(j);
3132 }
3133 }
3134 if (alarmsForUid.size() == 0) {
3135 mPendingBackgroundAlarms.removeAt(i);
3136 }
3137 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003138 if (didRemove) {
3139 if (DEBUG_BATCH) {
3140 Slog.v(TAG, "remove(package) changed bounds; rebatching");
3141 }
3142 rebatchAllAlarmsLocked(true);
3143 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003144 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003145 }
3146 }
3147
Christopher Tate1d99c392017-12-07 16:54:04 -08003148 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003149 if (uid == Process.SYSTEM_UID) {
3150 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
3151 return;
3152 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003153 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003154 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
3155 try {
3156 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
3157 uid, a.packageName)) {
3158 return true;
3159 }
3160 } catch (RemoteException e) { /* fall through */}
3161 return false;
3162 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003163 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3164 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003165 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003166 if (b.size() == 0) {
3167 mAlarmBatches.remove(i);
3168 }
3169 }
3170 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
3171 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003172 if (a.uid == uid) {
3173 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3174 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003175 }
3176 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003177 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3178 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
3179 mPendingBackgroundAlarms.removeAt(i);
3180 }
3181 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003182 if (didRemove) {
3183 if (DEBUG_BATCH) {
3184 Slog.v(TAG, "remove(package) changed bounds; rebatching");
3185 }
3186 rebatchAllAlarmsLocked(true);
3187 rescheduleKernelAlarmsLocked();
3188 updateNextAlarmClockLocked();
3189 }
3190 }
3191
Adam Lesinski182f73f2013-12-05 16:48:06 -08003192 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003193 if (userHandle == UserHandle.USER_SYSTEM) {
3194 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
3195 return;
3196 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003197 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003198 final Predicate<Alarm> whichAlarms =
3199 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003200 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3201 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003202 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003203 if (b.size() == 0) {
3204 mAlarmBatches.remove(i);
3205 }
3206 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003207 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003208 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003209 == userHandle) {
3210 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3211 mPendingWhileIdleAlarms.remove(i);
3212 }
3213 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003214 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3215 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
3216 mPendingBackgroundAlarms.removeAt(i);
3217 }
3218 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003219 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3220 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3221 mLastAllowWhileIdleDispatch.removeAt(i);
3222 }
3223 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003224
3225 if (didRemove) {
3226 if (DEBUG_BATCH) {
3227 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3228 }
3229 rebatchAllAlarmsLocked(true);
3230 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003231 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003232 }
3233 }
3234
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003235 void interactiveStateChangedLocked(boolean interactive) {
3236 if (mInteractive != interactive) {
3237 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003238 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003239 if (interactive) {
3240 if (mPendingNonWakeupAlarms.size() > 0) {
3241 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3242 mTotalDelayTime += thisDelayTime;
3243 if (mMaxDelayTime < thisDelayTime) {
3244 mMaxDelayTime = thisDelayTime;
3245 }
3246 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3247 mPendingNonWakeupAlarms.clear();
3248 }
3249 if (mNonInteractiveStartTime > 0) {
3250 long dur = nowELAPSED - mNonInteractiveStartTime;
3251 if (dur > mNonInteractiveTime) {
3252 mNonInteractiveTime = dur;
3253 }
3254 }
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003255 // And send a TIME_TICK right now, since it is important to get the UI updated.
3256 mHandler.post(() ->
3257 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003258 } else {
3259 mNonInteractiveStartTime = nowELAPSED;
3260 }
3261 }
3262 }
3263
Adam Lesinski182f73f2013-12-05 16:48:06 -08003264 boolean lookForPackageLocked(String packageName) {
3265 for (int i = 0; i < mAlarmBatches.size(); i++) {
3266 Batch b = mAlarmBatches.get(i);
3267 if (b.hasPackage(packageName)) {
3268 return true;
3269 }
3270 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003271 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003272 final Alarm a = mPendingWhileIdleAlarms.get(i);
3273 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003274 return true;
3275 }
3276 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003277 return false;
3278 }
3279
3280 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003281 if (mInjector.isAlarmDriverPresent()) {
3282 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003283 } else {
3284 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003285 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003286
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003287 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003288 mHandler.sendMessageAtTime(msg, when);
3289 }
3290 }
3291
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003292 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003293 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 for (int i=list.size()-1; i>=0; i--) {
3295 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003296 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3297 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003298 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
3300 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003301
3302 private static final String labelForType(int type) {
3303 switch (type) {
3304 case RTC: return "RTC";
3305 case RTC_WAKEUP : return "RTC_WAKEUP";
3306 case ELAPSED_REALTIME : return "ELAPSED";
3307 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003308 }
3309 return "--unknown--";
3310 }
3311
3312 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003313 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003314 for (int i=list.size()-1; i>=0; i--) {
3315 Alarm a = list.get(i);
3316 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003317 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3318 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003319 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003320 }
3321 }
3322
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003323 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003324 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003325 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003326 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003327 return false;
3328 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003329 if (alarm.operation != null) {
3330 if (alarm.operation.isActivity()) {
3331 // Don't defer starting actual UI
3332 return false;
3333 }
3334 if (alarm.operation.isForegroundService()) {
3335 // FG service alarms are nearly as important; consult AST policy
3336 exemptOnBatterySaver = true;
3337 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003338 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003339 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003340 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003341 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003342 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3343 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003344 }
3345
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003346 private static native long init();
3347 private static native void close(long nativeData);
3348 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3349 private static native int waitForAlarm(long nativeData);
3350 private static native int setKernelTime(long nativeData, long millis);
3351 private static native int setKernelTimezone(long nativeData, int minuteswest);
3352 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353
Makoto Onukiadb50d82018-01-29 16:20:30 -08003354 private long getWhileIdleMinIntervalLocked(int uid) {
3355 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003356 final boolean ebs = (mAppStateTracker != null)
3357 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003358 if (!dozing && !ebs) {
3359 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3360 }
3361 if (dozing) {
3362 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3363 }
3364 if (mUseAllowWhileIdleShortTime.get(uid)) {
3365 // if the last allow-while-idle went off while uid was fg, or the uid
3366 // recently came into fg, don't block the alarm for long.
3367 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3368 }
3369 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3370 }
3371
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003372 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003373 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003374 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003375 // batches are temporally sorted, so we need only pull from the
3376 // start of the list until we either empty it or hit a batch
3377 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003378 while (mAlarmBatches.size() > 0) {
3379 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003380 if (batch.start > nowELAPSED) {
3381 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 break;
3383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384
Christopher Tatee0a22b32013-07-11 14:43:13 -07003385 // We will (re)schedule some alarms now; don't let that interfere
3386 // with delivery of this current batch
3387 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003388
Christopher Tatee0a22b32013-07-11 14:43:13 -07003389 final int N = batch.size();
3390 for (int i = 0; i < N; i++) {
3391 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003392
3393 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3394 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003395 // schedule such alarms. The first such alarm from an app is always delivered.
3396 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003397 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003398 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003399 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3400 // alarm went off for this app. Reschedule the alarm to be in the
3401 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003402 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003403 if (alarm.maxWhenElapsed < minTime) {
3404 alarm.maxWhenElapsed = minTime;
3405 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003406 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003407 if (RECORD_DEVICE_IDLE_ALARMS) {
3408 IdleDispatchEntry ent = new IdleDispatchEntry();
3409 ent.uid = alarm.uid;
3410 ent.pkg = alarm.operation.getCreatorPackage();
3411 ent.tag = alarm.operation.getTag("");
3412 ent.op = "RESCHEDULE";
3413 ent.elapsedRealtime = nowELAPSED;
3414 ent.argRealtime = lastTime;
3415 mAllowWhileIdleDispatches.add(ent);
3416 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003417 setImplLocked(alarm, true, false);
3418 continue;
3419 }
3420 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003421 if (isBackgroundRestricted(alarm)) {
3422 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3423 if (DEBUG_BG_LIMIT) {
3424 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3425 }
3426 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3427 if (alarmsForUid == null) {
3428 alarmsForUid = new ArrayList<>();
3429 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3430 }
3431 alarmsForUid.add(alarm);
3432 continue;
3433 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003434
Christopher Tatee0a22b32013-07-11 14:43:13 -07003435 alarm.count = 1;
3436 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003437 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3438 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003439 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003440 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003441 if (mPendingIdleUntil == alarm) {
3442 mPendingIdleUntil = null;
3443 rebatchAllAlarmsLocked(false);
3444 restorePendingWhileIdleAlarmsLocked();
3445 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003446 if (mNextWakeFromIdle == alarm) {
3447 mNextWakeFromIdle = null;
3448 rebatchAllAlarmsLocked(false);
3449 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003450
3451 // Recurring alarms may have passed several alarm intervals while the
3452 // phone was asleep or off, so pass a trigger count when sending them.
3453 if (alarm.repeatInterval > 0) {
3454 // this adjustment will be zero if we're late by
3455 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003456 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003457
3458 // Also schedule its next recurrence
3459 final long delta = alarm.count * alarm.repeatInterval;
3460 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003461 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003462 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003463 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3464 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003465 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466
Christopher Tate864d42e2014-12-02 11:48:53 -08003467 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003468 hasWakeup = true;
3469 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003470
3471 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3472 if (alarm.alarmClock != null) {
3473 mNextAlarmClockMayChange = true;
3474 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003475 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003476 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003477
Christopher Tate1590f1e2014-10-02 17:27:57 -07003478 // This is a new alarm delivery set; bump the sequence number to indicate that
3479 // all apps' alarm delivery classes should be recalculated.
3480 mCurrentSeq++;
3481 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003482 Collections.sort(triggerList, mAlarmDispatchComparator);
3483
3484 if (localLOGV) {
3485 for (int i=0; i<triggerList.size(); i++) {
3486 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3487 }
3488 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003489
3490 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003492
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493 /**
3494 * This Comparator sorts Alarms into increasing time order.
3495 */
3496 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3497 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003498 long when1 = a1.whenElapsed;
3499 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003500 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 return 1;
3502 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003503 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 return -1;
3505 }
3506 return 0;
3507 }
3508 }
Kweku Adams61e03292017-10-19 14:27:12 -07003509
Makoto Onuki2206af32017-11-21 16:25:35 -08003510 @VisibleForTesting
3511 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003512 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003513 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003514 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003515 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003516 public final IAlarmListener listener;
3517 public final String listenerTag;
3518 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003519 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003520 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003521 public final AlarmManager.AlarmClockInfo alarmClock;
3522 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003523 public final int creatorUid;
3524 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003525 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003526 public int count;
3527 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003528 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003529 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003530 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003531 // Expected alarm expiry time before app standby deferring is applied.
3532 public long expectedWhenElapsed;
3533 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003535 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003536
Christopher Tate3e04b472013-10-21 17:51:31 -07003537 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003538 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3539 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3540 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003541 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003542 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003543 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3544 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003545 when = _when;
3546 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003547 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003548 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003549 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003550 repeatInterval = _interval;
3551 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003552 listener = _rec;
3553 listenerTag = _listenerTag;
3554 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003555 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003556 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003557 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003558 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003559 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003560 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003561 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003562 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003563
Christopher Tate14a7bb02015-10-01 10:24:31 -07003564 public static String makeTag(PendingIntent pi, String tag, int type) {
3565 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3566 ? "*walarm*:" : "*alarm*:";
3567 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3568 }
3569
3570 public WakeupEvent makeWakeupEvent(long nowRTC) {
3571 return new WakeupEvent(nowRTC, creatorUid,
3572 (operation != null)
3573 ? operation.getIntent().getAction()
3574 : ("<listener>:" + listenerTag));
3575 }
3576
3577 // Returns true if either matches
3578 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3579 return (operation != null)
3580 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003581 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003582 }
3583
3584 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003585 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003586 }
3587
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003588 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003589 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003590 StringBuilder sb = new StringBuilder(128);
3591 sb.append("Alarm{");
3592 sb.append(Integer.toHexString(System.identityHashCode(this)));
3593 sb.append(" type ");
3594 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003595 sb.append(" when ");
3596 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003597 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003598 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003599 sb.append('}');
3600 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 }
3602
Kweku Adams61e03292017-10-19 14:27:12 -07003603 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003604 SimpleDateFormat sdf) {
3605 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003606 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003607 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003608 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3609 expectedWhenElapsed, nowELAPSED, pw);
3610 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3611 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003612 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3613 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003614 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3615 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003616 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003617 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003618 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003619 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003620 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003621 }
3622 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003623 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003624 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003625 pw.print(" count="); pw.print(count);
3626 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003627 if (alarmClock != null) {
3628 pw.print(prefix); pw.println("Alarm clock:");
3629 pw.print(prefix); pw.print(" triggerTime=");
3630 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3631 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3632 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003633 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003634 if (listener != null) {
3635 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3636 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 }
Kweku Adams61e03292017-10-19 14:27:12 -07003638
3639 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3640 long nowRTC) {
3641 final long token = proto.start(fieldId);
3642
3643 proto.write(AlarmProto.TAG, statsTag);
3644 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003645 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003646 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3647 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3648 proto.write(AlarmProto.COUNT, count);
3649 proto.write(AlarmProto.FLAGS, flags);
3650 if (alarmClock != null) {
3651 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3652 }
3653 if (operation != null) {
3654 operation.writeToProto(proto, AlarmProto.OPERATION);
3655 }
3656 if (listener != null) {
3657 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3658 }
3659
3660 proto.end(token);
3661 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003663
Christopher Tatee0a22b32013-07-11 14:43:13 -07003664 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3665 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003666 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3667 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003668 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003669 break;
3670 }
3671
Christopher Tatee0a22b32013-07-11 14:43:13 -07003672 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003673 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3674 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003675 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003676 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003677 }
3678 }
3679
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003680 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3681 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3682 if (timeSinceOn < 5*60*1000) {
3683 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3684 return 2*60*1000;
3685 } else if (timeSinceOn < 30*60*1000) {
3686 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3687 return 15*60*1000;
3688 } else {
3689 // Otherwise, we will delay by at most an hour.
3690 return 60*60*1000;
3691 }
3692 }
3693
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003694 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003695 if (duration < 15*60*1000) {
3696 // If the duration until the time is less than 15 minutes, the maximum fuzz
3697 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003698 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003699 } else if (duration < 90*60*1000) {
3700 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3701 return 15*60*1000;
3702 } else {
3703 // Otherwise, we will fuzz by at most half an hour.
3704 return 30*60*1000;
3705 }
3706 }
3707
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003708 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3709 if (mInteractive) {
3710 return false;
3711 }
3712 if (mLastAlarmDeliveryTime <= 0) {
3713 return false;
3714 }
minho.choo649acab2014-12-12 16:13:55 +09003715 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003716 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3717 // and the next delivery time is in the past, then just deliver them all. This
3718 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3719 return false;
3720 }
3721 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3722 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3723 }
3724
3725 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3726 mLastAlarmDeliveryTime = nowELAPSED;
3727 for (int i=0; i<triggerList.size(); i++) {
3728 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003729 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003730 if (alarm.wakeup) {
3731 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3732 } else {
3733 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3734 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003735 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003736 if (localLOGV) {
3737 Slog.v(TAG, "sending alarm " + alarm);
3738 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003739 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003740 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3741 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003742 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003743 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003744 } catch (RuntimeException e) {
3745 Slog.w(TAG, "Failure sending alarm.", e);
3746 }
Tim Murray175c0f92017-11-28 15:01:04 -08003747 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003748 }
3749 }
3750
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003751 private boolean isExemptFromAppStandby(Alarm a) {
3752 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3753 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3754 }
3755
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003756 @VisibleForTesting
3757 static class Injector {
3758 private long mNativeData;
3759 private Context mContext;
3760
3761 Injector(Context context) {
3762 mContext = context;
3763 }
3764
3765 void init() {
3766 mNativeData = AlarmManagerService.init();
3767 }
3768
3769 int waitForAlarm() {
3770 return AlarmManagerService.waitForAlarm(mNativeData);
3771 }
3772
3773 boolean isAlarmDriverPresent() {
3774 return mNativeData != 0;
3775 }
3776
3777 void setAlarm(int type, long millis) {
3778 // The kernel never triggers alarms with negative wakeup times
3779 // so we ensure they are positive.
3780 final long alarmSeconds, alarmNanoseconds;
3781 if (millis < 0) {
3782 alarmSeconds = 0;
3783 alarmNanoseconds = 0;
3784 } else {
3785 alarmSeconds = millis / 1000;
3786 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3787 }
3788
3789 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3790 alarmNanoseconds);
3791 if (result != 0) {
3792 final long nowElapsed = SystemClock.elapsedRealtime();
3793 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3794 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3795 + "), ret = " + result + " = " + Os.strerror(result));
3796 }
3797 }
3798
3799 long getNextAlarm(int type) {
3800 return AlarmManagerService.getNextAlarm(mNativeData, type);
3801 }
3802
3803 void setKernelTimezone(int minutesWest) {
3804 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3805 }
3806
3807 void setKernelTime(long millis) {
3808 if (mNativeData != 0) {
3809 AlarmManagerService.setKernelTime(mNativeData, millis);
3810 }
3811 }
3812
3813 void close() {
3814 AlarmManagerService.close(mNativeData);
3815 }
3816
3817 long getElapsedRealtime() {
3818 return SystemClock.elapsedRealtime();
3819 }
3820
3821 long getCurrentTimeMillis() {
3822 return System.currentTimeMillis();
3823 }
3824
3825 PowerManager.WakeLock getAlarmWakeLock() {
3826 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3827 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3828 }
3829
3830 int getSystemUiUid() {
3831 int sysUiUid = -1;
3832 final PackageManager pm = mContext.getPackageManager();
3833 try {
3834 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3835 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3836 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3837 sysUiUid = sysUi.uid;
3838 } else {
3839 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3840 + " defined by non-privileged app " + sysUi.packageName
3841 + " - ignoring");
3842 }
3843 } catch (NameNotFoundException e) {
3844 }
3845 return sysUiUid;
3846 }
3847
3848 ClockReceiver getClockReceiver(AlarmManagerService service) {
3849 return service.new ClockReceiver();
3850 }
3851 }
3852
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003853 private class AlarmThread extends Thread
3854 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003855 private int mFalseWakeups;
3856 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003857 public AlarmThread()
3858 {
3859 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003860 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003861 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 }
Kweku Adams61e03292017-10-19 14:27:12 -07003863
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003864 public void run()
3865 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003866 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3867
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003868 while (true)
3869 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003870 int result = mInjector.waitForAlarm();
3871 final long nowRTC = mInjector.getCurrentTimeMillis();
3872 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003873 synchronized (mLock) {
3874 mLastWakeup = nowELAPSED;
3875 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003876 if (result == 0) {
3877 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3878 + ", nowElapsed = " + nowELAPSED);
3879 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003880 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003882 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003883 // The kernel can give us spurious time change notifications due to
3884 // small adjustments it makes internally; we want to filter those out.
3885 final long lastTimeChangeClockTime;
3886 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003887 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003888 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3889 expectedClockTime = lastTimeChangeClockTime
3890 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003891 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003892 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3893 || nowRTC > (expectedClockTime+1000)) {
3894 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003895 // let's do it!
3896 if (DEBUG_BATCH) {
3897 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3898 }
Bookatz7948c872018-09-04 12:58:33 -07003899 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3900 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003901 removeImpl(null, mTimeTickTrigger);
3902 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003903 rebatchAllAlarms();
3904 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003905 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003906 synchronized (mLock) {
3907 mNumTimeChanged++;
3908 mLastTimeChangeClockTime = nowRTC;
3909 mLastTimeChangeRealtime = nowELAPSED;
3910 }
3911 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3912 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003913 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003914 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3915 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003916 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3917
3918 // The world has changed on us, so we need to re-evaluate alarms
3919 // regardless of whether the kernel has told us one went off.
3920 result |= IS_WAKEUP_MASK;
3921 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003922 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003923
Dianne Hackbornc3527222015-05-13 14:03:20 -07003924 if (result != TIME_CHANGED_MASK) {
3925 // If this was anything besides just a time change, then figure what if
3926 // anything to do about alarms.
3927 synchronized (mLock) {
3928 if (localLOGV) Slog.v(
3929 TAG, "Checking for alarms... rtc=" + nowRTC
3930 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003931
Dianne Hackbornc3527222015-05-13 14:03:20 -07003932 if (WAKEUP_STATS) {
3933 if ((result & IS_WAKEUP_MASK) != 0) {
3934 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3935 int n = 0;
3936 for (WakeupEvent event : mRecentWakeups) {
3937 if (event.when > newEarliest) break;
3938 n++; // number of now-stale entries at the list head
3939 }
3940 for (int i = 0; i < n; i++) {
3941 mRecentWakeups.remove();
3942 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003943
Dianne Hackbornc3527222015-05-13 14:03:20 -07003944 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003945 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003946 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003947
Christopher Tate8b98ade2018-02-09 11:13:19 -08003948 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003949 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3950 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3951 // if there are no wakeup alarms and the screen is off, we can
3952 // delay what we have so far until the future.
3953 if (mPendingNonWakeupAlarms.size() == 0) {
3954 mStartCurrentDelayTime = nowELAPSED;
3955 mNextNonWakeupDeliveryTime = nowELAPSED
3956 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3957 }
3958 mPendingNonWakeupAlarms.addAll(triggerList);
3959 mNumDelayedAlarms += triggerList.size();
3960 rescheduleKernelAlarmsLocked();
3961 updateNextAlarmClockLocked();
3962 } else {
3963 // now deliver the alarm intents; if there are pending non-wakeup
3964 // alarms, we need to merge them in to the list. note we don't
3965 // just deliver them first because we generally want non-wakeup
3966 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003967 if (mPendingNonWakeupAlarms.size() > 0) {
3968 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3969 triggerList.addAll(mPendingNonWakeupAlarms);
3970 Collections.sort(triggerList, mAlarmDispatchComparator);
3971 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3972 mTotalDelayTime += thisDelayTime;
3973 if (mMaxDelayTime < thisDelayTime) {
3974 mMaxDelayTime = thisDelayTime;
3975 }
3976 mPendingNonWakeupAlarms.clear();
3977 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003978 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3979 if (++mFalseWakeups >= mWtfThreshold) {
3980 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3981 + ") false wakeups, nowElapsed=" + nowELAPSED);
3982 if (mWtfThreshold < 100_000) {
3983 mWtfThreshold *= 10;
3984 } else {
3985 mFalseWakeups = 0;
3986 }
3987 }
3988 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003989 final ArraySet<Pair<String, Integer>> triggerPackages =
3990 new ArraySet<>();
3991 for (int i = 0; i < triggerList.size(); i++) {
3992 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003993 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003994 triggerPackages.add(Pair.create(
3995 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003996 }
3997 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003998 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003999 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
4000 rescheduleKernelAlarmsLocked();
4001 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07004002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004003 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07004004
4005 } else {
4006 // Just in case -- even though no wakeup flag was set, make sure
4007 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07004008 synchronized (mLock) {
4009 rescheduleKernelAlarmsLocked();
4010 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004011 }
4012 }
4013 }
4014 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07004015
David Christieebe51fc2013-07-26 13:23:29 -07004016 /**
4017 * Attribute blame for a WakeLock.
David Christieebe51fc2013-07-26 13:23:29 -07004018 * @param ws WorkSource to attribute blame.
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004019 * @param knownUid attribution uid; < 0 values are ignored.
David Christieebe51fc2013-07-26 13:23:29 -07004020 */
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004021 void setWakelockWorkSource(WorkSource ws, int knownUid, String tag, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07004022 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07004023 mWakeLock.setHistoryTag(first ? tag : null);
4024
David Christieebe51fc2013-07-26 13:23:29 -07004025 if (ws != null) {
4026 mWakeLock.setWorkSource(ws);
4027 return;
4028 }
4029
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004030 if (knownUid >= 0) {
4031 mWakeLock.setWorkSource(new WorkSource(knownUid));
Christopher Tatec4a07d12012-04-06 14:19:13 -07004032 return;
4033 }
4034 } catch (Exception e) {
4035 }
4036
4037 // Something went wrong; fall back to attributing the lock to the OS
4038 mWakeLock.setWorkSource(null);
4039 }
4040
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004041 private static int getAlarmAttributionUid(Alarm alarm) {
4042 if (alarm.workSource != null && !alarm.workSource.isEmpty()) {
4043 return alarm.workSource.getAttributionUid();
4044 }
4045
4046 return alarm.creatorUid;
4047 }
4048
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004049 @VisibleForTesting
4050 class AlarmHandler extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004051 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004052 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
4053 public static final int LISTENER_TIMEOUT = 3;
4054 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08004055 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
4056 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08004057 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07004058
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004059 AlarmHandler() {
4060 super(Looper.myLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004061 }
Kweku Adams61e03292017-10-19 14:27:12 -07004062
Makoto Onuki4d298b52018-02-05 10:54:58 -08004063 public void postRemoveForStopped(int uid) {
4064 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
4065 }
4066
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004067 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004069 switch (msg.what) {
4070 case ALARM_EVENT: {
4071 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
4072 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004073 final long nowRTC = mInjector.getCurrentTimeMillis();
4074 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004075 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
4076 updateNextAlarmClockLocked();
4077 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02004078
Christopher Tate14a7bb02015-10-01 10:24:31 -07004079 // now trigger the alarms without the lock held
4080 for (int i=0; i<triggerList.size(); i++) {
4081 Alarm alarm = triggerList.get(i);
4082 try {
4083 alarm.operation.send();
4084 } catch (PendingIntent.CanceledException e) {
4085 if (alarm.repeatInterval > 0) {
4086 // This IntentSender is no longer valid, but this
4087 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07004088 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004090 }
4091 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004092 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004093 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004094
4095 case SEND_NEXT_ALARM_CLOCK_CHANGED:
4096 sendNextAlarmClockChanged();
4097 break;
4098
4099 case LISTENER_TIMEOUT:
4100 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
4101 break;
4102
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004103 case REPORT_ALARMS_ACTIVE:
4104 if (mLocalDeviceIdleController != null) {
4105 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
4106 }
4107 break;
4108
Suprabh Shukla75edab12018-01-29 14:09:06 -08004109 case APP_STANDBY_PAROLE_CHANGED:
4110 synchronized (mLock) {
4111 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004112 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
4113 rescheduleKernelAlarmsLocked();
4114 updateNextAlarmClockLocked();
4115 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004116 }
4117 break;
4118
4119 case APP_STANDBY_BUCKET_CHANGED:
4120 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004121 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
4122 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
4123 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
4124 rescheduleKernelAlarmsLocked();
4125 updateNextAlarmClockLocked();
4126 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004127 }
4128 break;
4129
Makoto Onuki4d298b52018-02-05 10:54:58 -08004130 case REMOVE_FOR_STOPPED:
4131 synchronized (mLock) {
4132 removeForStoppedLocked(msg.arg1);
4133 }
4134 break;
4135
Christopher Tate14a7bb02015-10-01 10:24:31 -07004136 default:
4137 // nope, just ignore it
4138 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004139 }
4140 }
4141 }
Kweku Adams61e03292017-10-19 14:27:12 -07004142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 class ClockReceiver extends BroadcastReceiver {
4144 public ClockReceiver() {
4145 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004146 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004147 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
Kweku Adams61e03292017-10-19 14:27:12 -07004149
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004150 @Override
4151 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07004152 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004153 // Since the kernel does not keep track of DST, we need to
4154 // reset the TZ information at the beginning of each day
4155 // based off of the current Zone gmt offset + userspace tracked
4156 // daylight savings information.
4157 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004158 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
4159 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07004160 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004161 }
4162 }
Kweku Adams61e03292017-10-19 14:27:12 -07004163
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004164 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004165 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09004166 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07004167
4168 // Schedule this event for the amount of time that it would take to get to
4169 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09004170 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07004171
David Christieebe51fc2013-07-26 13:23:29 -07004172 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004173 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004174 0, null, mTimeTickTrigger, "TIME_TICK", AlarmManager.FLAG_STANDALONE,
4175 workSource, null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08004176
4177 // Finally, remember when we set the tick alarm
4178 synchronized (mLock) {
4179 mLastTickSet = currentTime;
4180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004181 }
Christopher Tate385e4982013-07-23 18:22:29 -07004182
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004183 public void scheduleDateChangedEvent() {
4184 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004185 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07004186 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004187 calendar.set(Calendar.MINUTE, 0);
4188 calendar.set(Calendar.SECOND, 0);
4189 calendar.set(Calendar.MILLISECOND, 0);
4190 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07004191
4192 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07004193 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
4194 AlarmManager.FLAG_STANDALONE, workSource, null,
4195 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004196 }
4197 }
Kweku Adams61e03292017-10-19 14:27:12 -07004198
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07004199 class InteractiveStateReceiver extends BroadcastReceiver {
4200 public InteractiveStateReceiver() {
4201 IntentFilter filter = new IntentFilter();
4202 filter.addAction(Intent.ACTION_SCREEN_OFF);
4203 filter.addAction(Intent.ACTION_SCREEN_ON);
4204 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
4205 getContext().registerReceiver(this, filter);
4206 }
4207
4208 @Override
4209 public void onReceive(Context context, Intent intent) {
4210 synchronized (mLock) {
4211 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
4212 }
4213 }
4214 }
4215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 class UninstallReceiver extends BroadcastReceiver {
4217 public UninstallReceiver() {
4218 IntentFilter filter = new IntentFilter();
4219 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
4220 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004221 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004222 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08004223 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004224 // Register for events related to sdcard installation.
4225 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004226 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004227 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004228 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004229 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 }
Kweku Adams61e03292017-10-19 14:27:12 -07004231
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004232 @Override
4233 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004234 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004235 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004236 String pkgList[] = null;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004237 switch (intent.getAction()) {
4238 case Intent.ACTION_QUERY_PACKAGE_RESTART:
4239 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4240 for (String packageName : pkgList) {
4241 if (lookForPackageLocked(packageName)) {
4242 setResultCode(Activity.RESULT_OK);
4243 return;
Suprabh Shukla75edab12018-01-29 14:09:06 -08004244 }
4245 }
Dianne Hackborn409578f2010-03-10 17:23:43 -08004246 return;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004247 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
4248 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
4249 break;
4250 case Intent.ACTION_USER_STOPPED:
4251 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4252 if (userHandle >= 0) {
4253 removeUserLocked(userHandle);
4254 mAppWakeupHistory.removeForUser(userHandle);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004255 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004256 return;
4257 case Intent.ACTION_UID_REMOVED:
4258 if (uid >= 0) {
4259 mLastAllowWhileIdleDispatch.delete(uid);
4260 mUseAllowWhileIdleShortTime.delete(uid);
4261 }
4262 return;
4263 case Intent.ACTION_PACKAGE_REMOVED:
4264 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4265 // This package is being updated; don't kill its alarms.
4266 return;
4267 }
4268 // Intentional fall-through.
4269 case Intent.ACTION_PACKAGE_RESTARTED:
4270 final Uri data = intent.getData();
4271 if (data != null) {
4272 final String pkg = data.getSchemeSpecificPart();
4273 if (pkg != null) {
4274 pkgList = new String[]{pkg};
4275 }
4276 }
4277 break;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004278 }
4279 if (pkgList != null && (pkgList.length > 0)) {
4280 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004281 if (uid >= 0) {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004282 // package-removed and package-restarted case
4283 mAppWakeupHistory.removeForPackage(pkg, UserHandle.getUserId(uid));
Christopher Tate1d99c392017-12-07 16:54:04 -08004284 removeLocked(uid);
4285 } else {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004286 // external-applications-unavailable case
Christopher Tate1d99c392017-12-07 16:54:04 -08004287 removeLocked(pkg);
4288 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004289 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004290 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4291 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4292 if (uidStats.remove(pkg) != null) {
4293 if (uidStats.size() <= 0) {
4294 mBroadcastStats.removeAt(i);
4295 }
4296 }
4297 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004298 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004299 }
4300 }
4301 }
4302 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004303
4304 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004305 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004306 }
4307
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004308 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004309 if (disabled) {
4310 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004311 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004312 }
4313
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004314 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004315 }
4316
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004317 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004318 if (disabled) {
4319 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004320 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004321 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004322
4323 @Override public void onUidCachedChanged(int uid, boolean cached) {
4324 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004325 };
4326
Suprabh Shukla75edab12018-01-29 14:09:06 -08004327 /**
4328 * Tracking of app assignments to standby buckets
4329 */
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004330 private final class AppStandbyTracker extends
4331 UsageStatsManagerInternal.AppIdleStateChangeListener {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004332 @Override
4333 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004334 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004335 if (DEBUG_STANDBY) {
4336 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4337 bucket);
4338 }
4339 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004340 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4341 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004342 }
4343
4344 @Override
4345 public void onParoleStateChanged(boolean isParoleOn) {
4346 if (DEBUG_STANDBY) {
4347 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4348 }
4349 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4350 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4351 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4352 Boolean.valueOf(isParoleOn)).sendToTarget();
4353 }
4354 };
4355
Makoto Onuki2206af32017-11-21 16:25:35 -08004356 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004357 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004358 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004359 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004360 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004361 }
4362 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004363
4364 @Override
4365 public void unblockAlarmsForUid(int uid) {
4366 synchronized (mLock) {
4367 sendPendingBackgroundAlarmsLocked(uid, null);
4368 }
4369 }
4370
4371 @Override
4372 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4373 synchronized (mLock) {
4374 sendPendingBackgroundAlarmsLocked(uid, packageName);
4375 }
4376 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004377
4378 @Override
4379 public void onUidForeground(int uid, boolean foreground) {
4380 synchronized (mLock) {
4381 if (foreground) {
4382 mUseAllowWhileIdleShortTime.put(uid, true);
4383
4384 // Note we don't have to drain the pending while-idle alarms here, because
4385 // this event should coincide with unblockAlarmsForUid().
4386 }
4387 }
4388 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004389 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004391 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004392 String pkg = pi.getCreatorPackage();
4393 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004394 return getStatsLocked(uid, pkg);
4395 }
4396
4397 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004398 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4399 if (uidStats == null) {
4400 uidStats = new ArrayMap<String, BroadcastStats>();
4401 mBroadcastStats.put(uid, uidStats);
4402 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004403 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004404 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004405 bs = new BroadcastStats(uid, pkgName);
4406 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004407 }
4408 return bs;
4409 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004410
Christopher Tate21e9f192017-08-08 13:49:11 -07004411 /**
4412 * Canonical count of (operation.send() - onSendFinished()) and
4413 * listener send/complete/timeout invocations.
4414 * Guarded by the usual lock.
4415 */
4416 @GuardedBy("mLock")
4417 private int mSendCount = 0;
4418 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004419 private int mSendFinishCount = 0;
4420 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004421 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004422 @GuardedBy("mLock")
4423 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004424
Christopher Tate14a7bb02015-10-01 10:24:31 -07004425 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004426
Christopher Tate14a7bb02015-10-01 10:24:31 -07004427 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4428 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004429 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004430 return mInFlight.remove(i);
4431 }
4432 }
4433 mLog.w("No in-flight alarm for " + pi + " " + intent);
4434 return null;
4435 }
4436
4437 private InFlight removeLocked(IBinder listener) {
4438 for (int i = 0; i < mInFlight.size(); i++) {
4439 if (mInFlight.get(i).mListener == listener) {
4440 return mInFlight.remove(i);
4441 }
4442 }
4443 mLog.w("No in-flight alarm for listener " + listener);
4444 return null;
4445 }
4446
4447 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004448 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004449 BroadcastStats bs = inflight.mBroadcastStats;
4450 bs.nesting--;
4451 if (bs.nesting <= 0) {
4452 bs.nesting = 0;
4453 bs.aggregateTime += nowELAPSED - bs.startTime;
4454 }
4455 FilterStats fs = inflight.mFilterStats;
4456 fs.nesting--;
4457 if (fs.nesting <= 0) {
4458 fs.nesting = 0;
4459 fs.aggregateTime += nowELAPSED - fs.startTime;
4460 }
4461 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004462 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4463 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004464 }
4465 }
4466
4467 private void updateTrackingLocked(InFlight inflight) {
4468 if (inflight != null) {
4469 updateStatsLocked(inflight);
4470 }
4471 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004472 if (DEBUG_WAKELOCK) {
4473 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4474 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004475 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004476 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004477 mWakeLock.release();
4478 if (mInFlight.size() > 0) {
4479 mLog.w("Finished all dispatches with " + mInFlight.size()
4480 + " remaining inflights");
4481 for (int i=0; i<mInFlight.size(); i++) {
4482 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4483 }
4484 mInFlight.clear();
4485 }
4486 } else {
4487 // the next of our alarms is now in flight. reattribute the wakelock.
4488 if (mInFlight.size() > 0) {
4489 InFlight inFlight = mInFlight.get(0);
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004490 setWakelockWorkSource(inFlight.mWorkSource, inFlight.mCreatorUid, inFlight.mTag,
4491 false);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004492 } else {
4493 // should never happen
4494 mLog.w("Alarm wakelock still held but sent queue empty");
4495 mWakeLock.setWorkSource(null);
4496 }
4497 }
4498 }
4499
4500 /**
4501 * Callback that arrives when a direct-call alarm reports that delivery has finished
4502 */
4503 @Override
4504 public void alarmComplete(IBinder who) {
4505 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004506 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004507 + " pid=" + Binder.getCallingPid());
4508 return;
4509 }
4510
4511 final long ident = Binder.clearCallingIdentity();
4512 try {
4513 synchronized (mLock) {
4514 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4515 InFlight inflight = removeLocked(who);
4516 if (inflight != null) {
4517 if (DEBUG_LISTENER_CALLBACK) {
4518 Slog.i(TAG, "alarmComplete() from " + who);
4519 }
4520 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004521 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004522 } else {
4523 // Delivery timed out, and the timeout handling already took care of
4524 // updating our tracking here, so we needn't do anything further.
4525 if (DEBUG_LISTENER_CALLBACK) {
4526 Slog.i(TAG, "Late alarmComplete() from " + who);
4527 }
4528 }
4529 }
4530 } finally {
4531 Binder.restoreCallingIdentity(ident);
4532 }
4533 }
4534
4535 /**
4536 * Callback that arrives when a PendingIntent alarm has finished delivery
4537 */
4538 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004539 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4540 String resultData, Bundle resultExtras) {
4541 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004542 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004543 updateTrackingLocked(removeLocked(pi, intent));
4544 }
4545 }
4546
4547 /**
4548 * Timeout of a direct-call alarm delivery
4549 */
4550 public void alarmTimedOut(IBinder who) {
4551 synchronized (mLock) {
4552 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004553 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004554 // TODO: implement ANR policy for the target
4555 if (DEBUG_LISTENER_CALLBACK) {
4556 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004557 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004558 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004559 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004560 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004561 if (DEBUG_LISTENER_CALLBACK) {
4562 Slog.i(TAG, "Spurious timeout of listener " + who);
4563 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004564 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004565 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004566 }
4567 }
4568
4569 /**
4570 * Deliver an alarm and set up the post-delivery handling appropriately
4571 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004572 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004573 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004574 final long workSourceToken = ThreadLocalWorkSource.setUid(
4575 getAlarmAttributionUid(alarm));
4576 try {
4577 if (alarm.operation != null) {
4578 // PendingIntent alarm
4579 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004580
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004581 try {
4582 alarm.operation.send(getContext(), 0,
4583 mBackgroundIntent.putExtra(
4584 Intent.EXTRA_ALARM_COUNT, alarm.count),
4585 mDeliveryTracker, mHandler, null,
4586 allowWhileIdle ? mIdleOptions : null);
4587 } catch (PendingIntent.CanceledException e) {
4588 if (alarm.repeatInterval > 0) {
4589 // This IntentSender is no longer valid, but this
4590 // is a repeating alarm, so toss it
4591 removeImpl(alarm.operation, null);
4592 }
4593 // No actual delivery was possible, so the delivery tracker's
4594 // 'finished' callback won't be invoked. We also don't need
4595 // to do any wakelock or stats tracking, so we have nothing
4596 // left to do here but go on to the next thing.
4597 mSendFinishCount++;
4598 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004599 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004600 } else {
4601 // Direct listener callback alarm
4602 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004603
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004604 if (RECORD_ALARMS_IN_HISTORY) {
4605 if (alarm.listener == mTimeTickTrigger) {
4606 mTickHistory[mNextTickHistory++] = nowELAPSED;
4607 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4608 mNextTickHistory = 0;
4609 }
Christopher Tatec8b7f432018-09-28 16:23:10 -07004610 }
4611 }
Christopher Tatec8b7f432018-09-28 16:23:10 -07004612
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004613 try {
4614 if (DEBUG_LISTENER_CALLBACK) {
4615 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4616 + " listener=" + alarm.listener.asBinder());
4617 }
4618 alarm.listener.doAlarm(this);
4619 mHandler.sendMessageDelayed(
4620 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4621 alarm.listener.asBinder()),
4622 mConstants.LISTENER_TIMEOUT);
4623 } catch (Exception e) {
4624 if (DEBUG_LISTENER_CALLBACK) {
4625 Slog.i(TAG, "Alarm undeliverable to listener "
4626 + alarm.listener.asBinder(), e);
4627 }
4628 // As in the PendingIntent.CanceledException case, delivery of the
4629 // alarm was not possible, so we have no wakelock or timeout or
4630 // stats management to do. It threw before we posted the delayed
4631 // timeout message, so we're done here.
4632 mListenerFinishCount++;
4633 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004634 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004635 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004636 } finally {
4637 ThreadLocalWorkSource.restore(workSourceToken);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004638 }
4639
4640 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004641 if (DEBUG_WAKELOCK) {
4642 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4643 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004644 if (mBroadcastRefCount == 0) {
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004645 setWakelockWorkSource(alarm.workSource, alarm.creatorUid, alarm.statsTag, true);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004646 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004647 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004648 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004649 final InFlight inflight = new InFlight(AlarmManagerService.this, alarm, nowELAPSED);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004650 mInFlight.add(inflight);
4651 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004652 if (allowWhileIdle) {
4653 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004654 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004655 if ((mAppStateTracker == null)
4656 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004657 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4658 } else {
4659 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4660 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004661 if (RECORD_DEVICE_IDLE_ALARMS) {
4662 IdleDispatchEntry ent = new IdleDispatchEntry();
4663 ent.uid = alarm.uid;
4664 ent.pkg = alarm.packageName;
4665 ent.tag = alarm.statsTag;
4666 ent.op = "DELIVER";
4667 ent.elapsedRealtime = nowELAPSED;
4668 mAllowWhileIdleDispatches.add(ent);
4669 }
4670 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004671 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004672 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4673 UserHandle.getUserId(alarm.creatorUid));
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004674 mAppWakeupHistory.recordAlarmForPackage(alarm.sourcePackage,
4675 UserHandle.getUserId(alarm.creatorUid), nowELAPSED);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004676 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004677
4678 final BroadcastStats bs = inflight.mBroadcastStats;
4679 bs.count++;
4680 if (bs.nesting == 0) {
4681 bs.nesting = 1;
4682 bs.startTime = nowELAPSED;
4683 } else {
4684 bs.nesting++;
4685 }
4686 final FilterStats fs = inflight.mFilterStats;
4687 fs.count++;
4688 if (fs.nesting == 0) {
4689 fs.nesting = 1;
4690 fs.startTime = nowELAPSED;
4691 } else {
4692 fs.nesting++;
4693 }
4694 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4695 || alarm.type == RTC_WAKEUP) {
4696 bs.numWakeup++;
4697 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004698 ActivityManager.noteWakeupAlarm(
4699 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4700 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004701 }
4702 }
4703 }
mswest463f4c99d2018-02-01 10:13:10 -08004704
4705 private class ShellCmd extends ShellCommand {
4706
4707 IAlarmManager getBinderService() {
4708 return IAlarmManager.Stub.asInterface(mService);
4709 }
4710
4711 @Override
4712 public int onCommand(String cmd) {
4713 if (cmd == null) {
4714 return handleDefaultCommands(cmd);
4715 }
4716
4717 final PrintWriter pw = getOutPrintWriter();
4718 try {
4719 switch (cmd) {
4720 case "set-time":
4721 final long millis = Long.parseLong(getNextArgRequired());
4722 return (getBinderService().setTime(millis)) ? 0 : -1;
4723 case "set-timezone":
4724 final String tz = getNextArgRequired();
4725 getBinderService().setTimeZone(tz);
4726 return 0;
4727 default:
4728 return handleDefaultCommands(cmd);
4729 }
4730 } catch (Exception e) {
4731 pw.println(e);
4732 }
4733 return -1;
4734 }
4735
4736 @Override
4737 public void onHelp() {
4738 PrintWriter pw = getOutPrintWriter();
4739 pw.println("Alarm manager service (alarm) commands:");
4740 pw.println(" help");
4741 pw.println(" Print this help text.");
4742 pw.println(" set-time TIME");
4743 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4744 pw.println(" since the Epoch.");
4745 pw.println(" set-timezone TZ");
4746 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4747 }
4748 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004749}