blob: 10b532700d1b648a26d1f6608328b8c8ee6d0e6b [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<>();
Christopher Tate2f558d22019-01-17 16:58:31 -0800200 private final ArrayList<AlarmManagerInternal.InFlightListener> mInFlightListeners =
201 new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700202 AlarmHandler mHandler;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800203 AppWakeupHistory mAppWakeupHistory;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800204 ClockReceiver mClockReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700205 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Christopher Tatec8b7f432018-09-28 16:23:10 -0700206 Intent mTimeTickIntent;
207 IAlarmListener mTimeTickTrigger;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800208 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700209 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700210 boolean mInteractive = true;
211 long mNonInteractiveStartTime;
212 long mNonInteractiveTime;
213 long mLastAlarmDeliveryTime;
214 long mStartCurrentDelayTime;
215 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700216 long mLastTimeChangeClockTime;
217 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700218 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800219
Christopher Tatebb9cce52017-04-18 14:19:43 -0700220 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
221
222 /**
223 * This permission must be defined by the canonical System UI package,
224 * with protection level "signature".
225 */
226 private static final String SYSTEM_UI_SELF_PERMISSION =
227 "android.permission.systemui.IDENTITY";
228
229 /**
230 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
231 */
232 int mSystemUiUid;
233
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700234 /**
235 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700236 * used to determine the earliest we can dispatch the next such alarm. Times are in the
237 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700238 */
239 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
240
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800241 /**
242 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
243 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
244 */
245 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
246
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700247 final static class IdleDispatchEntry {
248 int uid;
249 String pkg;
250 String tag;
251 String op;
252 long elapsedRealtime;
253 long argRealtime;
254 }
255 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
256
Suprabh Shukla75edab12018-01-29 14:09:06 -0800257 interface Stats {
258 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800259 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800260 }
261
262 private final StatLogger mStatLogger = new StatLogger(new String[] {
263 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800264 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800265 });
266
Dianne Hackborna750a632015-06-16 17:18:23 -0700267 /**
268 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
269 */
270 Bundle mIdleOptions;
271
Jose Lima235510e2014-08-13 12:50:01 -0700272 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
273 new SparseArray<>();
274 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
275 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200276 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
277 new SparseBooleanArray();
278 private boolean mNextAlarmClockMayChange;
279
280 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700281 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
282 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200283
Makoto Onukie4918212018-02-06 11:30:15 -0800284 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800285 private boolean mAppStandbyParole;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800286
287 /**
288 * A rolling window history of previous times when an alarm was sent to a package.
289 */
290 private static class AppWakeupHistory {
291 private ArrayMap<Pair<String, Integer>, LongArrayQueue> mPackageHistory =
292 new ArrayMap<>();
293 private long mWindowSize;
294
295 AppWakeupHistory(long windowSize) {
296 mWindowSize = windowSize;
297 }
298
299 void recordAlarmForPackage(String packageName, int userId, long nowElapsed) {
300 final Pair<String, Integer> packageUser = Pair.create(packageName, userId);
301 LongArrayQueue history = mPackageHistory.get(packageUser);
302 if (history == null) {
303 history = new LongArrayQueue();
304 mPackageHistory.put(packageUser, history);
305 }
306 if (history.size() == 0 || history.peekLast() < nowElapsed) {
307 history.addLast(nowElapsed);
308 }
309 snapToWindow(history);
310 }
311
312 void removeForUser(int userId) {
313 for (int i = mPackageHistory.size() - 1; i >= 0; i--) {
314 final Pair<String, Integer> packageUserKey = mPackageHistory.keyAt(i);
315 if (packageUserKey.second == userId) {
316 mPackageHistory.removeAt(i);
317 }
318 }
319 }
320
321 void removeForPackage(String packageName, int userId) {
322 final Pair<String, Integer> packageUser = Pair.create(packageName, userId);
323 mPackageHistory.remove(packageUser);
324 }
325
326 private void snapToWindow(LongArrayQueue history) {
327 while (history.peekFirst() + mWindowSize < history.peekLast()) {
328 history.removeFirst();
329 }
330 }
331
332 int getTotalWakeupsInWindow(String packageName, int userId) {
333 final LongArrayQueue history = mPackageHistory.get(Pair.create(packageName, userId));
334 return (history == null) ? 0 : history.size();
335 }
336
337 long getLastWakeupForPackage(String packageName, int userId, int positionFromEnd) {
338 final LongArrayQueue history = mPackageHistory.get(Pair.create(packageName, userId));
339 if (history == null) {
340 return 0;
341 }
342 final int i = history.size() - positionFromEnd;
343 return (i < 0) ? 0 : history.get(i);
344 }
345
346 void dump(PrintWriter pw, String prefix, long nowElapsed) {
347 dump(new IndentingPrintWriter(pw, " ").setIndent(prefix), nowElapsed);
348 }
349
350 void dump(IndentingPrintWriter pw, long nowElapsed) {
351 pw.println("App Alarm history:");
352 pw.increaseIndent();
353 for (int i = 0; i < mPackageHistory.size(); i++) {
354 final Pair<String, Integer> packageUser = mPackageHistory.keyAt(i);
355 final LongArrayQueue timestamps = mPackageHistory.valueAt(i);
356 pw.print(packageUser.first);
357 pw.print(", u");
358 pw.print(packageUser.second);
359 pw.print(": ");
360 // limit dumping to a max of 100 values
361 final int lastIdx = Math.max(0, timestamps.size() - 100);
362 for (int j = timestamps.size() - 1; j >= lastIdx; j--) {
363 TimeUtils.formatDuration(timestamps.get(j), nowElapsed, pw);
364 pw.print(", ");
365 }
366 pw.println();
367 }
368 pw.decreaseIndent();
369 }
370 }
Makoto Onuki2206af32017-11-21 16:25:35 -0800371
Dianne Hackborna750a632015-06-16 17:18:23 -0700372 /**
373 * All times are in milliseconds. These constants are kept synchronized with the system
374 * global Settings. Any access to this class or its fields should be done while
375 * holding the AlarmManagerService.mLock lock.
376 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700377 @VisibleForTesting
378 final class Constants extends ContentObserver {
Dianne Hackborna750a632015-06-16 17:18:23 -0700379 // Key names stored in the settings value.
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700380 @VisibleForTesting
381 static final String KEY_MIN_FUTURITY = "min_futurity";
382 @VisibleForTesting
383 static final String KEY_MIN_INTERVAL = "min_interval";
384 @VisibleForTesting
385 static final String KEY_MAX_INTERVAL = "max_interval";
386 @VisibleForTesting
387 static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
388 @VisibleForTesting
389 static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
390 @VisibleForTesting
391 static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
Dianne Hackborna750a632015-06-16 17:18:23 -0700392 = "allow_while_idle_whitelist_duration";
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700393 @VisibleForTesting
394 static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800395 @VisibleForTesting
396 static final String KEY_APP_STANDBY_QUOTAS_ENABLED = "app_standby_quotas_enabled";
397 private static final String KEY_APP_STANDBY_WINDOW = "app_standby_window";
398 @VisibleForTesting
399 final String[] KEYS_APP_STANDBY_QUOTAS = {
400 "standby_active_quota",
401 "standby_working_quota",
402 "standby_frequent_quota",
403 "standby_rare_quota",
404 "standby_never_quota",
405 };
Dianne Hackborna750a632015-06-16 17:18:23 -0700406
Suprabh Shukla75edab12018-01-29 14:09:06 -0800407 // Keys for specifying throttling delay based on app standby bucketing
408 private final String[] KEYS_APP_STANDBY_DELAY = {
409 "standby_active_delay",
410 "standby_working_delay",
411 "standby_frequent_delay",
412 "standby_rare_delay",
413 "standby_never_delay",
414 };
415
Dianne Hackborna750a632015-06-16 17:18:23 -0700416 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
417 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800418 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700419 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700420 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700421 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700422 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800423 private static final boolean DEFAULT_APP_STANDBY_QUOTAS_ENABLED = true;
424 private static final long DEFAULT_APP_STANDBY_WINDOW = 60 * 60 * 1000; // 1 hr
425 /**
426 * Max number of times an app can receive alarms in {@link #APP_STANDBY_WINDOW}
427 */
428 private final int[] DEFAULT_APP_STANDBY_QUOTAS = {
429 720, // Active
430 10, // Working
431 2, // Frequent
432 1, // Rare
433 0 // Never
434 };
Suprabh Shukla75edab12018-01-29 14:09:06 -0800435 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
436 0, // Active
437 6 * 60_000, // Working
438 30 * 60_000, // Frequent
439 2 * 60 * 60_000, // Rare
440 10 * 24 * 60 * 60_000 // Never
441 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700442
Dianne Hackborna750a632015-06-16 17:18:23 -0700443 // Minimum futurity of a new alarm
444 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
445
446 // Minimum alarm recurrence interval
447 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
448
Christopher Tate22e919d2018-02-16 16:16:50 -0800449 // Maximum alarm recurrence interval
450 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
451
Dianne Hackborna750a632015-06-16 17:18:23 -0700452 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
453 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
454
455 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
456 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
457
458 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
459 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
460 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
461
Christopher Tate14a7bb02015-10-01 10:24:31 -0700462 // Direct alarm listener callback timeout
463 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800464 public boolean APP_STANDBY_QUOTAS_ENABLED = DEFAULT_APP_STANDBY_QUOTAS_ENABLED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700465
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800466 public long APP_STANDBY_WINDOW = DEFAULT_APP_STANDBY_WINDOW;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800467 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800468 public int[] APP_STANDBY_QUOTAS = new int[DEFAULT_APP_STANDBY_QUOTAS.length];
Suprabh Shukla75edab12018-01-29 14:09:06 -0800469
Dianne Hackborna750a632015-06-16 17:18:23 -0700470 private ContentResolver mResolver;
471 private final KeyValueListParser mParser = new KeyValueListParser(',');
472 private long mLastAllowWhileIdleWhitelistDuration = -1;
473
474 public Constants(Handler handler) {
475 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700476 updateAllowWhileIdleWhitelistDurationLocked();
477 }
478
479 public void start(ContentResolver resolver) {
480 mResolver = resolver;
481 mResolver.registerContentObserver(Settings.Global.getUriFor(
482 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
483 updateConstants();
484 }
485
Dianne Hackborna750a632015-06-16 17:18:23 -0700486 public void updateAllowWhileIdleWhitelistDurationLocked() {
487 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
488 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
489 BroadcastOptions opts = BroadcastOptions.makeBasic();
490 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
491 mIdleOptions = opts.toBundle();
492 }
493 }
494
495 @Override
496 public void onChange(boolean selfChange, Uri uri) {
497 updateConstants();
498 }
499
500 private void updateConstants() {
501 synchronized (mLock) {
502 try {
503 mParser.setString(Settings.Global.getString(mResolver,
504 Settings.Global.ALARM_MANAGER_CONSTANTS));
505 } catch (IllegalArgumentException e) {
506 // Failed to parse the settings string, log this and move on
507 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800508 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700509 }
510
511 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
512 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800513 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700514 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
515 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
516 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
517 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
518 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
519 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
520 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700521 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
522 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700523 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
524 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
525 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
526 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800527 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800528 Math.max(APP_STANDBY_MIN_DELAYS[i - 1], DEFAULT_APP_STANDBY_DELAYS[i]));
529 }
530
531 APP_STANDBY_QUOTAS_ENABLED = mParser.getBoolean(KEY_APP_STANDBY_QUOTAS_ENABLED,
532 DEFAULT_APP_STANDBY_QUOTAS_ENABLED);
533
534 APP_STANDBY_WINDOW = mParser.getLong(KEY_APP_STANDBY_WINDOW,
535 DEFAULT_APP_STANDBY_WINDOW);
536 if (APP_STANDBY_WINDOW > DEFAULT_APP_STANDBY_WINDOW) {
537 Slog.w(TAG, "Cannot exceed the app_standby_window size of "
538 + DEFAULT_APP_STANDBY_WINDOW);
539 APP_STANDBY_WINDOW = DEFAULT_APP_STANDBY_WINDOW;
540 } else if (APP_STANDBY_WINDOW < DEFAULT_APP_STANDBY_WINDOW) {
541 // Not recommended outside of testing.
542 Slog.w(TAG, "Using a non-default app_standby_window of " + APP_STANDBY_WINDOW);
543 }
544
545 APP_STANDBY_QUOTAS[ACTIVE_INDEX] = mParser.getInt(
546 KEYS_APP_STANDBY_QUOTAS[ACTIVE_INDEX],
547 DEFAULT_APP_STANDBY_QUOTAS[ACTIVE_INDEX]);
548 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_QUOTAS.length; i++) {
549 APP_STANDBY_QUOTAS[i] = mParser.getInt(KEYS_APP_STANDBY_QUOTAS[i],
550 Math.min(APP_STANDBY_QUOTAS[i - 1], DEFAULT_APP_STANDBY_QUOTAS[i]));
Suprabh Shukla75edab12018-01-29 14:09:06 -0800551 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700552 updateAllowWhileIdleWhitelistDurationLocked();
553 }
554 }
555
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800556 void dump(PrintWriter pw, String prefix) {
557 dump(new IndentingPrintWriter(pw, " ").setIndent(prefix));
558 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700559
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800560 void dump(IndentingPrintWriter pw) {
561 pw.println("Settings:");
562
563 pw.increaseIndent();
564
565 pw.print(KEY_MIN_FUTURITY); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700566 TimeUtils.formatDuration(MIN_FUTURITY, pw);
567 pw.println();
568
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800569 pw.print(KEY_MIN_INTERVAL); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700570 TimeUtils.formatDuration(MIN_INTERVAL, pw);
571 pw.println();
572
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800573 pw.print(KEY_MAX_INTERVAL); pw.print("=");
Christopher Tate22e919d2018-02-16 16:16:50 -0800574 TimeUtils.formatDuration(MAX_INTERVAL, pw);
575 pw.println();
576
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800577 pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
Christopher Tate14a7bb02015-10-01 10:24:31 -0700578 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
579 pw.println();
580
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800581 pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700582 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
583 pw.println();
584
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800585 pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700586 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
587 pw.println();
588
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800589 pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700590 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
591 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800592
593 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800594 pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
Suprabh Shukla75edab12018-01-29 14:09:06 -0800595 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
596 pw.println();
597 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800598
599 pw.print(KEY_APP_STANDBY_QUOTAS_ENABLED); pw.print("=");
600 pw.println(APP_STANDBY_QUOTAS_ENABLED);
601
602 pw.print(KEY_APP_STANDBY_WINDOW); pw.print("=");
603 TimeUtils.formatDuration(APP_STANDBY_WINDOW, pw);
604 pw.println();
605
606 for (int i = 0; i < KEYS_APP_STANDBY_QUOTAS.length; i++) {
607 pw.print(KEYS_APP_STANDBY_QUOTAS[i]); pw.print("=");
608 pw.println(APP_STANDBY_QUOTAS[i]);
609 }
610
611 pw.decreaseIndent();
Dianne Hackborna750a632015-06-16 17:18:23 -0700612 }
Kweku Adams61e03292017-10-19 14:27:12 -0700613
614 void dumpProto(ProtoOutputStream proto, long fieldId) {
615 final long token = proto.start(fieldId);
616
617 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
618 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800619 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700620 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
621 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
622 ALLOW_WHILE_IDLE_SHORT_TIME);
623 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
624 ALLOW_WHILE_IDLE_LONG_TIME);
625 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
626 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
627
628 proto.end(token);
629 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700630 }
631
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700632 Constants mConstants;
Dianne Hackborna750a632015-06-16 17:18:23 -0700633
Christopher Tate1590f1e2014-10-02 17:27:57 -0700634 // Alarm delivery ordering bookkeeping
635 static final int PRIO_TICK = 0;
636 static final int PRIO_WAKEUP = 1;
637 static final int PRIO_NORMAL = 2;
638
Dianne Hackborna750a632015-06-16 17:18:23 -0700639 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700640 int seq;
641 int priority;
642
643 PriorityClass() {
644 seq = mCurrentSeq - 1;
645 priority = PRIO_NORMAL;
646 }
647 }
648
Dianne Hackborna750a632015-06-16 17:18:23 -0700649 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700650 int mCurrentSeq = 0;
651
Dianne Hackborna750a632015-06-16 17:18:23 -0700652 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700653 public long when;
654 public int uid;
655 public String action;
656
657 public WakeupEvent(long theTime, int theUid, String theAction) {
658 when = theTime;
659 uid = theUid;
660 action = theAction;
661 }
662 }
663
Adam Lesinski182f73f2013-12-05 16:48:06 -0800664 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
665 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700666
Adrian Roosc42a1e12014-07-07 23:35:53 +0200667 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700668 long start; // These endpoints are always in ELAPSED
669 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700670 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700671
672 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
673
674 Batch() {
675 start = 0;
676 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700677 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700678 }
679
680 Batch(Alarm seed) {
681 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800682 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700683 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700684 alarms.add(seed);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700685 if (seed.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700686 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800687 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700688 }
689
690 int size() {
691 return alarms.size();
692 }
693
694 Alarm get(int index) {
695 return alarms.get(index);
696 }
697
698 boolean canHold(long whenElapsed, long maxWhen) {
699 return (end >= whenElapsed) && (start <= maxWhen);
700 }
701
702 boolean add(Alarm alarm) {
703 boolean newStart = false;
704 // narrows the batch if necessary; presumes that canHold(alarm) is true
705 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
706 if (index < 0) {
707 index = 0 - index - 1;
708 }
709 alarms.add(index, alarm);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700710 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700711 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800712 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700713 if (DEBUG_BATCH) {
714 Slog.v(TAG, "Adding " + alarm + " to " + this);
715 }
716 if (alarm.whenElapsed > start) {
717 start = alarm.whenElapsed;
718 newStart = true;
719 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700720 if (alarm.maxWhenElapsed < end) {
721 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700722 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700723 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700724
725 if (DEBUG_BATCH) {
726 Slog.v(TAG, " => now " + this);
727 }
728 return newStart;
729 }
730
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800731 boolean remove(Alarm alarm) {
732 return remove(a -> (a == alarm));
733 }
734
Christopher Tate1d99c392017-12-07 16:54:04 -0800735 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736 boolean didRemove = false;
737 long newStart = 0; // recalculate endpoints as we go
738 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700739 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700740 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700741 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800742 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700743 alarms.remove(i);
744 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200745 if (alarm.alarmClock != null) {
746 mNextAlarmClockMayChange = true;
747 }
Christopher Tatec8b7f432018-09-28 16:23:10 -0700748 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700749 mLastTickRemoved = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800750 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700751 } else {
752 if (alarm.whenElapsed > newStart) {
753 newStart = alarm.whenElapsed;
754 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700755 if (alarm.maxWhenElapsed < newEnd) {
756 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700757 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700758 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700759 i++;
760 }
761 }
762 if (didRemove) {
763 // commit the new batch bounds
764 start = newStart;
765 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700766 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700767 }
768 return didRemove;
769 }
770
Christopher Tatee0a22b32013-07-11 14:43:13 -0700771 boolean hasPackage(final String packageName) {
772 final int N = alarms.size();
773 for (int i = 0; i < N; i++) {
774 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700775 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700776 return true;
777 }
778 }
779 return false;
780 }
781
782 boolean hasWakeups() {
783 final int N = alarms.size();
784 for (int i = 0; i < N; i++) {
785 Alarm a = alarms.get(i);
786 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
787 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
788 return true;
789 }
790 }
791 return false;
792 }
793
794 @Override
795 public String toString() {
796 StringBuilder b = new StringBuilder(40);
797 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
798 b.append(" num="); b.append(size());
799 b.append(" start="); b.append(start);
800 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700801 if (flags != 0) {
802 b.append(" flgs=0x");
803 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700804 }
805 b.append('}');
806 return b.toString();
807 }
Kweku Adams61e03292017-10-19 14:27:12 -0700808
809 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
810 long nowRTC) {
811 final long token = proto.start(fieldId);
812
813 proto.write(BatchProto.START_REALTIME, start);
814 proto.write(BatchProto.END_REALTIME, end);
815 proto.write(BatchProto.FLAGS, flags);
816 for (Alarm a : alarms) {
817 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
818 }
819
820 proto.end(token);
821 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700822 }
823
824 static class BatchTimeOrder implements Comparator<Batch> {
825 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800826 long when1 = b1.start;
827 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800828 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700829 return 1;
830 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800831 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700832 return -1;
833 }
834 return 0;
835 }
836 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800837
838 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
839 @Override
840 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700841 // priority class trumps everything. TICK < WAKEUP < NORMAL
842 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
843 return -1;
844 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
845 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800846 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700847
848 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800849 if (lhs.whenElapsed < rhs.whenElapsed) {
850 return -1;
851 } else if (lhs.whenElapsed > rhs.whenElapsed) {
852 return 1;
853 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700854
855 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800856 return 0;
857 }
858 };
859
Christopher Tate1590f1e2014-10-02 17:27:57 -0700860 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
861 final int N = alarms.size();
862 for (int i = 0; i < N; i++) {
863 Alarm a = alarms.get(i);
864
865 final int alarmPrio;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700866 if (a.listener == mTimeTickTrigger) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700867 alarmPrio = PRIO_TICK;
868 } else if (a.wakeup) {
869 alarmPrio = PRIO_WAKEUP;
870 } else {
871 alarmPrio = PRIO_NORMAL;
872 }
873
874 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800875 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700876 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700877 if (packagePrio == null) {
878 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700879 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700880 }
881 a.priorityClass = packagePrio;
882
883 if (packagePrio.seq != mCurrentSeq) {
884 // first alarm we've seen in the current delivery generation from this package
885 packagePrio.priority = alarmPrio;
886 packagePrio.seq = mCurrentSeq;
887 } else {
888 // Multiple alarms from this package being delivered in this generation;
889 // bump the package's delivery class if it's warranted.
890 // TICK < WAKEUP < NORMAL
891 if (alarmPrio < packagePrio.priority) {
892 packagePrio.priority = alarmPrio;
893 }
894 }
895 }
896 }
897
Christopher Tatee0a22b32013-07-11 14:43:13 -0700898 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800899 static final long MIN_FUZZABLE_INTERVAL = 10000;
900 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700901 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
902
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700903 // 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 -0700904 // to run during this time are placed in mPendingWhileIdleAlarms
905 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700906 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700907 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700908
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700909 @VisibleForTesting
910 AlarmManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800911 super(context);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700912 mInjector = injector;
Jeff Brownb880d882014-02-10 19:47:07 -0800913 }
914
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700915 AlarmManagerService(Context context) {
916 this(context, new Injector(context));
917 }
918
919 private long convertToElapsed(long when, int type) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700920 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
921 if (isRtc) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700922 when -= mInjector.getCurrentTimeMillis() - mInjector.getElapsedRealtime();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700923 }
924 return when;
925 }
926
927 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
928 // calculate the end of our nominal delivery window for the alarm.
929 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
930 // Current heuristic: batchable window is 75% of either the recurrence interval
931 // [for a periodic alarm] or of the time from now to the desired delivery time,
932 // with a minimum delay/interval of 10 seconds, under which we will simply not
933 // defer the alarm.
934 long futurity = (interval == 0)
935 ? (triggerAtTime - now)
936 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700937 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700938 futurity = 0;
939 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800940 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700941 }
942
943 // returns true if the batch was added at the head
944 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
945 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
946 if (index < 0) {
947 index = 0 - index - 1;
948 }
949 list.add(index, newBatch);
950 return (index == 0);
951 }
952
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800953 private void insertAndBatchAlarmLocked(Alarm alarm) {
954 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
955 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
956
957 if (whichBatch < 0) {
958 addBatchLocked(mAlarmBatches, new Batch(alarm));
959 } else {
960 final Batch batch = mAlarmBatches.get(whichBatch);
961 if (batch.add(alarm)) {
962 // The start time of this batch advanced, so batch ordering may
963 // have just been broken. Move it to where it now belongs.
964 mAlarmBatches.remove(whichBatch);
965 addBatchLocked(mAlarmBatches, batch);
966 }
967 }
968 }
969
Christopher Tate385e4982013-07-23 18:22:29 -0700970 // Return the index of the matching batch, or -1 if none found.
971 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700972 final int N = mAlarmBatches.size();
973 for (int i = 0; i < N; i++) {
974 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700975 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700976 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700977 }
978 }
Christopher Tate385e4982013-07-23 18:22:29 -0700979 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700980 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800981 /** @return total count of the alarms in a set of alarm batches. */
982 static int getAlarmCount(ArrayList<Batch> batches) {
983 int ret = 0;
984
985 final int size = batches.size();
986 for (int i = 0; i < size; i++) {
987 ret += batches.get(i).size();
988 }
989 return ret;
990 }
991
992 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
993 if (alarms.size() == 0) {
994 return false;
995 }
996 final int batchSize = alarms.size();
997 for (int j = 0; j < batchSize; j++) {
Christopher Tatec8b7f432018-09-28 16:23:10 -0700998 if (alarms.get(j).listener == mTimeTickTrigger) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800999 return true;
1000 }
1001 }
1002 return false;
1003 }
1004
1005 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
1006 final int numBatches = batches.size();
1007 for (int i = 0; i < numBatches; i++) {
1008 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
1009 return true;
1010 }
1011 }
1012 return false;
1013 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001014
1015 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
1016 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001017 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001018 rebatchAllAlarmsLocked(true);
1019 }
1020 }
1021
1022 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001023 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001024 final int oldCount =
1025 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
1026 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
1027 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
1028
Christopher Tate4cb338d2013-07-26 13:11:31 -07001029 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
1030 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001031 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001032 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate4cb338d2013-07-26 13:11:31 -07001033 final int oldBatches = oldSet.size();
1034 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
1035 Batch batch = oldSet.get(batchNum);
1036 final int N = batch.size();
1037 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001038 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001039 }
1040 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001041 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
1042 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
1043 + " to " + mPendingIdleUntil);
1044 if (mPendingIdleUntil == null) {
1045 // Somehow we lost this... we need to restore all of the pending alarms.
1046 restorePendingWhileIdleAlarmsLocked();
1047 }
1048 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08001049 final int newCount =
1050 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
1051 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
1052 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
1053
1054 if (oldCount != newCount) {
1055 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
1056 }
1057 if (oldHasTick != newHasTick) {
1058 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
1059 }
1060
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001061 rescheduleKernelAlarmsLocked();
1062 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -08001063 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001064 }
1065
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001066 /**
1067 * Re-orders the alarm batches based on newly evaluated send times based on the current
1068 * app-standby buckets
1069 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
1070 * null indicates all
1071 * @return True if there was any reordering done to the current list.
1072 */
1073 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
1074 final long start = mStatLogger.getTime();
1075 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
1076
1077 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
1078 final Batch batch = mAlarmBatches.get(batchIndex);
1079 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
1080 final Alarm alarm = batch.get(alarmIndex);
1081 final Pair<String, Integer> packageUser =
1082 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
1083 if (targetPackages != null && !targetPackages.contains(packageUser)) {
1084 continue;
1085 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001086 if (adjustDeliveryTimeBasedOnBucketLocked(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001087 batch.remove(alarm);
1088 rescheduledAlarms.add(alarm);
1089 }
1090 }
1091 if (batch.size() == 0) {
1092 mAlarmBatches.remove(batchIndex);
1093 }
1094 }
1095 for (int i = 0; i < rescheduledAlarms.size(); i++) {
1096 final Alarm a = rescheduledAlarms.get(i);
1097 insertAndBatchAlarmLocked(a);
1098 }
1099
1100 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
1101 return rescheduledAlarms.size() > 0;
1102 }
1103
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001104 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
1105 a.when = a.origWhen;
1106 long whenElapsed = convertToElapsed(a.when, a.type);
1107 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001108 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001109 // Exact
1110 maxElapsed = whenElapsed;
1111 } else {
1112 // Not exact. Preserve any explicit window, otherwise recalculate
1113 // the window based on the alarm's new futurity. Note that this
1114 // reflects a policy of preferring timely to deferred delivery.
1115 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -08001116 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001117 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
1118 }
1119 a.whenElapsed = whenElapsed;
1120 a.maxWhenElapsed = maxElapsed;
1121 setImplLocked(a, true, doValidate);
1122 }
1123
Christopher Tate22e919d2018-02-16 16:16:50 -08001124 static long clampPositive(long val) {
1125 return (val >= 0) ? val : Long.MAX_VALUE;
1126 }
1127
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001128 /**
1129 * Sends alarms that were blocked due to user applied background restrictions - either because
1130 * the user lifted those or the uid came to foreground.
1131 *
1132 * @param uid uid to filter on
1133 * @param packageName package to filter on, or null for all packages in uid
1134 */
1135 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
1136 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
1137 if (alarmsForUid == null || alarmsForUid.size() == 0) {
1138 return;
1139 }
1140 final ArrayList<Alarm> alarmsToDeliver;
1141 if (packageName != null) {
1142 if (DEBUG_BG_LIMIT) {
1143 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
1144 }
1145 alarmsToDeliver = new ArrayList<>();
1146 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
1147 final Alarm a = alarmsForUid.get(i);
1148 if (a.matches(packageName)) {
1149 alarmsToDeliver.add(alarmsForUid.remove(i));
1150 }
1151 }
1152 if (alarmsForUid.size() == 0) {
1153 mPendingBackgroundAlarms.remove(uid);
1154 }
1155 } else {
1156 if (DEBUG_BG_LIMIT) {
1157 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
1158 }
1159 alarmsToDeliver = alarmsForUid;
1160 mPendingBackgroundAlarms.remove(uid);
1161 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001162 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001163 }
1164
Makoto Onuki2206af32017-11-21 16:25:35 -08001165 /**
1166 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
1167 * restricted.
1168 *
1169 * This is only called when the global "force all apps-standby" flag changes or when the
1170 * power save whitelist changes, so it's okay to be slow.
1171 */
1172 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001173 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001174
1175 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1176 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1177
1178 if (alarmsToDeliver.size() > 0) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001179 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Makoto Onuki2206af32017-11-21 16:25:35 -08001180 }
1181 }
1182
1183 @VisibleForTesting
1184 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1185 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1186 Predicate<Alarm> isBackgroundRestricted) {
1187
1188 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1189 final int uid = pendingAlarms.keyAt(uidIndex);
1190 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1191
1192 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1193 final Alarm alarm = alarmsForUid.get(alarmIndex);
1194
1195 if (isBackgroundRestricted.test(alarm)) {
1196 continue;
1197 }
1198
1199 unrestrictedAlarms.add(alarm);
1200 alarmsForUid.remove(alarmIndex);
1201 }
1202
1203 if (alarmsForUid.size() == 0) {
1204 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001205 }
1206 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001207 }
1208
1209 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1210 final int N = alarms.size();
1211 boolean hasWakeup = false;
1212 for (int i = 0; i < N; i++) {
1213 final Alarm alarm = alarms.get(i);
1214 if (alarm.wakeup) {
1215 hasWakeup = true;
1216 }
1217 alarm.count = 1;
1218 // Recurring alarms may have passed several alarm intervals while the
1219 // alarm was kept pending. Send the appropriate trigger count.
1220 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001221 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001222 // Also schedule its next recurrence
1223 final long delta = alarm.count * alarm.repeatInterval;
1224 final long nextElapsed = alarm.whenElapsed + delta;
1225 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1226 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1227 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1228 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1229 // Kernel alarms will be rescheduled as needed in setImplLocked
1230 }
1231 }
1232 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1233 // No need to wakeup for non wakeup alarms
1234 if (mPendingNonWakeupAlarms.size() == 0) {
1235 mStartCurrentDelayTime = nowELAPSED;
1236 mNextNonWakeupDeliveryTime = nowELAPSED
1237 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1238 }
1239 mPendingNonWakeupAlarms.addAll(alarms);
1240 mNumDelayedAlarms += alarms.size();
1241 } else {
1242 if (DEBUG_BG_LIMIT) {
1243 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1244 }
1245 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1246 if (mPendingNonWakeupAlarms.size() > 0) {
1247 alarms.addAll(mPendingNonWakeupAlarms);
1248 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1249 mTotalDelayTime += thisDelayTime;
1250 if (mMaxDelayTime < thisDelayTime) {
1251 mMaxDelayTime = thisDelayTime;
1252 }
1253 mPendingNonWakeupAlarms.clear();
1254 }
1255 calculateDeliveryPriorities(alarms);
1256 Collections.sort(alarms, mAlarmDispatchComparator);
1257 deliverAlarmsLocked(alarms, nowELAPSED);
1258 }
1259 }
1260
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001261 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001262 if (RECORD_DEVICE_IDLE_ALARMS) {
1263 IdleDispatchEntry ent = new IdleDispatchEntry();
1264 ent.uid = 0;
1265 ent.pkg = "FINISH IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001266 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001267 mAllowWhileIdleDispatches.add(ent);
1268 }
1269
Dianne Hackborn35d54032015-04-23 10:30:43 -07001270 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001271 if (mPendingWhileIdleAlarms.size() > 0) {
1272 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1273 mPendingWhileIdleAlarms = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001274 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001275 for (int i=alarms.size() - 1; i >= 0; i--) {
1276 Alarm a = alarms.get(i);
1277 reAddAlarmLocked(a, nowElapsed, false);
1278 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001279 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001280
1281 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001282 rescheduleKernelAlarmsLocked();
1283 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001284
Christopher Tatee0a22b32013-07-11 14:43:13 -07001285 }
1286
Christopher Tate14a7bb02015-10-01 10:24:31 -07001287 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001288 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001289 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001290 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001291 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001292 final int mUid;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001293 final int mCreatorUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001294 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001295 final BroadcastStats mBroadcastStats;
1296 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001297 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001298
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001299 InFlight(AlarmManagerService service, Alarm alarm, long nowELAPSED) {
1300 mPendingIntent = alarm.operation;
Christopher Tateeabba732017-08-17 17:12:52 -07001301 mWhenElapsed = nowELAPSED;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001302 mListener = alarm.listener != null ? alarm.listener.asBinder() : null;
1303 mWorkSource = alarm.workSource;
1304 mUid = alarm.uid;
1305 mCreatorUid = alarm.creatorUid;
1306 mTag = alarm.statsTag;
1307 mBroadcastStats = (alarm.operation != null)
1308 ? service.getStatsLocked(alarm.operation)
1309 : service.getStatsLocked(alarm.uid, alarm.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001310 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001311 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001312 fs = new FilterStats(mBroadcastStats, mTag);
1313 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001314 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001315 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001316 mFilterStats = fs;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001317 mAlarmType = alarm.type;
Dianne Hackborn81038902012-11-26 17:04:09 -08001318 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001319
Christopher Tate2f558d22019-01-17 16:58:31 -08001320 boolean isBroadcast() {
1321 return mPendingIntent != null && mPendingIntent.isBroadcast();
1322 }
1323
Makoto Onuki33955e12017-03-01 18:11:00 -08001324 @Override
1325 public String toString() {
1326 return "InFlight{"
1327 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001328 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001329 + ", workSource=" + mWorkSource
1330 + ", uid=" + mUid
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001331 + ", creatorUid=" + mCreatorUid
Makoto Onuki33955e12017-03-01 18:11:00 -08001332 + ", tag=" + mTag
1333 + ", broadcastStats=" + mBroadcastStats
1334 + ", filterStats=" + mFilterStats
1335 + ", alarmType=" + mAlarmType
1336 + "}";
1337 }
Kweku Adams61e03292017-10-19 14:27:12 -07001338
1339 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1340 final long token = proto.start(fieldId);
1341
1342 proto.write(InFlightProto.UID, mUid);
1343 proto.write(InFlightProto.TAG, mTag);
1344 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1345 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1346 if (mPendingIntent != null) {
1347 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1348 }
1349 if (mBroadcastStats != null) {
1350 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1351 }
1352 if (mFilterStats != null) {
1353 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1354 }
1355 if (mWorkSource != null) {
1356 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1357 }
1358
1359 proto.end(token);
1360 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001361 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001362
Christopher Tate2f558d22019-01-17 16:58:31 -08001363 private void notifyBroadcastAlarmPendingLocked(int uid) {
1364 final int numListeners = mInFlightListeners.size();
1365 for (int i = 0; i < numListeners; i++) {
1366 mInFlightListeners.get(i).broadcastAlarmPending(uid);
1367 }
1368 }
1369
1370 private void notifyBroadcastAlarmCompleteLocked(int uid) {
1371 final int numListeners = mInFlightListeners.size();
1372 for (int i = 0; i < numListeners; i++) {
1373 mInFlightListeners.get(i).broadcastAlarmComplete(uid);
1374 }
1375 }
1376
Adam Lesinski182f73f2013-12-05 16:48:06 -08001377 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001378 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001379 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001380
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001381 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001383 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 int numWakeup;
1385 long startTime;
1386 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001387
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001388 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001389 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001390 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001391 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001392
1393 @Override
1394 public String toString() {
1395 return "FilterStats{"
1396 + "tag=" + mTag
1397 + ", lastTime=" + lastTime
1398 + ", aggregateTime=" + aggregateTime
1399 + ", count=" + count
1400 + ", numWakeup=" + numWakeup
1401 + ", startTime=" + startTime
1402 + ", nesting=" + nesting
1403 + "}";
1404 }
Kweku Adams61e03292017-10-19 14:27:12 -07001405
1406 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1407 final long token = proto.start(fieldId);
1408
1409 proto.write(FilterStatsProto.TAG, mTag);
1410 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1411 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1412 proto.write(FilterStatsProto.COUNT, count);
1413 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1414 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1415 proto.write(FilterStatsProto.NESTING, nesting);
1416
1417 proto.end(token);
1418 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001419 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001420
Adam Lesinski182f73f2013-12-05 16:48:06 -08001421 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001422 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001423 final String mPackageName;
1424
1425 long aggregateTime;
1426 int count;
1427 int numWakeup;
1428 long startTime;
1429 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001430 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001431
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001432 BroadcastStats(int uid, String packageName) {
1433 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001434 mPackageName = packageName;
1435 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001436
1437 @Override
1438 public String toString() {
1439 return "BroadcastStats{"
1440 + "uid=" + mUid
1441 + ", packageName=" + mPackageName
1442 + ", aggregateTime=" + aggregateTime
1443 + ", count=" + count
1444 + ", numWakeup=" + numWakeup
1445 + ", startTime=" + startTime
1446 + ", nesting=" + nesting
1447 + "}";
1448 }
Kweku Adams61e03292017-10-19 14:27:12 -07001449
1450 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1451 final long token = proto.start(fieldId);
1452
1453 proto.write(BroadcastStatsProto.UID, mUid);
1454 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1455 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1456 proto.write(BroadcastStatsProto.COUNT, count);
1457 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1458 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1459 proto.write(BroadcastStatsProto.NESTING, nesting);
1460
1461 proto.end(token);
1462 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001464
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001465 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1466 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001467
1468 int mNumDelayedAlarms = 0;
1469 long mTotalDelayTime = 0;
1470 long mMaxDelayTime = 0;
1471
Adam Lesinski182f73f2013-12-05 16:48:06 -08001472 @Override
1473 public void onStart() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001474 mInjector.init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001475
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001476 synchronized (mLock) {
Suprabh Shukla12bd0162018-11-12 18:00:18 -08001477 mHandler = new AlarmHandler();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001478 mConstants = new Constants(mHandler);
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001479 mAppWakeupHistory = new AppWakeupHistory(Constants.DEFAULT_APP_STANDBY_WINDOW);
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001480
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001481 mNextWakeup = mNextNonWakeup = 0;
1482
1483 // We have to set current TimeZone info to kernel
1484 // because kernel doesn't keep this after reboot
1485 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
1486
Christopher Tate3d65d4d2018-12-11 14:55:19 -08001487 // Ensure that we're booting with a halfway sensible current time. Use the
1488 // most recent of Build.TIME, the root file system's timestamp, and the
1489 // value of the ro.build.date.utc system property (which is in seconds).
1490 final long systemBuildTime = Long.max(
1491 1000L * SystemProperties.getLong("ro.build.date.utc", -1L),
1492 Long.max(Environment.getRootDirectory().lastModified(), Build.TIME));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001493 if (mInjector.getCurrentTimeMillis() < systemBuildTime) {
1494 Slog.i(TAG, "Current time only " + mInjector.getCurrentTimeMillis()
Christopher Tate247571462017-04-10 11:45:05 -07001495 + ", advancing to build time " + systemBuildTime);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001496 mInjector.setKernelTime(systemBuildTime);
Christopher Tate247571462017-04-10 11:45:05 -07001497 }
Christopher Tate247571462017-04-10 11:45:05 -07001498
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001499 // Determine SysUI's uid
1500 mSystemUiUid = mInjector.getSystemUiUid();
1501 if (mSystemUiUid <= 0) {
1502 Slog.wtf(TAG, "SysUI package not found!");
1503 }
1504 mWakeLock = mInjector.getAlarmWakeLock();
1505
Christopher Tatec8b7f432018-09-28 16:23:10 -07001506 mTimeTickIntent = new Intent(Intent.ACTION_TIME_TICK).addFlags(
1507 Intent.FLAG_RECEIVER_REGISTERED_ONLY
1508 | Intent.FLAG_RECEIVER_FOREGROUND
1509 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1510
1511 mTimeTickTrigger = new IAlarmListener.Stub() {
1512 @Override
1513 public void doAlarm(final IAlarmCompleteListener callback) throws RemoteException {
1514 if (DEBUG_BATCH) {
1515 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1516 }
1517
1518 // Via handler because dispatch invokes this within its lock. OnAlarmListener
1519 // takes care of this automatically, but we're using the direct internal
1520 // interface here rather than that client-side wrapper infrastructure.
1521 mHandler.post(() -> {
1522 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL);
1523
1524 try {
1525 callback.alarmComplete(this);
1526 } catch (RemoteException e) { /* local method call */ }
1527 });
1528
1529 synchronized (mLock) {
1530 mLastTickReceived = mInjector.getCurrentTimeMillis();
1531 }
1532 mClockReceiver.scheduleTimeTickEvent();
1533 }
1534 };
1535
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001536 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
1537 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1538 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1539 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
1540 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
1541
1542 mClockReceiver = mInjector.getClockReceiver(this);
1543 new InteractiveStateReceiver();
1544 new UninstallReceiver();
1545
1546 if (mInjector.isAlarmDriverPresent()) {
1547 AlarmThread waitThread = new AlarmThread();
1548 waitThread.start();
Christopher Tatebb9cce52017-04-18 14:19:43 -07001549 } else {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001550 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
Christopher Tatebb9cce52017-04-18 14:19:43 -07001551 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001552
1553 try {
1554 ActivityManager.getService().registerUidObserver(new UidObserver(),
1555 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1556 | ActivityManager.UID_OBSERVER_ACTIVE,
1557 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1558 } catch (RemoteException e) {
1559 // ignored; both services live in system_server
1560 }
Christopher Tatebb9cce52017-04-18 14:19:43 -07001561 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001562 publishLocalService(AlarmManagerInternal.class, new LocalService());
Adam Lesinski182f73f2013-12-05 16:48:06 -08001563 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001565
1566 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001567 public void onBootPhase(int phase) {
1568 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001569 synchronized (mLock) {
1570 mConstants.start(getContext().getContentResolver());
1571 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1572 mLocalDeviceIdleController =
1573 LocalServices.getService(DeviceIdleController.LocalService.class);
1574 mUsageStatsManagerInternal =
1575 LocalServices.getService(UsageStatsManagerInternal.class);
1576 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001577
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001578 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1579 mAppStateTracker.addListener(mForceAppStandbyListener);
1580
1581 mClockReceiver.scheduleTimeTickEvent();
1582 mClockReceiver.scheduleDateChangedEvent();
1583 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001584 }
1585 }
1586
1587 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001588 protected void finalize() throws Throwable {
1589 try {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001590 mInjector.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001591 } finally {
1592 super.finalize();
1593 }
1594 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001595
mswest463f4c99d2018-02-01 10:13:10 -08001596 boolean setTimeImpl(long millis) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001597 if (!mInjector.isAlarmDriverPresent()) {
mswest463f4c99d2018-02-01 10:13:10 -08001598 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1599 return false;
1600 }
1601
1602 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001603 final long currentTimeMillis = mInjector.getCurrentTimeMillis();
1604 mInjector.setKernelTime(millis);
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001605 final TimeZone timeZone = TimeZone.getDefault();
1606 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1607 final int newTzOffset = timeZone.getOffset(millis);
1608 if (currentTzOffset != newTzOffset) {
1609 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001610 mInjector.setKernelTimezone(-(newTzOffset / 60000));
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001611 }
1612 // The native implementation of setKernelTime can return -1 even when the kernel
1613 // time was set correctly, so assume setting kernel time was successful and always
1614 // return true.
1615 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001616 }
1617 }
1618
Adam Lesinski182f73f2013-12-05 16:48:06 -08001619 void setTimeZoneImpl(String tz) {
1620 if (TextUtils.isEmpty(tz)) {
1621 return;
David Christieebe51fc2013-07-26 13:23:29 -07001622 }
1623
Adam Lesinski182f73f2013-12-05 16:48:06 -08001624 TimeZone zone = TimeZone.getTimeZone(tz);
1625 // Prevent reentrant calls from stepping on each other when writing
1626 // the time zone property
1627 boolean timeZoneWasChanged = false;
1628 synchronized (this) {
1629 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1630 if (current == null || !current.equals(zone.getID())) {
1631 if (localLOGV) {
1632 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1633 }
1634 timeZoneWasChanged = true;
1635 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1636 }
1637
1638 // Update the kernel timezone information
1639 // Kernel tracks time offsets as 'minutes west of GMT'
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001640 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
1641 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001642 }
1643
1644 TimeZone.setDefault(null);
1645
1646 if (timeZoneWasChanged) {
Christopher Tatea4618b02018-10-11 16:22:55 -07001647 // Don't wait for broadcasts to update our midnight alarm
1648 mClockReceiver.scheduleDateChangedEvent();
1649
1650 // And now let everyone else know
Adam Lesinski182f73f2013-12-05 16:48:06 -08001651 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001652 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001653 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001654 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001655 intent.putExtra("time-zone", zone.getID());
1656 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001659
Christopher Tatec8b7f432018-09-28 16:23:10 -07001660 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001661 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001662 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001663 }
1664 }
1665
1666 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001667 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1668 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1669 int callingUid, String callingPackage) {
1670 // must be *either* PendingIntent or AlarmReceiver, but not both
1671 if ((operation == null && directReceiver == null)
1672 || (operation != null && directReceiver != null)) {
1673 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1674 // NB: previous releases failed silently here, so we are continuing to do the same
1675 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001676 return;
1677 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001678
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001679 // Sanity check the window length. This will catch people mistakenly
1680 // trying to pass an end-of-window timestamp rather than a duration.
1681 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1682 Slog.w(TAG, "Window length " + windowLength
1683 + "ms suspiciously long; limiting to 1 hour");
1684 windowLength = AlarmManager.INTERVAL_HOUR;
1685 }
1686
Christopher Tate498c6cb2014-11-17 16:09:27 -08001687 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001688 // seconds when the API expects milliseconds, or apps trying shenanigans
1689 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001690 final long minInterval = mConstants.MIN_INTERVAL;
1691 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001692 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001693 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001694 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001695 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001696 } else if (interval > mConstants.MAX_INTERVAL) {
1697 Slog.w(TAG, "Suspiciously long interval " + interval
1698 + " millis; clamping");
1699 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001700 }
1701
Christopher Tatee0a22b32013-07-11 14:43:13 -07001702 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1703 throw new IllegalArgumentException("Invalid alarm type " + type);
1704 }
1705
Christopher Tate5f221e82013-07-30 17:13:15 -07001706 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001707 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001708 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001709 + " pid=" + what);
1710 triggerAtTime = 0;
1711 }
1712
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001713 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001714 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1715 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001716 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001717 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1718
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001719 final long maxElapsed;
1720 if (windowLength == AlarmManager.WINDOW_EXACT) {
1721 maxElapsed = triggerElapsed;
1722 } else if (windowLength < 0) {
1723 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001724 // Fix this window in place, so that as time approaches we don't collapse it.
1725 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001726 } else {
1727 maxElapsed = triggerElapsed + windowLength;
1728 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001731 if (DEBUG_BATCH) {
1732 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001733 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001734 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001735 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001736 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001737 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001738 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1739 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001740 }
1741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742
Christopher Tate3e04b472013-10-21 17:51:31 -07001743 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001744 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1745 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1746 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001747 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001748 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1749 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001750 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001751 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001752 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1753 + " -- package not allowed to start");
1754 return;
1755 }
1756 } catch (RemoteException e) {
1757 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001758 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001759 setImplLocked(a, false, doValidate);
1760 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001761
Christopher Tatef2159712018-03-27 16:04:14 -07001762 /**
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001763 * Returns the maximum alarms that an app in the specified bucket can receive in a rolling time
1764 * window given by {@link Constants#APP_STANDBY_WINDOW}
1765 */
1766 @VisibleForTesting
1767 int getQuotaForBucketLocked(int bucket) {
1768 final int index;
1769 if (bucket <= UsageStatsManager.STANDBY_BUCKET_ACTIVE) {
1770 index = ACTIVE_INDEX;
1771 } else if (bucket <= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1772 index = WORKING_INDEX;
1773 } else if (bucket <= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1774 index = FREQUENT_INDEX;
1775 } else if (bucket < UsageStatsManager.STANDBY_BUCKET_NEVER) {
1776 index = RARE_INDEX;
1777 } else {
1778 index = NEVER_INDEX;
1779 }
1780 return mConstants.APP_STANDBY_QUOTAS[index];
1781 }
1782
1783 /**
Christopher Tatef2159712018-03-27 16:04:14 -07001784 * Return the minimum time that should elapse before an app in the specified bucket
1785 * can receive alarms again
1786 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001787 @VisibleForTesting
1788 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001789 // UsageStats bucket values are treated as floors of their behavioral range.
1790 // In other words, a bucket value between WORKING and ACTIVE is treated as
1791 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1792 // values.
1793 final int index;
1794
1795 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1796 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1797 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1798 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1799 else index = ACTIVE_INDEX;
1800
1801 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001802 }
1803
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001804 /**
1805 * Adjusts the alarm delivery time based on the current app standby bucket.
1806 * @param alarm The alarm to adjust
1807 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001808 */
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001809 private boolean adjustDeliveryTimeBasedOnBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001810 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001811 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001812 }
1813 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001814 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001815 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001816 alarm.whenElapsed = alarm.expectedWhenElapsed;
1817 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1818 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001819 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001820 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001821 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001822 final long oldWhenElapsed = alarm.whenElapsed;
1823 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1824
Suprabh Shukla75edab12018-01-29 14:09:06 -08001825 final String sourcePackage = alarm.sourcePackage;
1826 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1827 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001828 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001829
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001830 if (mConstants.APP_STANDBY_QUOTAS_ENABLED) {
1831 // Quota deferring implementation:
1832 final int wakeupsInWindow = mAppWakeupHistory.getTotalWakeupsInWindow(sourcePackage,
1833 sourceUserId);
1834 final int quotaForBucket = getQuotaForBucketLocked(standbyBucket);
1835 boolean deferred = false;
1836 if (wakeupsInWindow >= quotaForBucket) {
1837 final long minElapsed;
1838 if (quotaForBucket <= 0) {
1839 // Just keep deferring for a day till the quota changes
1840 minElapsed = mInjector.getElapsedRealtime() + MILLIS_IN_DAY;
1841 } else {
1842 // Suppose the quota for window was q, and the qth last delivery time for this
1843 // package was t(q) then the next delivery must be after t(q) + <window_size>
1844 final long t = mAppWakeupHistory.getLastWakeupForPackage(sourcePackage,
1845 sourceUserId, quotaForBucket);
1846 minElapsed = t + 1 + mConstants.APP_STANDBY_WINDOW;
1847 }
1848 if (alarm.expectedWhenElapsed < minElapsed) {
1849 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1850 deferred = true;
1851 }
1852 }
1853 if (!deferred) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001854 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001855 alarm.whenElapsed = alarm.expectedWhenElapsed;
1856 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001857 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001858 } else {
1859 // Minimum delay deferring implementation:
1860 final long lastElapsed = mAppWakeupHistory.getLastWakeupForPackage(sourcePackage,
1861 sourceUserId, 1);
1862 if (lastElapsed > 0) {
1863 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
1864 if (alarm.expectedWhenElapsed < minElapsed) {
1865 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1866 } else {
1867 // app is now eligible to run alarms at the originally requested window.
1868 // Restore original requirements in case they were changed earlier.
1869 alarm.whenElapsed = alarm.expectedWhenElapsed;
1870 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1871 }
1872 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001873 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001874 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001875 }
1876
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001877 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1878 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001879 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001880 // The caller has given the time they want this to happen at, however we need
1881 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001882 // bring us out of idle at an earlier time.
1883 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001884 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001885 }
1886 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001887 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001888 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001889 if (fuzz > 0) {
1890 if (mRandom == null) {
1891 mRandom = new Random();
1892 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001893 final int delta = mRandom.nextInt(fuzz);
1894 a.whenElapsed -= delta;
1895 if (false) {
1896 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1897 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1898 Slog.d(TAG, "Applied fuzz: " + fuzz);
1899 Slog.d(TAG, "Final delta: " + delta);
1900 Slog.d(TAG, "Final when: " + a.whenElapsed);
1901 }
1902 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001903 }
1904
1905 } else if (mPendingIdleUntil != null) {
1906 // We currently have an idle until alarm scheduled; if the new alarm has
1907 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001908 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1909 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1910 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001911 == 0) {
1912 mPendingWhileIdleAlarms.add(a);
1913 return;
1914 }
1915 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001916 if (RECORD_DEVICE_IDLE_ALARMS) {
1917 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1918 IdleDispatchEntry ent = new IdleDispatchEntry();
1919 ent.uid = a.uid;
1920 ent.pkg = a.operation.getCreatorPackage();
1921 ent.tag = a.operation.getTag("");
1922 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001923 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001924 ent.argRealtime = a.whenElapsed;
1925 mAllowWhileIdleDispatches.add(ent);
1926 }
1927 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001928 adjustDeliveryTimeBasedOnBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001929 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001930
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001931 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001932 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001933 }
1934
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001935 boolean needRebatch = false;
1936
1937 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001938 if (RECORD_DEVICE_IDLE_ALARMS) {
1939 if (mPendingIdleUntil == null) {
1940 IdleDispatchEntry ent = new IdleDispatchEntry();
1941 ent.uid = 0;
1942 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001943 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001944 mAllowWhileIdleDispatches.add(ent);
1945 }
1946 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001947 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1948 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1949 + " to " + a);
1950 }
1951
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001952 mPendingIdleUntil = a;
1953 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001954 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1955 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1956 mNextWakeFromIdle = a;
1957 // If this wake from idle is earlier than whatever was previously scheduled,
1958 // and we are currently idling, then we need to rebatch alarms in case the idle
1959 // until time needs to be updated.
1960 if (mPendingIdleUntil != null) {
1961 needRebatch = true;
1962 }
1963 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001964 }
1965
1966 if (!rebatching) {
1967 if (DEBUG_VALIDATE) {
1968 if (doValidate && !validateConsistencyLocked()) {
1969 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1970 + " when(hex)=" + Long.toHexString(a.when)
1971 + " whenElapsed=" + a.whenElapsed
1972 + " maxWhenElapsed=" + a.maxWhenElapsed
1973 + " interval=" + a.repeatInterval + " op=" + a.operation
1974 + " flags=0x" + Integer.toHexString(a.flags));
1975 rebatchAllAlarmsLocked(false);
1976 needRebatch = false;
1977 }
1978 }
1979
1980 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001981 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001982 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001983
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001984 rescheduleKernelAlarmsLocked();
1985 updateNextAlarmClockLocked();
1986 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001987 }
1988
Christopher Tate1d99c392017-12-07 16:54:04 -08001989 /**
1990 * System-process internal API
1991 */
1992 private final class LocalService implements AlarmManagerInternal {
1993 @Override
1994 public void removeAlarmsForUid(int uid) {
1995 synchronized (mLock) {
1996 removeLocked(uid);
1997 }
1998 }
Christopher Tate2f558d22019-01-17 16:58:31 -08001999
2000 @Override
2001 public void registerInFlightListener(InFlightListener callback) {
2002 synchronized (mLock) {
2003 mInFlightListeners.add(callback);
2004 }
2005 }
Christopher Tate1d99c392017-12-07 16:54:04 -08002006 }
2007
2008 /**
2009 * Public-facing binder interface
2010 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08002011 private final IBinder mService = new IAlarmManager.Stub() {
2012 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07002013 public void set(String callingPackage,
2014 int type, long triggerAtTime, long windowLength, long interval, int flags,
2015 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
2016 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002017 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07002018
2019 // make sure the caller is not lying about which package should be blamed for
2020 // wakelock time spent in alarm delivery
2021 mAppOps.checkPackage(callingUid, callingPackage);
2022
2023 // Repeating alarms must use PendingIntent, not direct listener
2024 if (interval != 0) {
2025 if (directReceiver != null) {
2026 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
2027 }
2028 }
2029
Adam Lesinski182f73f2013-12-05 16:48:06 -08002030 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002031 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08002032 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002033 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07002034 }
2035
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002036 // No incoming callers can request either WAKE_FROM_IDLE or
2037 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
2038 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
2039 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
2040
2041 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
2042 // manager when to come out of idle mode, which is only for DeviceIdleController.
2043 if (callingUid != Process.SYSTEM_UID) {
2044 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
2045 }
2046
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002047 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002048 if (windowLength == AlarmManager.WINDOW_EXACT) {
2049 flags |= AlarmManager.FLAG_STANDALONE;
2050 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002051
2052 // If this alarm is for an alarm clock, then it must be standalone and we will
2053 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002054 if (alarmClock != null) {
2055 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002056
2057 // If the caller is a core system component or on the user's whitelist, and not calling
2058 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
2059 // This means we will allow these alarms to go off as normal even while idle, with no
2060 // timing restrictions.
2061 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08002062 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08002063 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002064 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002065 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
2066 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002067 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002068
Christopher Tate14a7bb02015-10-01 10:24:31 -07002069 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
2070 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002071 }
Christopher Tate89779822012-08-31 14:40:03 -07002072
Adam Lesinski182f73f2013-12-05 16:48:06 -08002073 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08002074 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002075 getContext().enforceCallingOrSelfPermission(
2076 "android.permission.SET_TIME",
2077 "setTime");
2078
mswest463f4c99d2018-02-01 10:13:10 -08002079 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002080 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002081
2082 @Override
2083 public void setTimeZone(String tz) {
2084 getContext().enforceCallingOrSelfPermission(
2085 "android.permission.SET_TIME_ZONE",
2086 "setTimeZone");
2087
2088 final long oldId = Binder.clearCallingIdentity();
2089 try {
2090 setTimeZoneImpl(tz);
2091 } finally {
2092 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002093 }
2094 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07002095
Adam Lesinski182f73f2013-12-05 16:48:06 -08002096 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07002097 public void remove(PendingIntent operation, IAlarmListener listener) {
2098 if (operation == null && listener == null) {
2099 Slog.w(TAG, "remove() with no intent or listener");
2100 return;
2101 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002102
Christopher Tate14a7bb02015-10-01 10:24:31 -07002103 synchronized (mLock) {
2104 removeLocked(operation, listener);
2105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002106 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07002107
Adam Lesinski182f73f2013-12-05 16:48:06 -08002108 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002109 public long getNextWakeFromIdleTime() {
2110 return getNextWakeFromIdleTimeImpl();
2111 }
2112
2113 @Override
Jose Lima235510e2014-08-13 12:50:01 -07002114 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002115 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2116 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
2117 "getNextAlarmClock", null);
2118
2119 return getNextAlarmClockImpl(userId);
2120 }
2121
2122 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07002123 public long currentNetworkTimeMillis() {
2124 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
2125 if (time.hasCache()) {
2126 return time.currentTimeMillis();
2127 } else {
2128 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
2129 }
2130 }
2131
2132 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08002133 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002134 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07002135
2136 if (args.length > 0 && "--proto".equals(args[0])) {
2137 dumpProto(fd);
2138 } else {
2139 dumpImpl(pw);
2140 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002141 }
mswest463f4c99d2018-02-01 10:13:10 -08002142
2143 @Override
2144 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2145 FileDescriptor err, String[] args, ShellCallback callback,
2146 ResultReceiver resultReceiver) {
2147 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
2148 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002149 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07002150
Adam Lesinski182f73f2013-12-05 16:48:06 -08002151 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002152 synchronized (mLock) {
2153 pw.println("Current Alarm Manager state:");
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08002154 mConstants.dump(pw, " ");
Dianne Hackborna750a632015-06-16 17:18:23 -07002155 pw.println();
2156
Makoto Onukie4918212018-02-06 11:30:15 -08002157 if (mAppStateTracker != null) {
2158 mAppStateTracker.dump(pw, " ");
2159 pw.println();
2160 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002161
Suprabh Shukla75edab12018-01-29 14:09:06 -08002162 pw.println(" App Standby Parole: " + mAppStandbyParole);
2163 pw.println();
2164
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002165 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002166 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07002167 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08002168 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002169
Dianne Hackborna750a632015-06-16 17:18:23 -07002170 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002171 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08002172 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002173 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002174 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002175 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08002176 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08002177 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
2178 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08002179 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
2180 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002181
Christopher Tatec8b7f432018-09-28 16:23:10 -07002182 if (RECORD_ALARMS_IN_HISTORY) {
2183 pw.println();
2184 pw.println(" Recent TIME_TICK history:");
2185 int i = mNextTickHistory;
2186 do {
2187 i--;
2188 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
2189 final long time = mTickHistory[i];
2190 pw.print(" ");
2191 pw.println((time > 0)
2192 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
2193 : "-");
2194 } while (i != mNextTickHistory);
2195 pw.println();
2196 }
2197
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002198 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
2199 if (ssm != null) {
2200 pw.println();
2201 pw.print(" RuntimeStarted=");
2202 pw.print(sdf.format(
2203 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
2204 if (ssm.isRuntimeRestarted()) {
2205 pw.print(" (Runtime restarted)");
2206 }
2207 pw.println();
2208 pw.print(" Runtime uptime (elapsed): ");
2209 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
2210 pw.println();
2211 pw.print(" Runtime uptime (uptime): ");
2212 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
2213 pw.println();
2214 }
2215
Dianne Hackbornc3527222015-05-13 14:03:20 -07002216 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002217 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002218 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002219 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
2220 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002221 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08002222 pw.print(" Max wakeup delay: ");
2223 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
2224 pw.println();
2225 pw.print(" Time since last dispatch: ");
2226 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
2227 pw.println();
2228 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002229 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08002230 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002231
2232 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
2233 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07002234 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002235 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002236 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002237 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002238 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
2239 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08002240 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
2241 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002242 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002243 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002244 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07002245
2246 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002247 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002248 pw.println();
2249 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002250 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002251 pw.println();
2252
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002253 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002254 pw.print(" = "); pw.println(mLastWakeup);
2255 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2256 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002257 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002258
John Spurlock604a5ee2015-06-01 12:27:22 -04002259 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002260 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002261 final TreeSet<Integer> users = new TreeSet<>();
2262 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2263 users.add(mNextAlarmClockForUser.keyAt(i));
2264 }
2265 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2266 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2267 }
2268 for (int user : users) {
2269 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2270 final long time = next != null ? next.getTriggerTime() : 0;
2271 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002272 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002273 pw.print(" pendingSend:"); pw.print(pendingSend);
2274 pw.print(" time:"); pw.print(time);
2275 if (time > 0) {
2276 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2277 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2278 }
2279 pw.println();
2280 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002281 if (mAlarmBatches.size() > 0) {
2282 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002283 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002284 pw.println(mAlarmBatches.size());
2285 for (Batch b : mAlarmBatches) {
2286 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002287 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002288 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002289 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002290 pw.println();
2291 pw.println(" Pending user blocked background alarms: ");
2292 boolean blocked = false;
2293 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2294 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2295 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2296 blocked = true;
2297 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2298 }
2299 }
2300 if (!blocked) {
2301 pw.println(" none");
2302 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002303
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08002304 mAppWakeupHistory.dump(pw, " ", nowELAPSED);
Suprabh Shukla75edab12018-01-29 14:09:06 -08002305
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002306 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002307 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002308 pw.println(" Idle mode state:");
2309 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002310 if (mPendingIdleUntil != null) {
2311 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002312 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002313 } else {
2314 pw.println("null");
2315 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002316 pw.println(" Pending alarms:");
2317 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002318 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002319 if (mNextWakeFromIdle != null) {
2320 pw.println();
2321 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002322 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002323 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002324
2325 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002326 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002327 if (mPendingNonWakeupAlarms.size() > 0) {
2328 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002329 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002330 } else {
2331 pw.println("(none)");
2332 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002333 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002334 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2335 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002336 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002337 pw.print(", max non-interactive time: ");
2338 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2339 pw.println();
2340
2341 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002342 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002343 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2344 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2345 pw.print(" Listener send count: "); pw.println(mListenerCount);
2346 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002347 pw.println();
2348
Christopher Tate7f2a0352015-12-08 10:24:33 -08002349 if (mInFlight.size() > 0) {
2350 pw.println("Outstanding deliveries:");
2351 for (int i = 0; i < mInFlight.size(); i++) {
2352 pw.print(" #"); pw.print(i); pw.print(": ");
2353 pw.println(mInFlight.get(i));
2354 }
2355 pw.println();
2356 }
2357
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002358 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002359 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002360 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002361 pw.print(" UID ");
2362 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2363 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002364 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002365 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2366 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2367
2368 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2369 pw.print(" Next allowed:");
2370 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2371 pw.print(" (");
2372 TimeUtils.formatDuration(minInterval, 0, pw);
2373 pw.print(")");
2374
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002375 pw.println();
2376 }
2377 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002378
2379 pw.print(" mUseAllowWhileIdleShortTime: [");
2380 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2381 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2382 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2383 pw.print(" ");
2384 }
2385 }
2386 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002387 pw.println();
2388
Dianne Hackborn81038902012-11-26 17:04:09 -08002389 if (mLog.dump(pw, " Recent problems", " ")) {
2390 pw.println();
2391 }
2392
2393 final FilterStats[] topFilters = new FilterStats[10];
2394 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2395 @Override
2396 public int compare(FilterStats lhs, FilterStats rhs) {
2397 if (lhs.aggregateTime < rhs.aggregateTime) {
2398 return 1;
2399 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2400 return -1;
2401 }
2402 return 0;
2403 }
2404 };
2405 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002406 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002407 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2408 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2409 for (int ip=0; ip<uidStats.size(); ip++) {
2410 BroadcastStats bs = uidStats.valueAt(ip);
2411 for (int is=0; is<bs.filterStats.size(); is++) {
2412 FilterStats fs = bs.filterStats.valueAt(is);
2413 int pos = len > 0
2414 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2415 if (pos < 0) {
2416 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002417 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002418 if (pos < topFilters.length) {
2419 int copylen = topFilters.length - pos - 1;
2420 if (copylen > 0) {
2421 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2422 }
2423 topFilters[pos] = fs;
2424 if (len < topFilters.length) {
2425 len++;
2426 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002427 }
2428 }
2429 }
2430 }
2431 if (len > 0) {
2432 pw.println(" Top Alarms:");
2433 for (int i=0; i<len; i++) {
2434 FilterStats fs = topFilters[i];
2435 pw.print(" ");
2436 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2437 TimeUtils.formatDuration(fs.aggregateTime, pw);
2438 pw.print(" running, "); pw.print(fs.numWakeup);
2439 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002440 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2441 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002442 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002443 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002444 pw.println();
2445 }
2446 }
2447
2448 pw.println(" ");
2449 pw.println(" Alarm Stats:");
2450 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002451 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2452 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2453 for (int ip=0; ip<uidStats.size(); ip++) {
2454 BroadcastStats bs = uidStats.valueAt(ip);
2455 pw.print(" ");
2456 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2457 UserHandle.formatUid(pw, bs.mUid);
2458 pw.print(":");
2459 pw.print(bs.mPackageName);
2460 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2461 pw.print(" running, "); pw.print(bs.numWakeup);
2462 pw.println(" wakeups:");
2463 tmpFilters.clear();
2464 for (int is=0; is<bs.filterStats.size(); is++) {
2465 tmpFilters.add(bs.filterStats.valueAt(is));
2466 }
2467 Collections.sort(tmpFilters, comparator);
2468 for (int i=0; i<tmpFilters.size(); i++) {
2469 FilterStats fs = tmpFilters.get(i);
2470 pw.print(" ");
2471 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2472 TimeUtils.formatDuration(fs.aggregateTime, pw);
2473 pw.print(" "); pw.print(fs.numWakeup);
2474 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002475 pw.print(" alarms, last ");
2476 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2477 pw.println(":");
2478 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002479 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002480 pw.println();
2481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002482 }
2483 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002484 pw.println();
2485 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002486
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002487 if (RECORD_DEVICE_IDLE_ALARMS) {
2488 pw.println();
2489 pw.println(" Allow while idle dispatches:");
2490 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2491 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2492 pw.print(" ");
2493 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2494 pw.print(": ");
2495 UserHandle.formatUid(pw, ent.uid);
2496 pw.print(":");
2497 pw.println(ent.pkg);
2498 if (ent.op != null) {
2499 pw.print(" ");
2500 pw.print(ent.op);
2501 pw.print(" / ");
2502 pw.print(ent.tag);
2503 if (ent.argRealtime != 0) {
2504 pw.print(" (");
2505 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2506 pw.print(")");
2507 }
2508 pw.println();
2509 }
2510 }
2511 }
2512
Christopher Tate18a75f12013-07-01 18:18:59 -07002513 if (WAKEUP_STATS) {
2514 pw.println();
2515 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002516 long last = -1;
2517 for (WakeupEvent event : mRecentWakeups) {
2518 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2519 pw.print('|');
2520 if (last < 0) {
2521 pw.print('0');
2522 } else {
2523 pw.print(event.when - last);
2524 }
2525 last = event.when;
2526 pw.print('|'); pw.print(event.uid);
2527 pw.print('|'); pw.print(event.action);
2528 pw.println();
2529 }
2530 pw.println();
2531 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002532 }
2533 }
2534
Kweku Adams61e03292017-10-19 14:27:12 -07002535 void dumpProto(FileDescriptor fd) {
2536 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2537
2538 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002539 final long nowRTC = mInjector.getCurrentTimeMillis();
2540 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002541 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2542 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2543 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002544 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002545 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002546 mLastTimeChangeRealtime);
2547
Yi Jin2b30f322018-02-20 15:41:47 -08002548 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002549
Makoto Onukie4918212018-02-06 11:30:15 -08002550 if (mAppStateTracker != null) {
2551 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002552 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002553 }
Kweku Adams61e03292017-10-19 14:27:12 -07002554
Yi Jin2b30f322018-02-20 15:41:47 -08002555 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002556 if (!mInteractive) {
2557 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002558 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002559 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002560 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002561 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002562 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002563 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002564 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002565 nowElapsed - mNextNonWakeupDeliveryTime);
2566 }
2567
Yi Jin2b30f322018-02-20 15:41:47 -08002568 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002569 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002570 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002571 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002572 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002573 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002574 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002575 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002576 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002577
2578 final TreeSet<Integer> users = new TreeSet<>();
2579 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2580 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2581 users.add(mNextAlarmClockForUser.keyAt(i));
2582 }
2583 final int pendingSendNextAlarmClockChangedForUserSize =
2584 mPendingSendNextAlarmClockChangedForUser.size();
2585 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2586 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2587 }
2588 for (int user : users) {
2589 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2590 final long time = next != null ? next.getTriggerTime() : 0;
2591 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002592 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002593 proto.write(AlarmClockMetadataProto.USER, user);
2594 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2595 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2596 proto.end(aToken);
2597 }
2598 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002599 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002600 nowElapsed, nowRTC);
2601 }
2602 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2603 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2604 if (blockedAlarms != null) {
2605 for (Alarm a : blockedAlarms) {
2606 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002607 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002608 nowElapsed, nowRTC);
2609 }
2610 }
2611 }
2612 if (mPendingIdleUntil != null) {
2613 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002614 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002615 }
2616 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002617 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002618 nowElapsed, nowRTC);
2619 }
2620 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002621 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002622 nowElapsed, nowRTC);
2623 }
2624
2625 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002626 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002627 nowElapsed, nowRTC);
2628 }
2629
Yi Jin2b30f322018-02-20 15:41:47 -08002630 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2631 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2632 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2633 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002634 mNonInteractiveTime);
2635
Yi Jin2b30f322018-02-20 15:41:47 -08002636 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2637 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2638 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2639 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2640 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002641
2642 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002643 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002644 }
2645
Kweku Adams61e03292017-10-19 14:27:12 -07002646 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2647 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002648 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002649 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2650 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2651
Yi Jin2b30f322018-02-20 15:41:47 -08002652 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2653 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2654 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002655 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002656 proto.end(token);
2657 }
2658
Makoto Onukiadb50d82018-01-29 16:20:30 -08002659 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2660 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002661 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002662 mUseAllowWhileIdleShortTime.keyAt(i));
2663 }
2664 }
2665
Yi Jin2b30f322018-02-20 15:41:47 -08002666 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002667
2668 final FilterStats[] topFilters = new FilterStats[10];
2669 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2670 @Override
2671 public int compare(FilterStats lhs, FilterStats rhs) {
2672 if (lhs.aggregateTime < rhs.aggregateTime) {
2673 return 1;
2674 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2675 return -1;
2676 }
2677 return 0;
2678 }
2679 };
2680 int len = 0;
2681 // Get the top 10 FilterStats, ordered by aggregateTime.
2682 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2683 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2684 for (int ip = 0; ip < uidStats.size(); ++ip) {
2685 BroadcastStats bs = uidStats.valueAt(ip);
2686 for (int is = 0; is < bs.filterStats.size(); ++is) {
2687 FilterStats fs = bs.filterStats.valueAt(is);
2688 int pos = len > 0
2689 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2690 if (pos < 0) {
2691 pos = -pos - 1;
2692 }
2693 if (pos < topFilters.length) {
2694 int copylen = topFilters.length - pos - 1;
2695 if (copylen > 0) {
2696 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2697 }
2698 topFilters[pos] = fs;
2699 if (len < topFilters.length) {
2700 len++;
2701 }
2702 }
2703 }
2704 }
2705 }
2706 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002707 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002708 FilterStats fs = topFilters[i];
2709
Yi Jin2b30f322018-02-20 15:41:47 -08002710 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2711 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002712 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002713 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002714
2715 proto.end(token);
2716 }
2717
2718 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2719 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2720 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2721 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002722 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002723
2724 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002725 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002726
2727 // uidStats is an ArrayMap, which we can't sort.
2728 tmpFilters.clear();
2729 for (int is = 0; is < bs.filterStats.size(); ++is) {
2730 tmpFilters.add(bs.filterStats.valueAt(is));
2731 }
2732 Collections.sort(tmpFilters, comparator);
2733 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002734 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002735 }
2736
2737 proto.end(token);
2738 }
2739 }
2740
2741 if (RECORD_DEVICE_IDLE_ALARMS) {
2742 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2743 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2744 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002745 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002746
2747 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2748 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2749 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2750 proto.write(IdleDispatchEntryProto.OP, ent.op);
2751 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2752 ent.elapsedRealtime);
2753 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2754
2755 proto.end(token);
2756 }
2757 }
2758
2759 if (WAKEUP_STATS) {
2760 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002761 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002762 proto.write(WakeupEventProto.UID, event.uid);
2763 proto.write(WakeupEventProto.ACTION, event.action);
2764 proto.write(WakeupEventProto.WHEN, event.when);
2765 proto.end(token);
2766 }
2767 }
2768 }
2769
2770 proto.flush();
2771 }
2772
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002773 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002774 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2775 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002776 final long nowRTC = mInjector.getCurrentTimeMillis();
2777 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002778 final int NZ = mAlarmBatches.size();
2779 for (int iz = 0; iz < NZ; iz++) {
2780 Batch bz = mAlarmBatches.get(iz);
2781 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002782 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002783 pw.flush();
2784 Slog.v(TAG, bs.toString());
2785 bs.reset();
2786 }
2787 }
2788
2789 private boolean validateConsistencyLocked() {
2790 if (DEBUG_VALIDATE) {
2791 long lastTime = Long.MIN_VALUE;
2792 final int N = mAlarmBatches.size();
2793 for (int i = 0; i < N; i++) {
2794 Batch b = mAlarmBatches.get(i);
2795 if (b.start >= lastTime) {
2796 // duplicate start times are okay because of standalone batches
2797 lastTime = b.start;
2798 } else {
2799 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002800 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2801 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002802 return false;
2803 }
2804 }
2805 }
2806 return true;
2807 }
2808
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002809 private Batch findFirstWakeupBatchLocked() {
2810 final int N = mAlarmBatches.size();
2811 for (int i = 0; i < N; i++) {
2812 Batch b = mAlarmBatches.get(i);
2813 if (b.hasWakeups()) {
2814 return b;
2815 }
2816 }
2817 return null;
2818 }
2819
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002820 long getNextWakeFromIdleTimeImpl() {
2821 synchronized (mLock) {
2822 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2823 }
2824 }
2825
2826 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002827 synchronized (mLock) {
2828 return mNextAlarmClockForUser.get(userId);
2829 }
2830 }
2831
2832 /**
2833 * Recomputes the next alarm clock for all users.
2834 */
2835 private void updateNextAlarmClockLocked() {
2836 if (!mNextAlarmClockMayChange) {
2837 return;
2838 }
2839 mNextAlarmClockMayChange = false;
2840
Jose Lima235510e2014-08-13 12:50:01 -07002841 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002842 nextForUser.clear();
2843
2844 final int N = mAlarmBatches.size();
2845 for (int i = 0; i < N; i++) {
2846 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2847 final int M = alarms.size();
2848
2849 for (int j = 0; j < M; j++) {
2850 Alarm a = alarms.get(j);
2851 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002852 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002853 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002854
2855 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002856 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002857 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002858 " for user " + userId);
2859 }
2860
2861 // Alarms and batches are sorted by time, no need to compare times here.
2862 if (nextForUser.get(userId) == null) {
2863 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002864 } else if (a.alarmClock.equals(current)
2865 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2866 // same/earlier time and it's the one we cited before, so stick with it
2867 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002868 }
2869 }
2870 }
2871 }
2872
2873 // Update mNextAlarmForUser with new values.
2874 final int NN = nextForUser.size();
2875 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002876 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002877 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002878 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002879 if (!newAlarm.equals(currentAlarm)) {
2880 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2881 }
2882 }
2883
2884 // Remove users without any alarm clocks scheduled.
2885 final int NNN = mNextAlarmClockForUser.size();
2886 for (int i = NNN - 1; i >= 0; i--) {
2887 int userId = mNextAlarmClockForUser.keyAt(i);
2888 if (nextForUser.get(userId) == null) {
2889 updateNextAlarmInfoForUserLocked(userId, null);
2890 }
2891 }
2892 }
2893
Jose Lima235510e2014-08-13 12:50:01 -07002894 private void updateNextAlarmInfoForUserLocked(int userId,
2895 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002896 if (alarmClock != null) {
2897 if (DEBUG_ALARM_CLOCK) {
2898 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002899 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002900 }
2901 mNextAlarmClockForUser.put(userId, alarmClock);
2902 } else {
2903 if (DEBUG_ALARM_CLOCK) {
2904 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2905 }
2906 mNextAlarmClockForUser.remove(userId);
2907 }
2908
2909 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2910 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2911 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2912 }
2913
2914 /**
2915 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2916 * for which alarm clocks have changed since the last call to this.
2917 *
2918 * Do not call with a lock held. Only call from mHandler's thread.
2919 *
2920 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2921 */
2922 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002923 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002924 pendingUsers.clear();
2925
2926 synchronized (mLock) {
2927 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2928 for (int i = 0; i < N; i++) {
2929 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2930 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2931 }
2932 mPendingSendNextAlarmClockChangedForUser.clear();
2933 }
2934
2935 final int N = pendingUsers.size();
2936 for (int i = 0; i < N; i++) {
2937 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002938 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002939 Settings.System.putStringForUser(getContext().getContentResolver(),
2940 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002941 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002942 userId);
2943
2944 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2945 new UserHandle(userId));
2946 }
2947 }
2948
2949 /**
2950 * Formats an alarm like platform/packages/apps/DeskClock used to.
2951 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002952 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2953 int userId) {
2954 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002955 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2956 return (info == null) ? "" :
2957 DateFormat.format(pattern, info.getTriggerTime()).toString();
2958 }
2959
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002960 /**
2961 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2962 * by more than half a minute, log a wtf.
2963 */
2964 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2965 final StringBuilder errorMsg = new StringBuilder();
2966 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002967 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002968 stuck = true;
2969 errorMsg.append("[mNextNonWakeup=");
2970 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002971 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002972 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002973 errorMsg.append(", mLastWakeup=");
2974 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002975 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002976 errorMsg.append("];");
2977 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002978 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002979 stuck = true;
2980 errorMsg.append("[mNextWakeup=");
2981 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002982 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002983 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002984 errorMsg.append(", mLastWakeup=");
2985 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2986 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002987 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002988 errorMsg.append("];");
2989 }
2990 if (stuck) {
2991 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2992 }
2993 }
2994
Adam Lesinski182f73f2013-12-05 16:48:06 -08002995 void rescheduleKernelAlarmsLocked() {
2996 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2997 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002998 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002999 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003000 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003001 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08003002 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003003 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003004 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08003005 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07003006 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08003007 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003008 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003009 if (firstBatch != firstWakeup) {
3010 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003011 }
3012 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003013 if (mPendingNonWakeupAlarms.size() > 0) {
3014 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
3015 nextNonWakeup = mNextNonWakeupDeliveryTime;
3016 }
3017 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003018 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003019 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07003020 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003021 setLocked(ELAPSED_REALTIME, nextNonWakeup);
3022 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003023 }
3024
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003025 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003026 if (operation == null && directReceiver == null) {
3027 if (localLOGV) {
3028 Slog.w(TAG, "requested remove() of null operation",
3029 new RuntimeException("here"));
3030 }
3031 return;
3032 }
3033
Adam Lesinski182f73f2013-12-05 16:48:06 -08003034 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003035 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003036 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3037 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003038 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003039 if (b.size() == 0) {
3040 mAlarmBatches.remove(i);
3041 }
3042 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003043 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003044 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003045 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3046 mPendingWhileIdleAlarms.remove(i);
3047 }
3048 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003049 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3050 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3051 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3052 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
3053 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3054 alarmsForUid.remove(j);
3055 }
3056 }
3057 if (alarmsForUid.size() == 0) {
3058 mPendingBackgroundAlarms.removeAt(i);
3059 }
3060 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003061 if (didRemove) {
3062 if (DEBUG_BATCH) {
3063 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
3064 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003065 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003066 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003067 mPendingIdleUntil = null;
3068 restorePending = true;
3069 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003070 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003071 mNextWakeFromIdle = null;
3072 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003073 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003074 if (restorePending) {
3075 restorePendingWhileIdleAlarmsLocked();
3076 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003077 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003078 }
3079 }
3080
Christopher Tate1d99c392017-12-07 16:54:04 -08003081 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003082 if (uid == Process.SYSTEM_UID) {
3083 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
3084 return;
3085 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003086 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003087 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003088 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3089 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003090 didRemove |= b.remove(whichAlarms);
3091 if (b.size() == 0) {
3092 mAlarmBatches.remove(i);
3093 }
3094 }
3095 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
3096 final Alarm a = mPendingWhileIdleAlarms.get(i);
3097 if (a.uid == uid) {
3098 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3099 mPendingWhileIdleAlarms.remove(i);
3100 }
3101 }
3102 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
3103 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3104 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3105 if (alarmsForUid.get(j).uid == uid) {
3106 alarmsForUid.remove(j);
3107 }
3108 }
3109 if (alarmsForUid.size() == 0) {
3110 mPendingBackgroundAlarms.removeAt(i);
3111 }
3112 }
3113 if (didRemove) {
3114 if (DEBUG_BATCH) {
3115 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
3116 }
3117 rebatchAllAlarmsLocked(true);
3118 rescheduleKernelAlarmsLocked();
3119 updateNextAlarmClockLocked();
3120 }
3121 }
3122
3123 void removeLocked(final String packageName) {
3124 if (packageName == null) {
3125 if (localLOGV) {
3126 Slog.w(TAG, "requested remove() of null packageName",
3127 new RuntimeException("here"));
3128 }
3129 return;
3130 }
3131
3132 boolean didRemove = false;
3133 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08003134 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08003135 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3136 Batch b = mAlarmBatches.get(i);
3137 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003138 if (b.size() == 0) {
3139 mAlarmBatches.remove(i);
3140 }
3141 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08003142 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
3143 if (oldHasTick != newHasTick) {
3144 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
3145 }
3146
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003147 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003148 final Alarm a = mPendingWhileIdleAlarms.get(i);
3149 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003150 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3151 mPendingWhileIdleAlarms.remove(i);
3152 }
3153 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003154 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
3155 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3156 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3157 if (alarmsForUid.get(j).matches(packageName)) {
3158 alarmsForUid.remove(j);
3159 }
3160 }
3161 if (alarmsForUid.size() == 0) {
3162 mPendingBackgroundAlarms.removeAt(i);
3163 }
3164 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003165 if (didRemove) {
3166 if (DEBUG_BATCH) {
3167 Slog.v(TAG, "remove(package) changed bounds; rebatching");
3168 }
3169 rebatchAllAlarmsLocked(true);
3170 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003171 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003172 }
3173 }
3174
Christopher Tate1d99c392017-12-07 16:54:04 -08003175 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003176 if (uid == Process.SYSTEM_UID) {
3177 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
3178 return;
3179 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003180 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003181 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
3182 try {
3183 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
3184 uid, a.packageName)) {
3185 return true;
3186 }
3187 } catch (RemoteException e) { /* fall through */}
3188 return false;
3189 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003190 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3191 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003192 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003193 if (b.size() == 0) {
3194 mAlarmBatches.remove(i);
3195 }
3196 }
3197 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
3198 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003199 if (a.uid == uid) {
3200 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3201 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003202 }
3203 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003204 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3205 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
3206 mPendingBackgroundAlarms.removeAt(i);
3207 }
3208 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003209 if (didRemove) {
3210 if (DEBUG_BATCH) {
3211 Slog.v(TAG, "remove(package) changed bounds; rebatching");
3212 }
3213 rebatchAllAlarmsLocked(true);
3214 rescheduleKernelAlarmsLocked();
3215 updateNextAlarmClockLocked();
3216 }
3217 }
3218
Adam Lesinski182f73f2013-12-05 16:48:06 -08003219 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003220 if (userHandle == UserHandle.USER_SYSTEM) {
3221 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
3222 return;
3223 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003224 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003225 final Predicate<Alarm> whichAlarms =
3226 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003227 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3228 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003229 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003230 if (b.size() == 0) {
3231 mAlarmBatches.remove(i);
3232 }
3233 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003234 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003235 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003236 == userHandle) {
3237 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3238 mPendingWhileIdleAlarms.remove(i);
3239 }
3240 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003241 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3242 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
3243 mPendingBackgroundAlarms.removeAt(i);
3244 }
3245 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003246 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3247 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3248 mLastAllowWhileIdleDispatch.removeAt(i);
3249 }
3250 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003251
3252 if (didRemove) {
3253 if (DEBUG_BATCH) {
3254 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3255 }
3256 rebatchAllAlarmsLocked(true);
3257 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003258 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003259 }
3260 }
3261
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003262 void interactiveStateChangedLocked(boolean interactive) {
3263 if (mInteractive != interactive) {
3264 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003265 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003266 if (interactive) {
3267 if (mPendingNonWakeupAlarms.size() > 0) {
3268 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3269 mTotalDelayTime += thisDelayTime;
3270 if (mMaxDelayTime < thisDelayTime) {
3271 mMaxDelayTime = thisDelayTime;
3272 }
3273 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3274 mPendingNonWakeupAlarms.clear();
3275 }
3276 if (mNonInteractiveStartTime > 0) {
3277 long dur = nowELAPSED - mNonInteractiveStartTime;
3278 if (dur > mNonInteractiveTime) {
3279 mNonInteractiveTime = dur;
3280 }
3281 }
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003282 // And send a TIME_TICK right now, since it is important to get the UI updated.
3283 mHandler.post(() ->
3284 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003285 } else {
3286 mNonInteractiveStartTime = nowELAPSED;
3287 }
3288 }
3289 }
3290
Adam Lesinski182f73f2013-12-05 16:48:06 -08003291 boolean lookForPackageLocked(String packageName) {
3292 for (int i = 0; i < mAlarmBatches.size(); i++) {
3293 Batch b = mAlarmBatches.get(i);
3294 if (b.hasPackage(packageName)) {
3295 return true;
3296 }
3297 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003298 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003299 final Alarm a = mPendingWhileIdleAlarms.get(i);
3300 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003301 return true;
3302 }
3303 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003304 return false;
3305 }
3306
3307 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003308 if (mInjector.isAlarmDriverPresent()) {
3309 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003310 } else {
3311 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003312 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003313
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003314 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003315 mHandler.sendMessageAtTime(msg, when);
3316 }
3317 }
3318
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003319 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003320 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 for (int i=list.size()-1; i>=0; i--) {
3322 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003323 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3324 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003325 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 }
3327 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003328
3329 private static final String labelForType(int type) {
3330 switch (type) {
3331 case RTC: return "RTC";
3332 case RTC_WAKEUP : return "RTC_WAKEUP";
3333 case ELAPSED_REALTIME : return "ELAPSED";
3334 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003335 }
3336 return "--unknown--";
3337 }
3338
3339 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003340 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003341 for (int i=list.size()-1; i>=0; i--) {
3342 Alarm a = list.get(i);
3343 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003344 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3345 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003346 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003347 }
3348 }
3349
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003350 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003351 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003352 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003353 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003354 return false;
3355 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003356 if (alarm.operation != null) {
3357 if (alarm.operation.isActivity()) {
3358 // Don't defer starting actual UI
3359 return false;
3360 }
3361 if (alarm.operation.isForegroundService()) {
3362 // FG service alarms are nearly as important; consult AST policy
3363 exemptOnBatterySaver = true;
3364 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003365 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003366 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003367 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003368 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003369 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3370 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003371 }
3372
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003373 private static native long init();
3374 private static native void close(long nativeData);
3375 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3376 private static native int waitForAlarm(long nativeData);
3377 private static native int setKernelTime(long nativeData, long millis);
3378 private static native int setKernelTimezone(long nativeData, int minuteswest);
3379 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380
Makoto Onukiadb50d82018-01-29 16:20:30 -08003381 private long getWhileIdleMinIntervalLocked(int uid) {
3382 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003383 final boolean ebs = (mAppStateTracker != null)
3384 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003385 if (!dozing && !ebs) {
3386 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3387 }
3388 if (dozing) {
3389 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3390 }
3391 if (mUseAllowWhileIdleShortTime.get(uid)) {
3392 // if the last allow-while-idle went off while uid was fg, or the uid
3393 // recently came into fg, don't block the alarm for long.
3394 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3395 }
3396 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3397 }
3398
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003399 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003400 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003401 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003402 // batches are temporally sorted, so we need only pull from the
3403 // start of the list until we either empty it or hit a batch
3404 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003405 while (mAlarmBatches.size() > 0) {
3406 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003407 if (batch.start > nowELAPSED) {
3408 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 break;
3410 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003411
Christopher Tatee0a22b32013-07-11 14:43:13 -07003412 // We will (re)schedule some alarms now; don't let that interfere
3413 // with delivery of this current batch
3414 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003415
Christopher Tatee0a22b32013-07-11 14:43:13 -07003416 final int N = batch.size();
3417 for (int i = 0; i < N; i++) {
3418 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003419
3420 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3421 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003422 // schedule such alarms. The first such alarm from an app is always delivered.
3423 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003424 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003425 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003426 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3427 // alarm went off for this app. Reschedule the alarm to be in the
3428 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003429 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003430 if (alarm.maxWhenElapsed < minTime) {
3431 alarm.maxWhenElapsed = minTime;
3432 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003433 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003434 if (RECORD_DEVICE_IDLE_ALARMS) {
3435 IdleDispatchEntry ent = new IdleDispatchEntry();
3436 ent.uid = alarm.uid;
3437 ent.pkg = alarm.operation.getCreatorPackage();
3438 ent.tag = alarm.operation.getTag("");
3439 ent.op = "RESCHEDULE";
3440 ent.elapsedRealtime = nowELAPSED;
3441 ent.argRealtime = lastTime;
3442 mAllowWhileIdleDispatches.add(ent);
3443 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003444 setImplLocked(alarm, true, false);
3445 continue;
3446 }
3447 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003448 if (isBackgroundRestricted(alarm)) {
3449 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3450 if (DEBUG_BG_LIMIT) {
3451 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3452 }
3453 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3454 if (alarmsForUid == null) {
3455 alarmsForUid = new ArrayList<>();
3456 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3457 }
3458 alarmsForUid.add(alarm);
3459 continue;
3460 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003461
Christopher Tatee0a22b32013-07-11 14:43:13 -07003462 alarm.count = 1;
3463 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003464 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3465 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003466 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003467 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003468 if (mPendingIdleUntil == alarm) {
3469 mPendingIdleUntil = null;
3470 rebatchAllAlarmsLocked(false);
3471 restorePendingWhileIdleAlarmsLocked();
3472 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003473 if (mNextWakeFromIdle == alarm) {
3474 mNextWakeFromIdle = null;
3475 rebatchAllAlarmsLocked(false);
3476 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003477
3478 // Recurring alarms may have passed several alarm intervals while the
3479 // phone was asleep or off, so pass a trigger count when sending them.
3480 if (alarm.repeatInterval > 0) {
3481 // this adjustment will be zero if we're late by
3482 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003483 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003484
3485 // Also schedule its next recurrence
3486 final long delta = alarm.count * alarm.repeatInterval;
3487 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003488 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003489 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003490 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3491 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003492 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003493
Christopher Tate864d42e2014-12-02 11:48:53 -08003494 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003495 hasWakeup = true;
3496 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003497
3498 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3499 if (alarm.alarmClock != null) {
3500 mNextAlarmClockMayChange = true;
3501 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003503 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003504
Christopher Tate1590f1e2014-10-02 17:27:57 -07003505 // This is a new alarm delivery set; bump the sequence number to indicate that
3506 // all apps' alarm delivery classes should be recalculated.
3507 mCurrentSeq++;
3508 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003509 Collections.sort(triggerList, mAlarmDispatchComparator);
3510
3511 if (localLOGV) {
3512 for (int i=0; i<triggerList.size(); i++) {
3513 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3514 }
3515 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003516
3517 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003518 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003519
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 /**
3521 * This Comparator sorts Alarms into increasing time order.
3522 */
3523 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3524 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003525 long when1 = a1.whenElapsed;
3526 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003527 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 return 1;
3529 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003530 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003531 return -1;
3532 }
3533 return 0;
3534 }
3535 }
Kweku Adams61e03292017-10-19 14:27:12 -07003536
Makoto Onuki2206af32017-11-21 16:25:35 -08003537 @VisibleForTesting
3538 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003539 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003540 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003541 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003542 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003543 public final IAlarmListener listener;
3544 public final String listenerTag;
3545 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003546 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003547 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003548 public final AlarmManager.AlarmClockInfo alarmClock;
3549 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003550 public final int creatorUid;
3551 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003552 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003553 public int count;
3554 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003555 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003556 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003557 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003558 // Expected alarm expiry time before app standby deferring is applied.
3559 public long expectedWhenElapsed;
3560 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003562 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003563
Christopher Tate3e04b472013-10-21 17:51:31 -07003564 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003565 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3566 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3567 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003568 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003569 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003570 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3571 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003572 when = _when;
3573 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003574 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003575 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003576 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003577 repeatInterval = _interval;
3578 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003579 listener = _rec;
3580 listenerTag = _listenerTag;
3581 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003582 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003583 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003584 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003585 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003586 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003587 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003588 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003589 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003590
Christopher Tate14a7bb02015-10-01 10:24:31 -07003591 public static String makeTag(PendingIntent pi, String tag, int type) {
3592 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3593 ? "*walarm*:" : "*alarm*:";
3594 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3595 }
3596
3597 public WakeupEvent makeWakeupEvent(long nowRTC) {
3598 return new WakeupEvent(nowRTC, creatorUid,
3599 (operation != null)
3600 ? operation.getIntent().getAction()
3601 : ("<listener>:" + listenerTag));
3602 }
3603
3604 // Returns true if either matches
3605 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3606 return (operation != null)
3607 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003608 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003609 }
3610
3611 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003612 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003613 }
3614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003616 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003617 StringBuilder sb = new StringBuilder(128);
3618 sb.append("Alarm{");
3619 sb.append(Integer.toHexString(System.identityHashCode(this)));
3620 sb.append(" type ");
3621 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003622 sb.append(" when ");
3623 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003624 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003625 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003626 sb.append('}');
3627 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003628 }
3629
Kweku Adams61e03292017-10-19 14:27:12 -07003630 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003631 SimpleDateFormat sdf) {
3632 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003633 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003634 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003635 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3636 expectedWhenElapsed, nowELAPSED, pw);
3637 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3638 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003639 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3640 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003641 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3642 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003643 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003644 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003645 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003646 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003647 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003648 }
3649 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003650 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003651 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003652 pw.print(" count="); pw.print(count);
3653 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003654 if (alarmClock != null) {
3655 pw.print(prefix); pw.println("Alarm clock:");
3656 pw.print(prefix); pw.print(" triggerTime=");
3657 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3658 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3659 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003660 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003661 if (listener != null) {
3662 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3663 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003664 }
Kweku Adams61e03292017-10-19 14:27:12 -07003665
3666 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3667 long nowRTC) {
3668 final long token = proto.start(fieldId);
3669
3670 proto.write(AlarmProto.TAG, statsTag);
3671 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003672 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003673 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3674 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3675 proto.write(AlarmProto.COUNT, count);
3676 proto.write(AlarmProto.FLAGS, flags);
3677 if (alarmClock != null) {
3678 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3679 }
3680 if (operation != null) {
3681 operation.writeToProto(proto, AlarmProto.OPERATION);
3682 }
3683 if (listener != null) {
3684 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3685 }
3686
3687 proto.end(token);
3688 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003690
Christopher Tatee0a22b32013-07-11 14:43:13 -07003691 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3692 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003693 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3694 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003695 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003696 break;
3697 }
3698
Christopher Tatee0a22b32013-07-11 14:43:13 -07003699 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003700 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3701 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003702 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003703 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003704 }
3705 }
3706
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003707 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3708 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3709 if (timeSinceOn < 5*60*1000) {
3710 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3711 return 2*60*1000;
3712 } else if (timeSinceOn < 30*60*1000) {
3713 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3714 return 15*60*1000;
3715 } else {
3716 // Otherwise, we will delay by at most an hour.
3717 return 60*60*1000;
3718 }
3719 }
3720
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003721 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003722 if (duration < 15*60*1000) {
3723 // If the duration until the time is less than 15 minutes, the maximum fuzz
3724 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003725 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003726 } else if (duration < 90*60*1000) {
3727 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3728 return 15*60*1000;
3729 } else {
3730 // Otherwise, we will fuzz by at most half an hour.
3731 return 30*60*1000;
3732 }
3733 }
3734
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003735 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3736 if (mInteractive) {
3737 return false;
3738 }
3739 if (mLastAlarmDeliveryTime <= 0) {
3740 return false;
3741 }
minho.choo649acab2014-12-12 16:13:55 +09003742 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003743 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3744 // and the next delivery time is in the past, then just deliver them all. This
3745 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3746 return false;
3747 }
3748 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3749 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3750 }
3751
3752 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3753 mLastAlarmDeliveryTime = nowELAPSED;
3754 for (int i=0; i<triggerList.size(); i++) {
3755 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003756 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003757 if (alarm.wakeup) {
3758 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3759 } else {
3760 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3761 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003762 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003763 if (localLOGV) {
3764 Slog.v(TAG, "sending alarm " + alarm);
3765 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003766 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003767 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3768 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003769 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003770 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003771 } catch (RuntimeException e) {
3772 Slog.w(TAG, "Failure sending alarm.", e);
3773 }
Tim Murray175c0f92017-11-28 15:01:04 -08003774 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003775 }
3776 }
3777
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003778 private boolean isExemptFromAppStandby(Alarm a) {
3779 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3780 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3781 }
3782
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003783 @VisibleForTesting
3784 static class Injector {
3785 private long mNativeData;
3786 private Context mContext;
3787
3788 Injector(Context context) {
3789 mContext = context;
3790 }
3791
3792 void init() {
3793 mNativeData = AlarmManagerService.init();
3794 }
3795
3796 int waitForAlarm() {
3797 return AlarmManagerService.waitForAlarm(mNativeData);
3798 }
3799
3800 boolean isAlarmDriverPresent() {
3801 return mNativeData != 0;
3802 }
3803
3804 void setAlarm(int type, long millis) {
3805 // The kernel never triggers alarms with negative wakeup times
3806 // so we ensure they are positive.
3807 final long alarmSeconds, alarmNanoseconds;
3808 if (millis < 0) {
3809 alarmSeconds = 0;
3810 alarmNanoseconds = 0;
3811 } else {
3812 alarmSeconds = millis / 1000;
3813 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3814 }
3815
3816 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3817 alarmNanoseconds);
3818 if (result != 0) {
3819 final long nowElapsed = SystemClock.elapsedRealtime();
3820 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3821 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3822 + "), ret = " + result + " = " + Os.strerror(result));
3823 }
3824 }
3825
3826 long getNextAlarm(int type) {
3827 return AlarmManagerService.getNextAlarm(mNativeData, type);
3828 }
3829
3830 void setKernelTimezone(int minutesWest) {
3831 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3832 }
3833
3834 void setKernelTime(long millis) {
3835 if (mNativeData != 0) {
3836 AlarmManagerService.setKernelTime(mNativeData, millis);
3837 }
3838 }
3839
3840 void close() {
3841 AlarmManagerService.close(mNativeData);
3842 }
3843
3844 long getElapsedRealtime() {
3845 return SystemClock.elapsedRealtime();
3846 }
3847
3848 long getCurrentTimeMillis() {
3849 return System.currentTimeMillis();
3850 }
3851
3852 PowerManager.WakeLock getAlarmWakeLock() {
3853 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3854 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3855 }
3856
3857 int getSystemUiUid() {
3858 int sysUiUid = -1;
3859 final PackageManager pm = mContext.getPackageManager();
3860 try {
3861 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3862 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3863 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3864 sysUiUid = sysUi.uid;
3865 } else {
3866 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3867 + " defined by non-privileged app " + sysUi.packageName
3868 + " - ignoring");
3869 }
3870 } catch (NameNotFoundException e) {
3871 }
3872 return sysUiUid;
3873 }
3874
3875 ClockReceiver getClockReceiver(AlarmManagerService service) {
3876 return service.new ClockReceiver();
3877 }
3878 }
3879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 private class AlarmThread extends Thread
3881 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003882 private int mFalseWakeups;
3883 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003884 public AlarmThread()
3885 {
3886 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003887 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003888 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003889 }
Kweku Adams61e03292017-10-19 14:27:12 -07003890
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003891 public void run()
3892 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003893 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3894
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003895 while (true)
3896 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003897 int result = mInjector.waitForAlarm();
3898 final long nowRTC = mInjector.getCurrentTimeMillis();
3899 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003900 synchronized (mLock) {
3901 mLastWakeup = nowELAPSED;
3902 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003903 if (result == 0) {
3904 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3905 + ", nowElapsed = " + nowELAPSED);
3906 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003907 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003909 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003910 // The kernel can give us spurious time change notifications due to
3911 // small adjustments it makes internally; we want to filter those out.
3912 final long lastTimeChangeClockTime;
3913 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003914 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003915 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3916 expectedClockTime = lastTimeChangeClockTime
3917 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003918 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003919 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3920 || nowRTC > (expectedClockTime+1000)) {
3921 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003922 // let's do it!
3923 if (DEBUG_BATCH) {
3924 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3925 }
Bookatz7948c872018-09-04 12:58:33 -07003926 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3927 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003928 removeImpl(null, mTimeTickTrigger);
3929 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003930 rebatchAllAlarms();
3931 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003932 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003933 synchronized (mLock) {
3934 mNumTimeChanged++;
3935 mLastTimeChangeClockTime = nowRTC;
3936 mLastTimeChangeRealtime = nowELAPSED;
3937 }
3938 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3939 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003940 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003941 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3942 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003943 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3944
3945 // The world has changed on us, so we need to re-evaluate alarms
3946 // regardless of whether the kernel has told us one went off.
3947 result |= IS_WAKEUP_MASK;
3948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003949 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950
Dianne Hackbornc3527222015-05-13 14:03:20 -07003951 if (result != TIME_CHANGED_MASK) {
3952 // If this was anything besides just a time change, then figure what if
3953 // anything to do about alarms.
3954 synchronized (mLock) {
3955 if (localLOGV) Slog.v(
3956 TAG, "Checking for alarms... rtc=" + nowRTC
3957 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003958
Dianne Hackbornc3527222015-05-13 14:03:20 -07003959 if (WAKEUP_STATS) {
3960 if ((result & IS_WAKEUP_MASK) != 0) {
3961 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3962 int n = 0;
3963 for (WakeupEvent event : mRecentWakeups) {
3964 if (event.when > newEarliest) break;
3965 n++; // number of now-stale entries at the list head
3966 }
3967 for (int i = 0; i < n; i++) {
3968 mRecentWakeups.remove();
3969 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003970
Dianne Hackbornc3527222015-05-13 14:03:20 -07003971 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003972 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003973 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003974
Christopher Tate8b98ade2018-02-09 11:13:19 -08003975 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003976 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3977 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3978 // if there are no wakeup alarms and the screen is off, we can
3979 // delay what we have so far until the future.
3980 if (mPendingNonWakeupAlarms.size() == 0) {
3981 mStartCurrentDelayTime = nowELAPSED;
3982 mNextNonWakeupDeliveryTime = nowELAPSED
3983 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3984 }
3985 mPendingNonWakeupAlarms.addAll(triggerList);
3986 mNumDelayedAlarms += triggerList.size();
3987 rescheduleKernelAlarmsLocked();
3988 updateNextAlarmClockLocked();
3989 } else {
3990 // now deliver the alarm intents; if there are pending non-wakeup
3991 // alarms, we need to merge them in to the list. note we don't
3992 // just deliver them first because we generally want non-wakeup
3993 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003994 if (mPendingNonWakeupAlarms.size() > 0) {
3995 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3996 triggerList.addAll(mPendingNonWakeupAlarms);
3997 Collections.sort(triggerList, mAlarmDispatchComparator);
3998 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3999 mTotalDelayTime += thisDelayTime;
4000 if (mMaxDelayTime < thisDelayTime) {
4001 mMaxDelayTime = thisDelayTime;
4002 }
4003 mPendingNonWakeupAlarms.clear();
4004 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07004005 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
4006 if (++mFalseWakeups >= mWtfThreshold) {
4007 Slog.wtf(TAG, "Too many (" + mFalseWakeups
4008 + ") false wakeups, nowElapsed=" + nowELAPSED);
4009 if (mWtfThreshold < 100_000) {
4010 mWtfThreshold *= 10;
4011 } else {
4012 mFalseWakeups = 0;
4013 }
4014 }
4015 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004016 final ArraySet<Pair<String, Integer>> triggerPackages =
4017 new ArraySet<>();
4018 for (int i = 0; i < triggerList.size(); i++) {
4019 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004020 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004021 triggerPackages.add(Pair.create(
4022 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08004023 }
4024 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07004025 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004026 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
4027 rescheduleKernelAlarmsLocked();
4028 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07004029 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004030 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07004031
4032 } else {
4033 // Just in case -- even though no wakeup flag was set, make sure
4034 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07004035 synchronized (mLock) {
4036 rescheduleKernelAlarmsLocked();
4037 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004038 }
4039 }
4040 }
4041 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07004042
David Christieebe51fc2013-07-26 13:23:29 -07004043 /**
4044 * Attribute blame for a WakeLock.
David Christieebe51fc2013-07-26 13:23:29 -07004045 * @param ws WorkSource to attribute blame.
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004046 * @param knownUid attribution uid; < 0 values are ignored.
David Christieebe51fc2013-07-26 13:23:29 -07004047 */
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004048 void setWakelockWorkSource(WorkSource ws, int knownUid, String tag, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07004049 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07004050 mWakeLock.setHistoryTag(first ? tag : null);
4051
David Christieebe51fc2013-07-26 13:23:29 -07004052 if (ws != null) {
4053 mWakeLock.setWorkSource(ws);
4054 return;
4055 }
4056
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004057 if (knownUid >= 0) {
4058 mWakeLock.setWorkSource(new WorkSource(knownUid));
Christopher Tatec4a07d12012-04-06 14:19:13 -07004059 return;
4060 }
4061 } catch (Exception e) {
4062 }
4063
4064 // Something went wrong; fall back to attributing the lock to the OS
4065 mWakeLock.setWorkSource(null);
4066 }
4067
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004068 private static int getAlarmAttributionUid(Alarm alarm) {
4069 if (alarm.workSource != null && !alarm.workSource.isEmpty()) {
4070 return alarm.workSource.getAttributionUid();
4071 }
4072
4073 return alarm.creatorUid;
4074 }
4075
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004076 @VisibleForTesting
4077 class AlarmHandler extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004078 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004079 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
4080 public static final int LISTENER_TIMEOUT = 3;
4081 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08004082 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
4083 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08004084 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07004085
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004086 AlarmHandler() {
4087 super(Looper.myLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 }
Kweku Adams61e03292017-10-19 14:27:12 -07004089
Makoto Onuki4d298b52018-02-05 10:54:58 -08004090 public void postRemoveForStopped(int uid) {
4091 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
4092 }
4093
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004094 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004095 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004096 switch (msg.what) {
4097 case ALARM_EVENT: {
4098 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
4099 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004100 final long nowRTC = mInjector.getCurrentTimeMillis();
4101 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004102 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
4103 updateNextAlarmClockLocked();
4104 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02004105
Christopher Tate14a7bb02015-10-01 10:24:31 -07004106 // now trigger the alarms without the lock held
4107 for (int i=0; i<triggerList.size(); i++) {
4108 Alarm alarm = triggerList.get(i);
4109 try {
4110 alarm.operation.send();
4111 } catch (PendingIntent.CanceledException e) {
4112 if (alarm.repeatInterval > 0) {
4113 // This IntentSender is no longer valid, but this
4114 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07004115 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004117 }
4118 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004119 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004121
4122 case SEND_NEXT_ALARM_CLOCK_CHANGED:
4123 sendNextAlarmClockChanged();
4124 break;
4125
4126 case LISTENER_TIMEOUT:
4127 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
4128 break;
4129
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004130 case REPORT_ALARMS_ACTIVE:
4131 if (mLocalDeviceIdleController != null) {
4132 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
4133 }
4134 break;
4135
Suprabh Shukla75edab12018-01-29 14:09:06 -08004136 case APP_STANDBY_PAROLE_CHANGED:
4137 synchronized (mLock) {
4138 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004139 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
4140 rescheduleKernelAlarmsLocked();
4141 updateNextAlarmClockLocked();
4142 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004143 }
4144 break;
4145
4146 case APP_STANDBY_BUCKET_CHANGED:
4147 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004148 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
4149 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
4150 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
4151 rescheduleKernelAlarmsLocked();
4152 updateNextAlarmClockLocked();
4153 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004154 }
4155 break;
4156
Makoto Onuki4d298b52018-02-05 10:54:58 -08004157 case REMOVE_FOR_STOPPED:
4158 synchronized (mLock) {
4159 removeForStoppedLocked(msg.arg1);
4160 }
4161 break;
4162
Christopher Tate14a7bb02015-10-01 10:24:31 -07004163 default:
4164 // nope, just ignore it
4165 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004166 }
4167 }
4168 }
Kweku Adams61e03292017-10-19 14:27:12 -07004169
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 class ClockReceiver extends BroadcastReceiver {
4171 public ClockReceiver() {
4172 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004173 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004174 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004175 }
Kweku Adams61e03292017-10-19 14:27:12 -07004176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004177 @Override
4178 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07004179 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004180 // Since the kernel does not keep track of DST, we need to
4181 // reset the TZ information at the beginning of each day
4182 // based off of the current Zone gmt offset + userspace tracked
4183 // daylight savings information.
4184 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004185 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
4186 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07004187 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004188 }
4189 }
Kweku Adams61e03292017-10-19 14:27:12 -07004190
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004192 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09004193 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07004194
4195 // Schedule this event for the amount of time that it would take to get to
4196 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09004197 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07004198
David Christieebe51fc2013-07-26 13:23:29 -07004199 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004200 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004201 0, null, mTimeTickTrigger, "TIME_TICK", AlarmManager.FLAG_STANDALONE,
4202 workSource, null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08004203
4204 // Finally, remember when we set the tick alarm
4205 synchronized (mLock) {
4206 mLastTickSet = currentTime;
4207 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004208 }
Christopher Tate385e4982013-07-23 18:22:29 -07004209
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 public void scheduleDateChangedEvent() {
4211 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004212 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07004213 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004214 calendar.set(Calendar.MINUTE, 0);
4215 calendar.set(Calendar.SECOND, 0);
4216 calendar.set(Calendar.MILLISECOND, 0);
4217 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07004218
4219 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07004220 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
4221 AlarmManager.FLAG_STANDALONE, workSource, null,
4222 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004223 }
4224 }
Kweku Adams61e03292017-10-19 14:27:12 -07004225
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07004226 class InteractiveStateReceiver extends BroadcastReceiver {
4227 public InteractiveStateReceiver() {
4228 IntentFilter filter = new IntentFilter();
4229 filter.addAction(Intent.ACTION_SCREEN_OFF);
4230 filter.addAction(Intent.ACTION_SCREEN_ON);
4231 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
4232 getContext().registerReceiver(this, filter);
4233 }
4234
4235 @Override
4236 public void onReceive(Context context, Intent intent) {
4237 synchronized (mLock) {
4238 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
4239 }
4240 }
4241 }
4242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004243 class UninstallReceiver extends BroadcastReceiver {
4244 public UninstallReceiver() {
4245 IntentFilter filter = new IntentFilter();
4246 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
4247 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004248 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004249 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08004250 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004251 // Register for events related to sdcard installation.
4252 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004253 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004254 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004255 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004256 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004257 }
Kweku Adams61e03292017-10-19 14:27:12 -07004258
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004259 @Override
4260 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004261 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004262 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004263 String pkgList[] = null;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004264 switch (intent.getAction()) {
4265 case Intent.ACTION_QUERY_PACKAGE_RESTART:
4266 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4267 for (String packageName : pkgList) {
4268 if (lookForPackageLocked(packageName)) {
4269 setResultCode(Activity.RESULT_OK);
4270 return;
Suprabh Shukla75edab12018-01-29 14:09:06 -08004271 }
4272 }
Dianne Hackborn409578f2010-03-10 17:23:43 -08004273 return;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004274 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
4275 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
4276 break;
4277 case Intent.ACTION_USER_STOPPED:
4278 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4279 if (userHandle >= 0) {
4280 removeUserLocked(userHandle);
4281 mAppWakeupHistory.removeForUser(userHandle);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004282 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004283 return;
4284 case Intent.ACTION_UID_REMOVED:
4285 if (uid >= 0) {
4286 mLastAllowWhileIdleDispatch.delete(uid);
4287 mUseAllowWhileIdleShortTime.delete(uid);
4288 }
4289 return;
4290 case Intent.ACTION_PACKAGE_REMOVED:
4291 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4292 // This package is being updated; don't kill its alarms.
4293 return;
4294 }
4295 // Intentional fall-through.
4296 case Intent.ACTION_PACKAGE_RESTARTED:
4297 final Uri data = intent.getData();
4298 if (data != null) {
4299 final String pkg = data.getSchemeSpecificPart();
4300 if (pkg != null) {
4301 pkgList = new String[]{pkg};
4302 }
4303 }
4304 break;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004305 }
4306 if (pkgList != null && (pkgList.length > 0)) {
4307 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004308 if (uid >= 0) {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004309 // package-removed and package-restarted case
4310 mAppWakeupHistory.removeForPackage(pkg, UserHandle.getUserId(uid));
Christopher Tate1d99c392017-12-07 16:54:04 -08004311 removeLocked(uid);
4312 } else {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004313 // external-applications-unavailable case
Christopher Tate1d99c392017-12-07 16:54:04 -08004314 removeLocked(pkg);
4315 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004316 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004317 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4318 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4319 if (uidStats.remove(pkg) != null) {
4320 if (uidStats.size() <= 0) {
4321 mBroadcastStats.removeAt(i);
4322 }
4323 }
4324 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326 }
4327 }
4328 }
4329 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004330
4331 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004332 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004333 }
4334
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004335 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004336 if (disabled) {
4337 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004338 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004339 }
4340
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004341 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004342 }
4343
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004344 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004345 if (disabled) {
4346 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004347 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004348 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004349
4350 @Override public void onUidCachedChanged(int uid, boolean cached) {
4351 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004352 };
4353
Suprabh Shukla75edab12018-01-29 14:09:06 -08004354 /**
4355 * Tracking of app assignments to standby buckets
4356 */
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004357 private final class AppStandbyTracker extends
4358 UsageStatsManagerInternal.AppIdleStateChangeListener {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004359 @Override
4360 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004361 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004362 if (DEBUG_STANDBY) {
4363 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4364 bucket);
4365 }
4366 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004367 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4368 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004369 }
4370
4371 @Override
4372 public void onParoleStateChanged(boolean isParoleOn) {
4373 if (DEBUG_STANDBY) {
4374 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4375 }
4376 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4377 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4378 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4379 Boolean.valueOf(isParoleOn)).sendToTarget();
4380 }
4381 };
4382
Makoto Onuki2206af32017-11-21 16:25:35 -08004383 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004384 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004385 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004386 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004387 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004388 }
4389 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004390
4391 @Override
4392 public void unblockAlarmsForUid(int uid) {
4393 synchronized (mLock) {
4394 sendPendingBackgroundAlarmsLocked(uid, null);
4395 }
4396 }
4397
4398 @Override
4399 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4400 synchronized (mLock) {
4401 sendPendingBackgroundAlarmsLocked(uid, packageName);
4402 }
4403 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004404
4405 @Override
4406 public void onUidForeground(int uid, boolean foreground) {
4407 synchronized (mLock) {
4408 if (foreground) {
4409 mUseAllowWhileIdleShortTime.put(uid, true);
4410
4411 // Note we don't have to drain the pending while-idle alarms here, because
4412 // this event should coincide with unblockAlarmsForUid().
4413 }
4414 }
4415 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004416 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004417
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004418 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004419 String pkg = pi.getCreatorPackage();
4420 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004421 return getStatsLocked(uid, pkg);
4422 }
4423
4424 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004425 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4426 if (uidStats == null) {
4427 uidStats = new ArrayMap<String, BroadcastStats>();
4428 mBroadcastStats.put(uid, uidStats);
4429 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004430 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004431 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004432 bs = new BroadcastStats(uid, pkgName);
4433 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004434 }
4435 return bs;
4436 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004437
Christopher Tate21e9f192017-08-08 13:49:11 -07004438 /**
4439 * Canonical count of (operation.send() - onSendFinished()) and
4440 * listener send/complete/timeout invocations.
4441 * Guarded by the usual lock.
4442 */
4443 @GuardedBy("mLock")
4444 private int mSendCount = 0;
4445 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004446 private int mSendFinishCount = 0;
4447 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004448 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004449 @GuardedBy("mLock")
4450 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004451
Christopher Tate14a7bb02015-10-01 10:24:31 -07004452 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004453
Christopher Tate14a7bb02015-10-01 10:24:31 -07004454 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4455 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tate2f558d22019-01-17 16:58:31 -08004456 final InFlight inflight = mInFlight.get(i);
4457 if (inflight.mPendingIntent == pi) {
4458 if (pi.isBroadcast()) {
4459 notifyBroadcastAlarmCompleteLocked(inflight.mUid);
4460 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004461 return mInFlight.remove(i);
4462 }
4463 }
4464 mLog.w("No in-flight alarm for " + pi + " " + intent);
4465 return null;
4466 }
4467
4468 private InFlight removeLocked(IBinder listener) {
4469 for (int i = 0; i < mInFlight.size(); i++) {
4470 if (mInFlight.get(i).mListener == listener) {
4471 return mInFlight.remove(i);
4472 }
4473 }
4474 mLog.w("No in-flight alarm for listener " + listener);
4475 return null;
4476 }
4477
4478 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004479 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004480 BroadcastStats bs = inflight.mBroadcastStats;
4481 bs.nesting--;
4482 if (bs.nesting <= 0) {
4483 bs.nesting = 0;
4484 bs.aggregateTime += nowELAPSED - bs.startTime;
4485 }
4486 FilterStats fs = inflight.mFilterStats;
4487 fs.nesting--;
4488 if (fs.nesting <= 0) {
4489 fs.nesting = 0;
4490 fs.aggregateTime += nowELAPSED - fs.startTime;
4491 }
4492 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004493 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4494 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004495 }
4496 }
4497
4498 private void updateTrackingLocked(InFlight inflight) {
4499 if (inflight != null) {
4500 updateStatsLocked(inflight);
4501 }
4502 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004503 if (DEBUG_WAKELOCK) {
4504 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4505 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004506 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004507 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004508 mWakeLock.release();
4509 if (mInFlight.size() > 0) {
4510 mLog.w("Finished all dispatches with " + mInFlight.size()
4511 + " remaining inflights");
4512 for (int i=0; i<mInFlight.size(); i++) {
4513 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4514 }
4515 mInFlight.clear();
4516 }
4517 } else {
4518 // the next of our alarms is now in flight. reattribute the wakelock.
4519 if (mInFlight.size() > 0) {
4520 InFlight inFlight = mInFlight.get(0);
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004521 setWakelockWorkSource(inFlight.mWorkSource, inFlight.mCreatorUid, inFlight.mTag,
4522 false);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004523 } else {
4524 // should never happen
4525 mLog.w("Alarm wakelock still held but sent queue empty");
4526 mWakeLock.setWorkSource(null);
4527 }
4528 }
4529 }
4530
4531 /**
4532 * Callback that arrives when a direct-call alarm reports that delivery has finished
4533 */
4534 @Override
4535 public void alarmComplete(IBinder who) {
4536 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004537 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004538 + " pid=" + Binder.getCallingPid());
4539 return;
4540 }
4541
4542 final long ident = Binder.clearCallingIdentity();
4543 try {
4544 synchronized (mLock) {
4545 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4546 InFlight inflight = removeLocked(who);
4547 if (inflight != null) {
4548 if (DEBUG_LISTENER_CALLBACK) {
4549 Slog.i(TAG, "alarmComplete() from " + who);
4550 }
4551 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004552 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004553 } else {
4554 // Delivery timed out, and the timeout handling already took care of
4555 // updating our tracking here, so we needn't do anything further.
4556 if (DEBUG_LISTENER_CALLBACK) {
4557 Slog.i(TAG, "Late alarmComplete() from " + who);
4558 }
4559 }
4560 }
4561 } finally {
4562 Binder.restoreCallingIdentity(ident);
4563 }
4564 }
4565
4566 /**
4567 * Callback that arrives when a PendingIntent alarm has finished delivery
4568 */
4569 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004570 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4571 String resultData, Bundle resultExtras) {
4572 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004573 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004574 updateTrackingLocked(removeLocked(pi, intent));
4575 }
4576 }
4577
4578 /**
4579 * Timeout of a direct-call alarm delivery
4580 */
4581 public void alarmTimedOut(IBinder who) {
4582 synchronized (mLock) {
4583 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004584 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004585 // TODO: implement ANR policy for the target
4586 if (DEBUG_LISTENER_CALLBACK) {
4587 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004588 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004589 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004590 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004591 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004592 if (DEBUG_LISTENER_CALLBACK) {
4593 Slog.i(TAG, "Spurious timeout of listener " + who);
4594 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004595 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004596 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004597 }
4598 }
4599
4600 /**
4601 * Deliver an alarm and set up the post-delivery handling appropriately
4602 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004603 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004604 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004605 final long workSourceToken = ThreadLocalWorkSource.setUid(
4606 getAlarmAttributionUid(alarm));
4607 try {
4608 if (alarm.operation != null) {
4609 // PendingIntent alarm
4610 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004611
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004612 try {
4613 alarm.operation.send(getContext(), 0,
4614 mBackgroundIntent.putExtra(
4615 Intent.EXTRA_ALARM_COUNT, alarm.count),
4616 mDeliveryTracker, mHandler, null,
4617 allowWhileIdle ? mIdleOptions : null);
4618 } catch (PendingIntent.CanceledException e) {
4619 if (alarm.repeatInterval > 0) {
4620 // This IntentSender is no longer valid, but this
4621 // is a repeating alarm, so toss it
4622 removeImpl(alarm.operation, null);
4623 }
4624 // No actual delivery was possible, so the delivery tracker's
4625 // 'finished' callback won't be invoked. We also don't need
4626 // to do any wakelock or stats tracking, so we have nothing
4627 // left to do here but go on to the next thing.
4628 mSendFinishCount++;
4629 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004630 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004631 } else {
4632 // Direct listener callback alarm
4633 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004634
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004635 if (RECORD_ALARMS_IN_HISTORY) {
4636 if (alarm.listener == mTimeTickTrigger) {
4637 mTickHistory[mNextTickHistory++] = nowELAPSED;
4638 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4639 mNextTickHistory = 0;
4640 }
Christopher Tatec8b7f432018-09-28 16:23:10 -07004641 }
4642 }
Christopher Tatec8b7f432018-09-28 16:23:10 -07004643
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004644 try {
4645 if (DEBUG_LISTENER_CALLBACK) {
4646 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4647 + " listener=" + alarm.listener.asBinder());
4648 }
4649 alarm.listener.doAlarm(this);
4650 mHandler.sendMessageDelayed(
4651 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4652 alarm.listener.asBinder()),
4653 mConstants.LISTENER_TIMEOUT);
4654 } catch (Exception e) {
4655 if (DEBUG_LISTENER_CALLBACK) {
4656 Slog.i(TAG, "Alarm undeliverable to listener "
4657 + alarm.listener.asBinder(), e);
4658 }
4659 // As in the PendingIntent.CanceledException case, delivery of the
4660 // alarm was not possible, so we have no wakelock or timeout or
4661 // stats management to do. It threw before we posted the delayed
4662 // timeout message, so we're done here.
4663 mListenerFinishCount++;
4664 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004665 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004666 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004667 } finally {
4668 ThreadLocalWorkSource.restore(workSourceToken);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004669 }
4670
4671 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004672 if (DEBUG_WAKELOCK) {
4673 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4674 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004675 if (mBroadcastRefCount == 0) {
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004676 setWakelockWorkSource(alarm.workSource, alarm.creatorUid, alarm.statsTag, true);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004677 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004678 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004679 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004680 final InFlight inflight = new InFlight(AlarmManagerService.this, alarm, nowELAPSED);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004681 mInFlight.add(inflight);
4682 mBroadcastRefCount++;
Christopher Tate2f558d22019-01-17 16:58:31 -08004683 if (inflight.isBroadcast()) {
4684 notifyBroadcastAlarmPendingLocked(alarm.uid);
4685 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004686 if (allowWhileIdle) {
4687 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004688 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004689 if ((mAppStateTracker == null)
4690 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004691 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4692 } else {
4693 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4694 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004695 if (RECORD_DEVICE_IDLE_ALARMS) {
4696 IdleDispatchEntry ent = new IdleDispatchEntry();
4697 ent.uid = alarm.uid;
4698 ent.pkg = alarm.packageName;
4699 ent.tag = alarm.statsTag;
4700 ent.op = "DELIVER";
4701 ent.elapsedRealtime = nowELAPSED;
4702 mAllowWhileIdleDispatches.add(ent);
4703 }
4704 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004705 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004706 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4707 UserHandle.getUserId(alarm.creatorUid));
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004708 mAppWakeupHistory.recordAlarmForPackage(alarm.sourcePackage,
4709 UserHandle.getUserId(alarm.creatorUid), nowELAPSED);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004710 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004711
4712 final BroadcastStats bs = inflight.mBroadcastStats;
4713 bs.count++;
4714 if (bs.nesting == 0) {
4715 bs.nesting = 1;
4716 bs.startTime = nowELAPSED;
4717 } else {
4718 bs.nesting++;
4719 }
4720 final FilterStats fs = inflight.mFilterStats;
4721 fs.count++;
4722 if (fs.nesting == 0) {
4723 fs.nesting = 1;
4724 fs.startTime = nowELAPSED;
4725 } else {
4726 fs.nesting++;
4727 }
4728 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4729 || alarm.type == RTC_WAKEUP) {
4730 bs.numWakeup++;
4731 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004732 ActivityManager.noteWakeupAlarm(
4733 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4734 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004735 }
4736 }
4737 }
mswest463f4c99d2018-02-01 10:13:10 -08004738
4739 private class ShellCmd extends ShellCommand {
4740
4741 IAlarmManager getBinderService() {
4742 return IAlarmManager.Stub.asInterface(mService);
4743 }
4744
4745 @Override
4746 public int onCommand(String cmd) {
4747 if (cmd == null) {
4748 return handleDefaultCommands(cmd);
4749 }
4750
4751 final PrintWriter pw = getOutPrintWriter();
4752 try {
4753 switch (cmd) {
4754 case "set-time":
4755 final long millis = Long.parseLong(getNextArgRequired());
4756 return (getBinderService().setTime(millis)) ? 0 : -1;
4757 case "set-timezone":
4758 final String tz = getNextArgRequired();
4759 getBinderService().setTimeZone(tz);
4760 return 0;
4761 default:
4762 return handleDefaultCommands(cmd);
4763 }
4764 } catch (Exception e) {
4765 pw.println(e);
4766 }
4767 return -1;
4768 }
4769
4770 @Override
4771 public void onHelp() {
4772 PrintWriter pw = getOutPrintWriter();
4773 pw.println("Alarm manager service (alarm) commands:");
4774 pw.println(" help");
4775 pw.println(" Print this help text.");
4776 pw.println(" set-time TIME");
4777 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4778 pw.println(" since the Epoch.");
4779 pw.println(" set-timezone TZ");
4780 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4781 }
4782 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004783}