blob: 69b4945f195237dfe32ebcef9b25cf7b1b72dfbd [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;
Tim Murray175c0f92017-11-28 15:01:04 -080067import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070068import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070069import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020070import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080071import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020073import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080074import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080075import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080076import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070077import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020078import android.util.Log;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -080079import android.util.LongArrayQueue;
Jeff Sharkey9911a282018-02-14 22:29:11 -070080import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080081import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080082import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080083import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020084import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070085import android.util.SparseLongArray;
Bookatz7948c872018-09-04 12:58:33 -070086import android.util.StatsLog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070087import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070088import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Jeff Sharkey9911a282018-02-14 22:29:11 -070090import com.android.internal.annotations.GuardedBy;
91import com.android.internal.annotations.VisibleForTesting;
92import com.android.internal.util.ArrayUtils;
93import com.android.internal.util.DumpUtils;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -080094import com.android.internal.util.IndentingPrintWriter;
Jeff Sharkey9911a282018-02-14 22:29:11 -070095import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070096import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070097import com.android.server.AppStateTracker.Listener;
98
Christopher Tate4cb338d2013-07-26 13:11:31 -070099import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.io.FileDescriptor;
101import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700102import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700103import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800105import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800106import java.util.Calendar;
107import java.util.Collections;
108import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500109import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700110import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700111import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200112import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700113import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800114import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400115import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800116import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800117
Makoto Onuki2206af32017-11-21 16:25:35 -0800118/**
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700119 * Alarm manager implementation.
Makoto Onuki2206af32017-11-21 16:25:35 -0800120 *
121 * Unit test:
122 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
123 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700125 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
126 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700128 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final int TIME_CHANGED_MASK = 1 << 16;
130 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800131
Christopher Tatee0a22b32013-07-11 14:43:13 -0700132 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800133 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800134
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 static final boolean localLOGV = false;
137 static final boolean DEBUG_BATCH = localLOGV || false;
138 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200139 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800141 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700142 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800143 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700144 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700145 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800146 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200147
Christopher Tatec8b7f432018-09-28 16:23:10 -0700148 static final int TICK_HISTORY_DEPTH = 10;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800149 static final long MILLIS_IN_DAY = 24 * 60 * 60 * 1000;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700150
Christopher Tatef2159712018-03-27 16:04:14 -0700151 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
152 static final int ACTIVE_INDEX = 0;
153 static final int WORKING_INDEX = 1;
154 static final int FREQUENT_INDEX = 2;
155 static final int RARE_INDEX = 3;
156 static final int NEVER_INDEX = 4;
157
Christopher Tate14a7bb02015-10-01 10:24:31 -0700158 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800160 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700161
Adam Lesinski182f73f2013-12-05 16:48:06 -0800162 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700163
Christopher Tate24cd46f2016-02-02 14:28:01 -0800164 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
165 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700166 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
167 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200168
Adam Lesinski182f73f2013-12-05 16:48:06 -0800169 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800170
Christopher Tate14a7bb02015-10-01 10:24:31 -0700171 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800172 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800173 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700174
Adam Lesinski182f73f2013-12-05 16:48:06 -0800175 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800176
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700177 // List of alarms per uid deferred due to user applied background restrictions on the source app
178 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800179 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700180 private long mNextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -0700181 private long mNextWakeUpSetAt;
182 private long mNextNonWakeUpSetAt;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700183 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800184 private long mLastTrigger;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700185
Christopher Tate12cf0b62018-01-05 18:40:14 -0800186 private long mLastTickSet;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800187 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800188 private long mLastTickAdded;
189 private long mLastTickRemoved;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700190 // ring buffer of recent TIME_TICK issuance, in the elapsed timebase
191 private final long[] mTickHistory = new long[TICK_HISTORY_DEPTH];
192 private int mNextTickHistory;
193
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700194 private final Injector mInjector;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800195 int mBroadcastRefCount = 0;
196 PowerManager.WakeLock mWakeLock;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700197 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
198 ArrayList<InFlight> mInFlight = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700199 AlarmHandler mHandler;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800200 AppWakeupHistory mAppWakeupHistory;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800201 ClockReceiver mClockReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700202 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Christopher Tatec8b7f432018-09-28 16:23:10 -0700203 Intent mTimeTickIntent;
204 IAlarmListener mTimeTickTrigger;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800205 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700206 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700207 boolean mInteractive = true;
208 long mNonInteractiveStartTime;
209 long mNonInteractiveTime;
210 long mLastAlarmDeliveryTime;
211 long mStartCurrentDelayTime;
212 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700213 long mLastTimeChangeClockTime;
214 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700215 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800216
Christopher Tatebb9cce52017-04-18 14:19:43 -0700217 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
218
219 /**
220 * This permission must be defined by the canonical System UI package,
221 * with protection level "signature".
222 */
223 private static final String SYSTEM_UI_SELF_PERMISSION =
224 "android.permission.systemui.IDENTITY";
225
226 /**
227 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
228 */
229 int mSystemUiUid;
230
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700231 /**
232 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700233 * used to determine the earliest we can dispatch the next such alarm. Times are in the
234 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700235 */
236 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
237
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800238 /**
239 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
240 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
241 */
242 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
243
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700244 final static class IdleDispatchEntry {
245 int uid;
246 String pkg;
247 String tag;
248 String op;
249 long elapsedRealtime;
250 long argRealtime;
251 }
252 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
253
Suprabh Shukla75edab12018-01-29 14:09:06 -0800254 interface Stats {
255 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800256 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800257 }
258
259 private final StatLogger mStatLogger = new StatLogger(new String[] {
260 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800261 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800262 });
263
Dianne Hackborna750a632015-06-16 17:18:23 -0700264 /**
265 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
266 */
267 Bundle mIdleOptions;
268
Jose Lima235510e2014-08-13 12:50:01 -0700269 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
270 new SparseArray<>();
271 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
272 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200273 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
274 new SparseBooleanArray();
275 private boolean mNextAlarmClockMayChange;
276
277 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700278 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
279 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200280
Makoto Onukie4918212018-02-06 11:30:15 -0800281 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800282 private boolean mAppStandbyParole;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800283
284 /**
285 * A rolling window history of previous times when an alarm was sent to a package.
286 */
287 private static class AppWakeupHistory {
288 private ArrayMap<Pair<String, Integer>, LongArrayQueue> mPackageHistory =
289 new ArrayMap<>();
290 private long mWindowSize;
291
292 AppWakeupHistory(long windowSize) {
293 mWindowSize = windowSize;
294 }
295
296 void recordAlarmForPackage(String packageName, int userId, long nowElapsed) {
297 final Pair<String, Integer> packageUser = Pair.create(packageName, userId);
298 LongArrayQueue history = mPackageHistory.get(packageUser);
299 if (history == null) {
300 history = new LongArrayQueue();
301 mPackageHistory.put(packageUser, history);
302 }
303 if (history.size() == 0 || history.peekLast() < nowElapsed) {
304 history.addLast(nowElapsed);
305 }
306 snapToWindow(history);
307 }
308
309 void removeForUser(int userId) {
310 for (int i = mPackageHistory.size() - 1; i >= 0; i--) {
311 final Pair<String, Integer> packageUserKey = mPackageHistory.keyAt(i);
312 if (packageUserKey.second == userId) {
313 mPackageHistory.removeAt(i);
314 }
315 }
316 }
317
318 void removeForPackage(String packageName, int userId) {
319 final Pair<String, Integer> packageUser = Pair.create(packageName, userId);
320 mPackageHistory.remove(packageUser);
321 }
322
323 private void snapToWindow(LongArrayQueue history) {
324 while (history.peekFirst() + mWindowSize < history.peekLast()) {
325 history.removeFirst();
326 }
327 }
328
329 int getTotalWakeupsInWindow(String packageName, int userId) {
330 final LongArrayQueue history = mPackageHistory.get(Pair.create(packageName, userId));
331 return (history == null) ? 0 : history.size();
332 }
333
334 long getLastWakeupForPackage(String packageName, int userId, int positionFromEnd) {
335 final LongArrayQueue history = mPackageHistory.get(Pair.create(packageName, userId));
336 if (history == null) {
337 return 0;
338 }
339 final int i = history.size() - positionFromEnd;
340 return (i < 0) ? 0 : history.get(i);
341 }
342
343 void dump(PrintWriter pw, String prefix, long nowElapsed) {
344 dump(new IndentingPrintWriter(pw, " ").setIndent(prefix), nowElapsed);
345 }
346
347 void dump(IndentingPrintWriter pw, long nowElapsed) {
348 pw.println("App Alarm history:");
349 pw.increaseIndent();
350 for (int i = 0; i < mPackageHistory.size(); i++) {
351 final Pair<String, Integer> packageUser = mPackageHistory.keyAt(i);
352 final LongArrayQueue timestamps = mPackageHistory.valueAt(i);
353 pw.print(packageUser.first);
354 pw.print(", u");
355 pw.print(packageUser.second);
356 pw.print(": ");
357 // limit dumping to a max of 100 values
358 final int lastIdx = Math.max(0, timestamps.size() - 100);
359 for (int j = timestamps.size() - 1; j >= lastIdx; j--) {
360 TimeUtils.formatDuration(timestamps.get(j), nowElapsed, pw);
361 pw.print(", ");
362 }
363 pw.println();
364 }
365 pw.decreaseIndent();
366 }
367 }
Makoto Onuki2206af32017-11-21 16:25:35 -0800368
Dianne Hackborna750a632015-06-16 17:18:23 -0700369 /**
370 * All times are in milliseconds. These constants are kept synchronized with the system
371 * global Settings. Any access to this class or its fields should be done while
372 * holding the AlarmManagerService.mLock lock.
373 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700374 @VisibleForTesting
375 final class Constants extends ContentObserver {
Dianne Hackborna750a632015-06-16 17:18:23 -0700376 // Key names stored in the settings value.
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700377 @VisibleForTesting
378 static final String KEY_MIN_FUTURITY = "min_futurity";
379 @VisibleForTesting
380 static final String KEY_MIN_INTERVAL = "min_interval";
381 @VisibleForTesting
382 static final String KEY_MAX_INTERVAL = "max_interval";
383 @VisibleForTesting
384 static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
385 @VisibleForTesting
386 static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
387 @VisibleForTesting
388 static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
Dianne Hackborna750a632015-06-16 17:18:23 -0700389 = "allow_while_idle_whitelist_duration";
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700390 @VisibleForTesting
391 static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800392 @VisibleForTesting
393 static final String KEY_APP_STANDBY_QUOTAS_ENABLED = "app_standby_quotas_enabled";
394 private static final String KEY_APP_STANDBY_WINDOW = "app_standby_window";
395 @VisibleForTesting
396 final String[] KEYS_APP_STANDBY_QUOTAS = {
397 "standby_active_quota",
398 "standby_working_quota",
399 "standby_frequent_quota",
400 "standby_rare_quota",
401 "standby_never_quota",
402 };
Dianne Hackborna750a632015-06-16 17:18:23 -0700403
Suprabh Shukla75edab12018-01-29 14:09:06 -0800404 // Keys for specifying throttling delay based on app standby bucketing
405 private final String[] KEYS_APP_STANDBY_DELAY = {
406 "standby_active_delay",
407 "standby_working_delay",
408 "standby_frequent_delay",
409 "standby_rare_delay",
410 "standby_never_delay",
411 };
412
Dianne Hackborna750a632015-06-16 17:18:23 -0700413 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
414 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800415 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700416 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700417 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700418 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700419 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800420 private static final boolean DEFAULT_APP_STANDBY_QUOTAS_ENABLED = true;
421 private static final long DEFAULT_APP_STANDBY_WINDOW = 60 * 60 * 1000; // 1 hr
422 /**
423 * Max number of times an app can receive alarms in {@link #APP_STANDBY_WINDOW}
424 */
425 private final int[] DEFAULT_APP_STANDBY_QUOTAS = {
426 720, // Active
427 10, // Working
428 2, // Frequent
429 1, // Rare
430 0 // Never
431 };
Suprabh Shukla75edab12018-01-29 14:09:06 -0800432 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
433 0, // Active
434 6 * 60_000, // Working
435 30 * 60_000, // Frequent
436 2 * 60 * 60_000, // Rare
437 10 * 24 * 60 * 60_000 // Never
438 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700439
Dianne Hackborna750a632015-06-16 17:18:23 -0700440 // Minimum futurity of a new alarm
441 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
442
443 // Minimum alarm recurrence interval
444 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
445
Christopher Tate22e919d2018-02-16 16:16:50 -0800446 // Maximum alarm recurrence interval
447 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
448
Dianne Hackborna750a632015-06-16 17:18:23 -0700449 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
450 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
451
452 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
453 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
454
455 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
456 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
457 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
458
Christopher Tate14a7bb02015-10-01 10:24:31 -0700459 // Direct alarm listener callback timeout
460 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800461 public boolean APP_STANDBY_QUOTAS_ENABLED = DEFAULT_APP_STANDBY_QUOTAS_ENABLED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700462
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800463 public long APP_STANDBY_WINDOW = DEFAULT_APP_STANDBY_WINDOW;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800464 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800465 public int[] APP_STANDBY_QUOTAS = new int[DEFAULT_APP_STANDBY_QUOTAS.length];
Suprabh Shukla75edab12018-01-29 14:09:06 -0800466
Dianne Hackborna750a632015-06-16 17:18:23 -0700467 private ContentResolver mResolver;
468 private final KeyValueListParser mParser = new KeyValueListParser(',');
469 private long mLastAllowWhileIdleWhitelistDuration = -1;
470
471 public Constants(Handler handler) {
472 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700473 updateAllowWhileIdleWhitelistDurationLocked();
474 }
475
476 public void start(ContentResolver resolver) {
477 mResolver = resolver;
478 mResolver.registerContentObserver(Settings.Global.getUriFor(
479 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
480 updateConstants();
481 }
482
Dianne Hackborna750a632015-06-16 17:18:23 -0700483 public void updateAllowWhileIdleWhitelistDurationLocked() {
484 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
485 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
486 BroadcastOptions opts = BroadcastOptions.makeBasic();
487 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
488 mIdleOptions = opts.toBundle();
489 }
490 }
491
492 @Override
493 public void onChange(boolean selfChange, Uri uri) {
494 updateConstants();
495 }
496
497 private void updateConstants() {
498 synchronized (mLock) {
499 try {
500 mParser.setString(Settings.Global.getString(mResolver,
501 Settings.Global.ALARM_MANAGER_CONSTANTS));
502 } catch (IllegalArgumentException e) {
503 // Failed to parse the settings string, log this and move on
504 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800505 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700506 }
507
508 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
509 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800510 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700511 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
512 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
513 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
514 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
515 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
516 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
517 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700518 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
519 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700520 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
521 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
522 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
523 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800524 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800525 Math.max(APP_STANDBY_MIN_DELAYS[i - 1], DEFAULT_APP_STANDBY_DELAYS[i]));
526 }
527
528 APP_STANDBY_QUOTAS_ENABLED = mParser.getBoolean(KEY_APP_STANDBY_QUOTAS_ENABLED,
529 DEFAULT_APP_STANDBY_QUOTAS_ENABLED);
530
531 APP_STANDBY_WINDOW = mParser.getLong(KEY_APP_STANDBY_WINDOW,
532 DEFAULT_APP_STANDBY_WINDOW);
533 if (APP_STANDBY_WINDOW > DEFAULT_APP_STANDBY_WINDOW) {
534 Slog.w(TAG, "Cannot exceed the app_standby_window size of "
535 + DEFAULT_APP_STANDBY_WINDOW);
536 APP_STANDBY_WINDOW = DEFAULT_APP_STANDBY_WINDOW;
537 } else if (APP_STANDBY_WINDOW < DEFAULT_APP_STANDBY_WINDOW) {
538 // Not recommended outside of testing.
539 Slog.w(TAG, "Using a non-default app_standby_window of " + APP_STANDBY_WINDOW);
540 }
541
542 APP_STANDBY_QUOTAS[ACTIVE_INDEX] = mParser.getInt(
543 KEYS_APP_STANDBY_QUOTAS[ACTIVE_INDEX],
544 DEFAULT_APP_STANDBY_QUOTAS[ACTIVE_INDEX]);
545 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_QUOTAS.length; i++) {
546 APP_STANDBY_QUOTAS[i] = mParser.getInt(KEYS_APP_STANDBY_QUOTAS[i],
547 Math.min(APP_STANDBY_QUOTAS[i - 1], DEFAULT_APP_STANDBY_QUOTAS[i]));
Suprabh Shukla75edab12018-01-29 14:09:06 -0800548 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700549 updateAllowWhileIdleWhitelistDurationLocked();
550 }
551 }
552
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800553 void dump(PrintWriter pw, String prefix) {
554 dump(new IndentingPrintWriter(pw, " ").setIndent(prefix));
555 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700556
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800557 void dump(IndentingPrintWriter pw) {
558 pw.println("Settings:");
559
560 pw.increaseIndent();
561
562 pw.print(KEY_MIN_FUTURITY); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700563 TimeUtils.formatDuration(MIN_FUTURITY, pw);
564 pw.println();
565
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800566 pw.print(KEY_MIN_INTERVAL); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700567 TimeUtils.formatDuration(MIN_INTERVAL, pw);
568 pw.println();
569
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800570 pw.print(KEY_MAX_INTERVAL); pw.print("=");
Christopher Tate22e919d2018-02-16 16:16:50 -0800571 TimeUtils.formatDuration(MAX_INTERVAL, pw);
572 pw.println();
573
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800574 pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
Christopher Tate14a7bb02015-10-01 10:24:31 -0700575 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
576 pw.println();
577
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800578 pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700579 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
580 pw.println();
581
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800582 pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700583 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
584 pw.println();
585
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800586 pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
Dianne Hackborna750a632015-06-16 17:18:23 -0700587 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
588 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800589
590 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800591 pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
Suprabh Shukla75edab12018-01-29 14:09:06 -0800592 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
593 pw.println();
594 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -0800595
596 pw.print(KEY_APP_STANDBY_QUOTAS_ENABLED); pw.print("=");
597 pw.println(APP_STANDBY_QUOTAS_ENABLED);
598
599 pw.print(KEY_APP_STANDBY_WINDOW); pw.print("=");
600 TimeUtils.formatDuration(APP_STANDBY_WINDOW, pw);
601 pw.println();
602
603 for (int i = 0; i < KEYS_APP_STANDBY_QUOTAS.length; i++) {
604 pw.print(KEYS_APP_STANDBY_QUOTAS[i]); pw.print("=");
605 pw.println(APP_STANDBY_QUOTAS[i]);
606 }
607
608 pw.decreaseIndent();
Dianne Hackborna750a632015-06-16 17:18:23 -0700609 }
Kweku Adams61e03292017-10-19 14:27:12 -0700610
611 void dumpProto(ProtoOutputStream proto, long fieldId) {
612 final long token = proto.start(fieldId);
613
614 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
615 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800616 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700617 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
618 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
619 ALLOW_WHILE_IDLE_SHORT_TIME);
620 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
621 ALLOW_WHILE_IDLE_LONG_TIME);
622 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
623 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
624
625 proto.end(token);
626 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700627 }
628
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700629 Constants mConstants;
Dianne Hackborna750a632015-06-16 17:18:23 -0700630
Christopher Tate1590f1e2014-10-02 17:27:57 -0700631 // Alarm delivery ordering bookkeeping
632 static final int PRIO_TICK = 0;
633 static final int PRIO_WAKEUP = 1;
634 static final int PRIO_NORMAL = 2;
635
Dianne Hackborna750a632015-06-16 17:18:23 -0700636 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700637 int seq;
638 int priority;
639
640 PriorityClass() {
641 seq = mCurrentSeq - 1;
642 priority = PRIO_NORMAL;
643 }
644 }
645
Dianne Hackborna750a632015-06-16 17:18:23 -0700646 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700647 int mCurrentSeq = 0;
648
Dianne Hackborna750a632015-06-16 17:18:23 -0700649 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700650 public long when;
651 public int uid;
652 public String action;
653
654 public WakeupEvent(long theTime, int theUid, String theAction) {
655 when = theTime;
656 uid = theUid;
657 action = theAction;
658 }
659 }
660
Adam Lesinski182f73f2013-12-05 16:48:06 -0800661 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
662 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700663
Adrian Roosc42a1e12014-07-07 23:35:53 +0200664 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700665 long start; // These endpoints are always in ELAPSED
666 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700667 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700668
669 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
670
671 Batch() {
672 start = 0;
673 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700674 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700675 }
676
677 Batch(Alarm seed) {
678 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800679 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700680 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700681 alarms.add(seed);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700682 if (seed.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700683 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800684 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700685 }
686
687 int size() {
688 return alarms.size();
689 }
690
691 Alarm get(int index) {
692 return alarms.get(index);
693 }
694
695 boolean canHold(long whenElapsed, long maxWhen) {
696 return (end >= whenElapsed) && (start <= maxWhen);
697 }
698
699 boolean add(Alarm alarm) {
700 boolean newStart = false;
701 // narrows the batch if necessary; presumes that canHold(alarm) is true
702 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
703 if (index < 0) {
704 index = 0 - index - 1;
705 }
706 alarms.add(index, alarm);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700707 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700708 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800709 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700710 if (DEBUG_BATCH) {
711 Slog.v(TAG, "Adding " + alarm + " to " + this);
712 }
713 if (alarm.whenElapsed > start) {
714 start = alarm.whenElapsed;
715 newStart = true;
716 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700717 if (alarm.maxWhenElapsed < end) {
718 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700720 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700721
722 if (DEBUG_BATCH) {
723 Slog.v(TAG, " => now " + this);
724 }
725 return newStart;
726 }
727
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800728 boolean remove(Alarm alarm) {
729 return remove(a -> (a == alarm));
730 }
731
Christopher Tate1d99c392017-12-07 16:54:04 -0800732 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700733 boolean didRemove = false;
734 long newStart = 0; // recalculate endpoints as we go
735 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700736 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700737 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700738 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800739 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700740 alarms.remove(i);
741 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200742 if (alarm.alarmClock != null) {
743 mNextAlarmClockMayChange = true;
744 }
Christopher Tatec8b7f432018-09-28 16:23:10 -0700745 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700746 mLastTickRemoved = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800747 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700748 } else {
749 if (alarm.whenElapsed > newStart) {
750 newStart = alarm.whenElapsed;
751 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700752 if (alarm.maxWhenElapsed < newEnd) {
753 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700754 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700755 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700756 i++;
757 }
758 }
759 if (didRemove) {
760 // commit the new batch bounds
761 start = newStart;
762 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700763 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700764 }
765 return didRemove;
766 }
767
Christopher Tatee0a22b32013-07-11 14:43:13 -0700768 boolean hasPackage(final String packageName) {
769 final int N = alarms.size();
770 for (int i = 0; i < N; i++) {
771 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700772 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700773 return true;
774 }
775 }
776 return false;
777 }
778
779 boolean hasWakeups() {
780 final int N = alarms.size();
781 for (int i = 0; i < N; i++) {
782 Alarm a = alarms.get(i);
783 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
784 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
785 return true;
786 }
787 }
788 return false;
789 }
790
791 @Override
792 public String toString() {
793 StringBuilder b = new StringBuilder(40);
794 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
795 b.append(" num="); b.append(size());
796 b.append(" start="); b.append(start);
797 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700798 if (flags != 0) {
799 b.append(" flgs=0x");
800 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700801 }
802 b.append('}');
803 return b.toString();
804 }
Kweku Adams61e03292017-10-19 14:27:12 -0700805
806 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
807 long nowRTC) {
808 final long token = proto.start(fieldId);
809
810 proto.write(BatchProto.START_REALTIME, start);
811 proto.write(BatchProto.END_REALTIME, end);
812 proto.write(BatchProto.FLAGS, flags);
813 for (Alarm a : alarms) {
814 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
815 }
816
817 proto.end(token);
818 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700819 }
820
821 static class BatchTimeOrder implements Comparator<Batch> {
822 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800823 long when1 = b1.start;
824 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800825 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700826 return 1;
827 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800828 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700829 return -1;
830 }
831 return 0;
832 }
833 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800834
835 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
836 @Override
837 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700838 // priority class trumps everything. TICK < WAKEUP < NORMAL
839 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
840 return -1;
841 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
842 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800843 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700844
845 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800846 if (lhs.whenElapsed < rhs.whenElapsed) {
847 return -1;
848 } else if (lhs.whenElapsed > rhs.whenElapsed) {
849 return 1;
850 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700851
852 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800853 return 0;
854 }
855 };
856
Christopher Tate1590f1e2014-10-02 17:27:57 -0700857 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
858 final int N = alarms.size();
859 for (int i = 0; i < N; i++) {
860 Alarm a = alarms.get(i);
861
862 final int alarmPrio;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700863 if (a.listener == mTimeTickTrigger) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700864 alarmPrio = PRIO_TICK;
865 } else if (a.wakeup) {
866 alarmPrio = PRIO_WAKEUP;
867 } else {
868 alarmPrio = PRIO_NORMAL;
869 }
870
871 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800872 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700873 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700874 if (packagePrio == null) {
875 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700876 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700877 }
878 a.priorityClass = packagePrio;
879
880 if (packagePrio.seq != mCurrentSeq) {
881 // first alarm we've seen in the current delivery generation from this package
882 packagePrio.priority = alarmPrio;
883 packagePrio.seq = mCurrentSeq;
884 } else {
885 // Multiple alarms from this package being delivered in this generation;
886 // bump the package's delivery class if it's warranted.
887 // TICK < WAKEUP < NORMAL
888 if (alarmPrio < packagePrio.priority) {
889 packagePrio.priority = alarmPrio;
890 }
891 }
892 }
893 }
894
Christopher Tatee0a22b32013-07-11 14:43:13 -0700895 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800896 static final long MIN_FUZZABLE_INTERVAL = 10000;
897 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700898 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
899
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700900 // 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 -0700901 // to run during this time are placed in mPendingWhileIdleAlarms
902 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700903 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700904 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700905
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700906 @VisibleForTesting
907 AlarmManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800908 super(context);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700909 mInjector = injector;
Jeff Brownb880d882014-02-10 19:47:07 -0800910 }
911
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700912 AlarmManagerService(Context context) {
913 this(context, new Injector(context));
914 }
915
916 private long convertToElapsed(long when, int type) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700917 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
918 if (isRtc) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700919 when -= mInjector.getCurrentTimeMillis() - mInjector.getElapsedRealtime();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700920 }
921 return when;
922 }
923
924 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
925 // calculate the end of our nominal delivery window for the alarm.
926 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
927 // Current heuristic: batchable window is 75% of either the recurrence interval
928 // [for a periodic alarm] or of the time from now to the desired delivery time,
929 // with a minimum delay/interval of 10 seconds, under which we will simply not
930 // defer the alarm.
931 long futurity = (interval == 0)
932 ? (triggerAtTime - now)
933 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700934 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700935 futurity = 0;
936 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800937 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700938 }
939
940 // returns true if the batch was added at the head
941 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
942 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
943 if (index < 0) {
944 index = 0 - index - 1;
945 }
946 list.add(index, newBatch);
947 return (index == 0);
948 }
949
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800950 private void insertAndBatchAlarmLocked(Alarm alarm) {
951 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
952 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
953
954 if (whichBatch < 0) {
955 addBatchLocked(mAlarmBatches, new Batch(alarm));
956 } else {
957 final Batch batch = mAlarmBatches.get(whichBatch);
958 if (batch.add(alarm)) {
959 // The start time of this batch advanced, so batch ordering may
960 // have just been broken. Move it to where it now belongs.
961 mAlarmBatches.remove(whichBatch);
962 addBatchLocked(mAlarmBatches, batch);
963 }
964 }
965 }
966
Christopher Tate385e4982013-07-23 18:22:29 -0700967 // Return the index of the matching batch, or -1 if none found.
968 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700969 final int N = mAlarmBatches.size();
970 for (int i = 0; i < N; i++) {
971 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700972 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700973 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700974 }
975 }
Christopher Tate385e4982013-07-23 18:22:29 -0700976 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700977 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800978 /** @return total count of the alarms in a set of alarm batches. */
979 static int getAlarmCount(ArrayList<Batch> batches) {
980 int ret = 0;
981
982 final int size = batches.size();
983 for (int i = 0; i < size; i++) {
984 ret += batches.get(i).size();
985 }
986 return ret;
987 }
988
989 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
990 if (alarms.size() == 0) {
991 return false;
992 }
993 final int batchSize = alarms.size();
994 for (int j = 0; j < batchSize; j++) {
Christopher Tatec8b7f432018-09-28 16:23:10 -0700995 if (alarms.get(j).listener == mTimeTickTrigger) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800996 return true;
997 }
998 }
999 return false;
1000 }
1001
1002 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
1003 final int numBatches = batches.size();
1004 for (int i = 0; i < numBatches; i++) {
1005 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
1006 return true;
1007 }
1008 }
1009 return false;
1010 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001011
1012 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
1013 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001014 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001015 rebatchAllAlarmsLocked(true);
1016 }
1017 }
1018
1019 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001020 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001021 final int oldCount =
1022 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
1023 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
1024 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
1025
Christopher Tate4cb338d2013-07-26 13:11:31 -07001026 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
1027 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001028 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001029 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate4cb338d2013-07-26 13:11:31 -07001030 final int oldBatches = oldSet.size();
1031 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
1032 Batch batch = oldSet.get(batchNum);
1033 final int N = batch.size();
1034 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001035 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001036 }
1037 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001038 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
1039 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
1040 + " to " + mPendingIdleUntil);
1041 if (mPendingIdleUntil == null) {
1042 // Somehow we lost this... we need to restore all of the pending alarms.
1043 restorePendingWhileIdleAlarmsLocked();
1044 }
1045 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08001046 final int newCount =
1047 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
1048 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
1049 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
1050
1051 if (oldCount != newCount) {
1052 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
1053 }
1054 if (oldHasTick != newHasTick) {
1055 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
1056 }
1057
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001058 rescheduleKernelAlarmsLocked();
1059 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -08001060 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001061 }
1062
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001063 /**
1064 * Re-orders the alarm batches based on newly evaluated send times based on the current
1065 * app-standby buckets
1066 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
1067 * null indicates all
1068 * @return True if there was any reordering done to the current list.
1069 */
1070 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
1071 final long start = mStatLogger.getTime();
1072 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
1073
1074 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
1075 final Batch batch = mAlarmBatches.get(batchIndex);
1076 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
1077 final Alarm alarm = batch.get(alarmIndex);
1078 final Pair<String, Integer> packageUser =
1079 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
1080 if (targetPackages != null && !targetPackages.contains(packageUser)) {
1081 continue;
1082 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001083 if (adjustDeliveryTimeBasedOnBucketLocked(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001084 batch.remove(alarm);
1085 rescheduledAlarms.add(alarm);
1086 }
1087 }
1088 if (batch.size() == 0) {
1089 mAlarmBatches.remove(batchIndex);
1090 }
1091 }
1092 for (int i = 0; i < rescheduledAlarms.size(); i++) {
1093 final Alarm a = rescheduledAlarms.get(i);
1094 insertAndBatchAlarmLocked(a);
1095 }
1096
1097 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
1098 return rescheduledAlarms.size() > 0;
1099 }
1100
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001101 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
1102 a.when = a.origWhen;
1103 long whenElapsed = convertToElapsed(a.when, a.type);
1104 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001105 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001106 // Exact
1107 maxElapsed = whenElapsed;
1108 } else {
1109 // Not exact. Preserve any explicit window, otherwise recalculate
1110 // the window based on the alarm's new futurity. Note that this
1111 // reflects a policy of preferring timely to deferred delivery.
1112 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -08001113 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001114 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
1115 }
1116 a.whenElapsed = whenElapsed;
1117 a.maxWhenElapsed = maxElapsed;
1118 setImplLocked(a, true, doValidate);
1119 }
1120
Christopher Tate22e919d2018-02-16 16:16:50 -08001121 static long clampPositive(long val) {
1122 return (val >= 0) ? val : Long.MAX_VALUE;
1123 }
1124
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001125 /**
1126 * Sends alarms that were blocked due to user applied background restrictions - either because
1127 * the user lifted those or the uid came to foreground.
1128 *
1129 * @param uid uid to filter on
1130 * @param packageName package to filter on, or null for all packages in uid
1131 */
1132 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
1133 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
1134 if (alarmsForUid == null || alarmsForUid.size() == 0) {
1135 return;
1136 }
1137 final ArrayList<Alarm> alarmsToDeliver;
1138 if (packageName != null) {
1139 if (DEBUG_BG_LIMIT) {
1140 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
1141 }
1142 alarmsToDeliver = new ArrayList<>();
1143 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
1144 final Alarm a = alarmsForUid.get(i);
1145 if (a.matches(packageName)) {
1146 alarmsToDeliver.add(alarmsForUid.remove(i));
1147 }
1148 }
1149 if (alarmsForUid.size() == 0) {
1150 mPendingBackgroundAlarms.remove(uid);
1151 }
1152 } else {
1153 if (DEBUG_BG_LIMIT) {
1154 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
1155 }
1156 alarmsToDeliver = alarmsForUid;
1157 mPendingBackgroundAlarms.remove(uid);
1158 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001159 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001160 }
1161
Makoto Onuki2206af32017-11-21 16:25:35 -08001162 /**
1163 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
1164 * restricted.
1165 *
1166 * This is only called when the global "force all apps-standby" flag changes or when the
1167 * power save whitelist changes, so it's okay to be slow.
1168 */
1169 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001170 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001171
1172 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1173 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1174
1175 if (alarmsToDeliver.size() > 0) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001176 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Makoto Onuki2206af32017-11-21 16:25:35 -08001177 }
1178 }
1179
1180 @VisibleForTesting
1181 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1182 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1183 Predicate<Alarm> isBackgroundRestricted) {
1184
1185 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1186 final int uid = pendingAlarms.keyAt(uidIndex);
1187 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1188
1189 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1190 final Alarm alarm = alarmsForUid.get(alarmIndex);
1191
1192 if (isBackgroundRestricted.test(alarm)) {
1193 continue;
1194 }
1195
1196 unrestrictedAlarms.add(alarm);
1197 alarmsForUid.remove(alarmIndex);
1198 }
1199
1200 if (alarmsForUid.size() == 0) {
1201 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001202 }
1203 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001204 }
1205
1206 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1207 final int N = alarms.size();
1208 boolean hasWakeup = false;
1209 for (int i = 0; i < N; i++) {
1210 final Alarm alarm = alarms.get(i);
1211 if (alarm.wakeup) {
1212 hasWakeup = true;
1213 }
1214 alarm.count = 1;
1215 // Recurring alarms may have passed several alarm intervals while the
1216 // alarm was kept pending. Send the appropriate trigger count.
1217 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001218 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001219 // Also schedule its next recurrence
1220 final long delta = alarm.count * alarm.repeatInterval;
1221 final long nextElapsed = alarm.whenElapsed + delta;
1222 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1223 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1224 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1225 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1226 // Kernel alarms will be rescheduled as needed in setImplLocked
1227 }
1228 }
1229 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1230 // No need to wakeup for non wakeup alarms
1231 if (mPendingNonWakeupAlarms.size() == 0) {
1232 mStartCurrentDelayTime = nowELAPSED;
1233 mNextNonWakeupDeliveryTime = nowELAPSED
1234 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1235 }
1236 mPendingNonWakeupAlarms.addAll(alarms);
1237 mNumDelayedAlarms += alarms.size();
1238 } else {
1239 if (DEBUG_BG_LIMIT) {
1240 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1241 }
1242 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1243 if (mPendingNonWakeupAlarms.size() > 0) {
1244 alarms.addAll(mPendingNonWakeupAlarms);
1245 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1246 mTotalDelayTime += thisDelayTime;
1247 if (mMaxDelayTime < thisDelayTime) {
1248 mMaxDelayTime = thisDelayTime;
1249 }
1250 mPendingNonWakeupAlarms.clear();
1251 }
1252 calculateDeliveryPriorities(alarms);
1253 Collections.sort(alarms, mAlarmDispatchComparator);
1254 deliverAlarmsLocked(alarms, nowELAPSED);
1255 }
1256 }
1257
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001258 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001259 if (RECORD_DEVICE_IDLE_ALARMS) {
1260 IdleDispatchEntry ent = new IdleDispatchEntry();
1261 ent.uid = 0;
1262 ent.pkg = "FINISH IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001263 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001264 mAllowWhileIdleDispatches.add(ent);
1265 }
1266
Dianne Hackborn35d54032015-04-23 10:30:43 -07001267 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001268 if (mPendingWhileIdleAlarms.size() > 0) {
1269 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1270 mPendingWhileIdleAlarms = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001271 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001272 for (int i=alarms.size() - 1; i >= 0; i--) {
1273 Alarm a = alarms.get(i);
1274 reAddAlarmLocked(a, nowElapsed, false);
1275 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001276 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001277
1278 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001279 rescheduleKernelAlarmsLocked();
1280 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001281
Christopher Tatee0a22b32013-07-11 14:43:13 -07001282 }
1283
Christopher Tate14a7bb02015-10-01 10:24:31 -07001284 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001285 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001286 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001287 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001288 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001289 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001290 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001291 final BroadcastStats mBroadcastStats;
1292 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001293 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001294
Christopher Tate14a7bb02015-10-01 10:24:31 -07001295 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1296 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1297 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001298 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001299 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001300 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001301 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001302 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001303 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001304 mBroadcastStats = (pendingIntent != null)
1305 ? service.getStatsLocked(pendingIntent)
1306 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001307 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001308 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001309 fs = new FilterStats(mBroadcastStats, mTag);
1310 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001311 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001312 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001313 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001314 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001315 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001316
1317 @Override
1318 public String toString() {
1319 return "InFlight{"
1320 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001321 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001322 + ", workSource=" + mWorkSource
1323 + ", uid=" + mUid
1324 + ", tag=" + mTag
1325 + ", broadcastStats=" + mBroadcastStats
1326 + ", filterStats=" + mFilterStats
1327 + ", alarmType=" + mAlarmType
1328 + "}";
1329 }
Kweku Adams61e03292017-10-19 14:27:12 -07001330
1331 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1332 final long token = proto.start(fieldId);
1333
1334 proto.write(InFlightProto.UID, mUid);
1335 proto.write(InFlightProto.TAG, mTag);
1336 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1337 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1338 if (mPendingIntent != null) {
1339 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1340 }
1341 if (mBroadcastStats != null) {
1342 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1343 }
1344 if (mFilterStats != null) {
1345 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1346 }
1347 if (mWorkSource != null) {
1348 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1349 }
1350
1351 proto.end(token);
1352 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001353 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001354
Adam Lesinski182f73f2013-12-05 16:48:06 -08001355 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001356 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001357 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001358
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001359 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001361 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 int numWakeup;
1363 long startTime;
1364 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001365
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001366 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001367 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001368 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001369 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001370
1371 @Override
1372 public String toString() {
1373 return "FilterStats{"
1374 + "tag=" + mTag
1375 + ", lastTime=" + lastTime
1376 + ", aggregateTime=" + aggregateTime
1377 + ", count=" + count
1378 + ", numWakeup=" + numWakeup
1379 + ", startTime=" + startTime
1380 + ", nesting=" + nesting
1381 + "}";
1382 }
Kweku Adams61e03292017-10-19 14:27:12 -07001383
1384 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1385 final long token = proto.start(fieldId);
1386
1387 proto.write(FilterStatsProto.TAG, mTag);
1388 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1389 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1390 proto.write(FilterStatsProto.COUNT, count);
1391 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1392 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1393 proto.write(FilterStatsProto.NESTING, nesting);
1394
1395 proto.end(token);
1396 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001397 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001398
Adam Lesinski182f73f2013-12-05 16:48:06 -08001399 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001400 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001401 final String mPackageName;
1402
1403 long aggregateTime;
1404 int count;
1405 int numWakeup;
1406 long startTime;
1407 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001408 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001409
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001410 BroadcastStats(int uid, String packageName) {
1411 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001412 mPackageName = packageName;
1413 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001414
1415 @Override
1416 public String toString() {
1417 return "BroadcastStats{"
1418 + "uid=" + mUid
1419 + ", packageName=" + mPackageName
1420 + ", aggregateTime=" + aggregateTime
1421 + ", count=" + count
1422 + ", numWakeup=" + numWakeup
1423 + ", startTime=" + startTime
1424 + ", nesting=" + nesting
1425 + "}";
1426 }
Kweku Adams61e03292017-10-19 14:27:12 -07001427
1428 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1429 final long token = proto.start(fieldId);
1430
1431 proto.write(BroadcastStatsProto.UID, mUid);
1432 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1433 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1434 proto.write(BroadcastStatsProto.COUNT, count);
1435 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1436 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1437 proto.write(BroadcastStatsProto.NESTING, nesting);
1438
1439 proto.end(token);
1440 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001441 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001442
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001443 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1444 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001445
1446 int mNumDelayedAlarms = 0;
1447 long mTotalDelayTime = 0;
1448 long mMaxDelayTime = 0;
1449
Adam Lesinski182f73f2013-12-05 16:48:06 -08001450 @Override
1451 public void onStart() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001452 mInjector.init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001453
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001454 synchronized (mLock) {
Suprabh Shukla12bd0162018-11-12 18:00:18 -08001455 mHandler = new AlarmHandler();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001456 mConstants = new Constants(mHandler);
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001457 mAppWakeupHistory = new AppWakeupHistory(Constants.DEFAULT_APP_STANDBY_WINDOW);
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001458
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001459 mNextWakeup = mNextNonWakeup = 0;
1460
1461 // We have to set current TimeZone info to kernel
1462 // because kernel doesn't keep this after reboot
1463 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
1464
Christopher Tate3d65d4d2018-12-11 14:55:19 -08001465 // Ensure that we're booting with a halfway sensible current time. Use the
1466 // most recent of Build.TIME, the root file system's timestamp, and the
1467 // value of the ro.build.date.utc system property (which is in seconds).
1468 final long systemBuildTime = Long.max(
1469 1000L * SystemProperties.getLong("ro.build.date.utc", -1L),
1470 Long.max(Environment.getRootDirectory().lastModified(), Build.TIME));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001471 if (mInjector.getCurrentTimeMillis() < systemBuildTime) {
1472 Slog.i(TAG, "Current time only " + mInjector.getCurrentTimeMillis()
Christopher Tate247571462017-04-10 11:45:05 -07001473 + ", advancing to build time " + systemBuildTime);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001474 mInjector.setKernelTime(systemBuildTime);
Christopher Tate247571462017-04-10 11:45:05 -07001475 }
Christopher Tate247571462017-04-10 11:45:05 -07001476
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001477 // Determine SysUI's uid
1478 mSystemUiUid = mInjector.getSystemUiUid();
1479 if (mSystemUiUid <= 0) {
1480 Slog.wtf(TAG, "SysUI package not found!");
1481 }
1482 mWakeLock = mInjector.getAlarmWakeLock();
1483
Christopher Tatec8b7f432018-09-28 16:23:10 -07001484 mTimeTickIntent = new Intent(Intent.ACTION_TIME_TICK).addFlags(
1485 Intent.FLAG_RECEIVER_REGISTERED_ONLY
1486 | Intent.FLAG_RECEIVER_FOREGROUND
1487 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1488
1489 mTimeTickTrigger = new IAlarmListener.Stub() {
1490 @Override
1491 public void doAlarm(final IAlarmCompleteListener callback) throws RemoteException {
1492 if (DEBUG_BATCH) {
1493 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1494 }
1495
1496 // Via handler because dispatch invokes this within its lock. OnAlarmListener
1497 // takes care of this automatically, but we're using the direct internal
1498 // interface here rather than that client-side wrapper infrastructure.
1499 mHandler.post(() -> {
1500 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL);
1501
1502 try {
1503 callback.alarmComplete(this);
1504 } catch (RemoteException e) { /* local method call */ }
1505 });
1506
1507 synchronized (mLock) {
1508 mLastTickReceived = mInjector.getCurrentTimeMillis();
1509 }
1510 mClockReceiver.scheduleTimeTickEvent();
1511 }
1512 };
1513
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001514 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
1515 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1516 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1517 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
1518 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
1519
1520 mClockReceiver = mInjector.getClockReceiver(this);
1521 new InteractiveStateReceiver();
1522 new UninstallReceiver();
1523
1524 if (mInjector.isAlarmDriverPresent()) {
1525 AlarmThread waitThread = new AlarmThread();
1526 waitThread.start();
Christopher Tatebb9cce52017-04-18 14:19:43 -07001527 } else {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001528 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
Christopher Tatebb9cce52017-04-18 14:19:43 -07001529 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001530
1531 try {
1532 ActivityManager.getService().registerUidObserver(new UidObserver(),
1533 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1534 | ActivityManager.UID_OBSERVER_ACTIVE,
1535 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1536 } catch (RemoteException e) {
1537 // ignored; both services live in system_server
1538 }
Christopher Tatebb9cce52017-04-18 14:19:43 -07001539 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001540 publishLocalService(AlarmManagerInternal.class, new LocalService());
Adam Lesinski182f73f2013-12-05 16:48:06 -08001541 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001543
1544 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001545 public void onBootPhase(int phase) {
1546 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001547 synchronized (mLock) {
1548 mConstants.start(getContext().getContentResolver());
1549 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1550 mLocalDeviceIdleController =
1551 LocalServices.getService(DeviceIdleController.LocalService.class);
1552 mUsageStatsManagerInternal =
1553 LocalServices.getService(UsageStatsManagerInternal.class);
1554 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001555
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001556 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1557 mAppStateTracker.addListener(mForceAppStandbyListener);
1558
1559 mClockReceiver.scheduleTimeTickEvent();
1560 mClockReceiver.scheduleDateChangedEvent();
1561 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001562 }
1563 }
1564
1565 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 protected void finalize() throws Throwable {
1567 try {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001568 mInjector.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001569 } finally {
1570 super.finalize();
1571 }
1572 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001573
mswest463f4c99d2018-02-01 10:13:10 -08001574 boolean setTimeImpl(long millis) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001575 if (!mInjector.isAlarmDriverPresent()) {
mswest463f4c99d2018-02-01 10:13:10 -08001576 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1577 return false;
1578 }
1579
1580 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001581 final long currentTimeMillis = mInjector.getCurrentTimeMillis();
1582 mInjector.setKernelTime(millis);
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001583 final TimeZone timeZone = TimeZone.getDefault();
1584 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1585 final int newTzOffset = timeZone.getOffset(millis);
1586 if (currentTzOffset != newTzOffset) {
1587 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001588 mInjector.setKernelTimezone(-(newTzOffset / 60000));
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001589 }
1590 // The native implementation of setKernelTime can return -1 even when the kernel
1591 // time was set correctly, so assume setting kernel time was successful and always
1592 // return true.
1593 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001594 }
1595 }
1596
Adam Lesinski182f73f2013-12-05 16:48:06 -08001597 void setTimeZoneImpl(String tz) {
1598 if (TextUtils.isEmpty(tz)) {
1599 return;
David Christieebe51fc2013-07-26 13:23:29 -07001600 }
1601
Adam Lesinski182f73f2013-12-05 16:48:06 -08001602 TimeZone zone = TimeZone.getTimeZone(tz);
1603 // Prevent reentrant calls from stepping on each other when writing
1604 // the time zone property
1605 boolean timeZoneWasChanged = false;
1606 synchronized (this) {
1607 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1608 if (current == null || !current.equals(zone.getID())) {
1609 if (localLOGV) {
1610 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1611 }
1612 timeZoneWasChanged = true;
1613 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1614 }
1615
1616 // Update the kernel timezone information
1617 // Kernel tracks time offsets as 'minutes west of GMT'
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001618 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
1619 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001620 }
1621
1622 TimeZone.setDefault(null);
1623
1624 if (timeZoneWasChanged) {
Christopher Tatea4618b02018-10-11 16:22:55 -07001625 // Don't wait for broadcasts to update our midnight alarm
1626 mClockReceiver.scheduleDateChangedEvent();
1627
1628 // And now let everyone else know
Adam Lesinski182f73f2013-12-05 16:48:06 -08001629 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001630 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001631 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001632 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001633 intent.putExtra("time-zone", zone.getID());
1634 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001637
Christopher Tatec8b7f432018-09-28 16:23:10 -07001638 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001639 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001640 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001641 }
1642 }
1643
1644 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001645 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1646 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1647 int callingUid, String callingPackage) {
1648 // must be *either* PendingIntent or AlarmReceiver, but not both
1649 if ((operation == null && directReceiver == null)
1650 || (operation != null && directReceiver != null)) {
1651 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1652 // NB: previous releases failed silently here, so we are continuing to do the same
1653 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001654 return;
1655 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001656
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001657 // Sanity check the window length. This will catch people mistakenly
1658 // trying to pass an end-of-window timestamp rather than a duration.
1659 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1660 Slog.w(TAG, "Window length " + windowLength
1661 + "ms suspiciously long; limiting to 1 hour");
1662 windowLength = AlarmManager.INTERVAL_HOUR;
1663 }
1664
Christopher Tate498c6cb2014-11-17 16:09:27 -08001665 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001666 // seconds when the API expects milliseconds, or apps trying shenanigans
1667 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001668 final long minInterval = mConstants.MIN_INTERVAL;
1669 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001670 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001671 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001672 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001673 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001674 } else if (interval > mConstants.MAX_INTERVAL) {
1675 Slog.w(TAG, "Suspiciously long interval " + interval
1676 + " millis; clamping");
1677 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001678 }
1679
Christopher Tatee0a22b32013-07-11 14:43:13 -07001680 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1681 throw new IllegalArgumentException("Invalid alarm type " + type);
1682 }
1683
Christopher Tate5f221e82013-07-30 17:13:15 -07001684 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001685 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001686 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001687 + " pid=" + what);
1688 triggerAtTime = 0;
1689 }
1690
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001691 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001692 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1693 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001694 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001695 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1696
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001697 final long maxElapsed;
1698 if (windowLength == AlarmManager.WINDOW_EXACT) {
1699 maxElapsed = triggerElapsed;
1700 } else if (windowLength < 0) {
1701 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001702 // Fix this window in place, so that as time approaches we don't collapse it.
1703 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001704 } else {
1705 maxElapsed = triggerElapsed + windowLength;
1706 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001707
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001708 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001709 if (DEBUG_BATCH) {
1710 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001711 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001712 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001713 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001715 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001716 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1717 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001718 }
1719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001720
Christopher Tate3e04b472013-10-21 17:51:31 -07001721 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001722 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1723 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1724 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001725 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001726 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1727 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001728 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001729 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001730 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1731 + " -- package not allowed to start");
1732 return;
1733 }
1734 } catch (RemoteException e) {
1735 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001736 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001737 setImplLocked(a, false, doValidate);
1738 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001739
Christopher Tatef2159712018-03-27 16:04:14 -07001740 /**
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001741 * Returns the maximum alarms that an app in the specified bucket can receive in a rolling time
1742 * window given by {@link Constants#APP_STANDBY_WINDOW}
1743 */
1744 @VisibleForTesting
1745 int getQuotaForBucketLocked(int bucket) {
1746 final int index;
1747 if (bucket <= UsageStatsManager.STANDBY_BUCKET_ACTIVE) {
1748 index = ACTIVE_INDEX;
1749 } else if (bucket <= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1750 index = WORKING_INDEX;
1751 } else if (bucket <= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1752 index = FREQUENT_INDEX;
1753 } else if (bucket < UsageStatsManager.STANDBY_BUCKET_NEVER) {
1754 index = RARE_INDEX;
1755 } else {
1756 index = NEVER_INDEX;
1757 }
1758 return mConstants.APP_STANDBY_QUOTAS[index];
1759 }
1760
1761 /**
Christopher Tatef2159712018-03-27 16:04:14 -07001762 * Return the minimum time that should elapse before an app in the specified bucket
1763 * can receive alarms again
1764 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001765 @VisibleForTesting
1766 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001767 // UsageStats bucket values are treated as floors of their behavioral range.
1768 // In other words, a bucket value between WORKING and ACTIVE is treated as
1769 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1770 // values.
1771 final int index;
1772
1773 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1774 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1775 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1776 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1777 else index = ACTIVE_INDEX;
1778
1779 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001780 }
1781
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001782 /**
1783 * Adjusts the alarm delivery time based on the current app standby bucket.
1784 * @param alarm The alarm to adjust
1785 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001786 */
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001787 private boolean adjustDeliveryTimeBasedOnBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001788 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001789 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001790 }
1791 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001792 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001793 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001794 alarm.whenElapsed = alarm.expectedWhenElapsed;
1795 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1796 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001797 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001798 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001799 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001800 final long oldWhenElapsed = alarm.whenElapsed;
1801 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1802
Suprabh Shukla75edab12018-01-29 14:09:06 -08001803 final String sourcePackage = alarm.sourcePackage;
1804 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1805 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001806 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001807
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001808 if (mConstants.APP_STANDBY_QUOTAS_ENABLED) {
1809 // Quota deferring implementation:
1810 final int wakeupsInWindow = mAppWakeupHistory.getTotalWakeupsInWindow(sourcePackage,
1811 sourceUserId);
1812 final int quotaForBucket = getQuotaForBucketLocked(standbyBucket);
1813 boolean deferred = false;
1814 if (wakeupsInWindow >= quotaForBucket) {
1815 final long minElapsed;
1816 if (quotaForBucket <= 0) {
1817 // Just keep deferring for a day till the quota changes
1818 minElapsed = mInjector.getElapsedRealtime() + MILLIS_IN_DAY;
1819 } else {
1820 // Suppose the quota for window was q, and the qth last delivery time for this
1821 // package was t(q) then the next delivery must be after t(q) + <window_size>
1822 final long t = mAppWakeupHistory.getLastWakeupForPackage(sourcePackage,
1823 sourceUserId, quotaForBucket);
1824 minElapsed = t + 1 + mConstants.APP_STANDBY_WINDOW;
1825 }
1826 if (alarm.expectedWhenElapsed < minElapsed) {
1827 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1828 deferred = true;
1829 }
1830 }
1831 if (!deferred) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001832 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001833 alarm.whenElapsed = alarm.expectedWhenElapsed;
1834 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001835 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001836 } else {
1837 // Minimum delay deferring implementation:
1838 final long lastElapsed = mAppWakeupHistory.getLastWakeupForPackage(sourcePackage,
1839 sourceUserId, 1);
1840 if (lastElapsed > 0) {
1841 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
1842 if (alarm.expectedWhenElapsed < minElapsed) {
1843 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1844 } else {
1845 // app is now eligible to run alarms at the originally requested window.
1846 // Restore original requirements in case they were changed earlier.
1847 alarm.whenElapsed = alarm.expectedWhenElapsed;
1848 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1849 }
1850 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001851 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001852 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001853 }
1854
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001855 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1856 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001857 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001858 // The caller has given the time they want this to happen at, however we need
1859 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001860 // bring us out of idle at an earlier time.
1861 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001862 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001863 }
1864 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001865 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001866 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001867 if (fuzz > 0) {
1868 if (mRandom == null) {
1869 mRandom = new Random();
1870 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001871 final int delta = mRandom.nextInt(fuzz);
1872 a.whenElapsed -= delta;
1873 if (false) {
1874 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1875 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1876 Slog.d(TAG, "Applied fuzz: " + fuzz);
1877 Slog.d(TAG, "Final delta: " + delta);
1878 Slog.d(TAG, "Final when: " + a.whenElapsed);
1879 }
1880 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001881 }
1882
1883 } else if (mPendingIdleUntil != null) {
1884 // We currently have an idle until alarm scheduled; if the new alarm has
1885 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001886 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1887 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1888 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001889 == 0) {
1890 mPendingWhileIdleAlarms.add(a);
1891 return;
1892 }
1893 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001894 if (RECORD_DEVICE_IDLE_ALARMS) {
1895 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1896 IdleDispatchEntry ent = new IdleDispatchEntry();
1897 ent.uid = a.uid;
1898 ent.pkg = a.operation.getCreatorPackage();
1899 ent.tag = a.operation.getTag("");
1900 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001901 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001902 ent.argRealtime = a.whenElapsed;
1903 mAllowWhileIdleDispatches.add(ent);
1904 }
1905 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08001906 adjustDeliveryTimeBasedOnBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001907 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001909 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001910 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001911 }
1912
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001913 boolean needRebatch = false;
1914
1915 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001916 if (RECORD_DEVICE_IDLE_ALARMS) {
1917 if (mPendingIdleUntil == null) {
1918 IdleDispatchEntry ent = new IdleDispatchEntry();
1919 ent.uid = 0;
1920 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001921 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001922 mAllowWhileIdleDispatches.add(ent);
1923 }
1924 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001925 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1926 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1927 + " to " + a);
1928 }
1929
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001930 mPendingIdleUntil = a;
1931 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001932 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1933 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1934 mNextWakeFromIdle = a;
1935 // If this wake from idle is earlier than whatever was previously scheduled,
1936 // and we are currently idling, then we need to rebatch alarms in case the idle
1937 // until time needs to be updated.
1938 if (mPendingIdleUntil != null) {
1939 needRebatch = true;
1940 }
1941 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001942 }
1943
1944 if (!rebatching) {
1945 if (DEBUG_VALIDATE) {
1946 if (doValidate && !validateConsistencyLocked()) {
1947 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1948 + " when(hex)=" + Long.toHexString(a.when)
1949 + " whenElapsed=" + a.whenElapsed
1950 + " maxWhenElapsed=" + a.maxWhenElapsed
1951 + " interval=" + a.repeatInterval + " op=" + a.operation
1952 + " flags=0x" + Integer.toHexString(a.flags));
1953 rebatchAllAlarmsLocked(false);
1954 needRebatch = false;
1955 }
1956 }
1957
1958 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001959 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001960 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001961
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001962 rescheduleKernelAlarmsLocked();
1963 updateNextAlarmClockLocked();
1964 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001965 }
1966
Christopher Tate1d99c392017-12-07 16:54:04 -08001967 /**
1968 * System-process internal API
1969 */
1970 private final class LocalService implements AlarmManagerInternal {
1971 @Override
1972 public void removeAlarmsForUid(int uid) {
1973 synchronized (mLock) {
1974 removeLocked(uid);
1975 }
1976 }
1977 }
1978
1979 /**
1980 * Public-facing binder interface
1981 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001982 private final IBinder mService = new IAlarmManager.Stub() {
1983 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001984 public void set(String callingPackage,
1985 int type, long triggerAtTime, long windowLength, long interval, int flags,
1986 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1987 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001988 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001989
1990 // make sure the caller is not lying about which package should be blamed for
1991 // wakelock time spent in alarm delivery
1992 mAppOps.checkPackage(callingUid, callingPackage);
1993
1994 // Repeating alarms must use PendingIntent, not direct listener
1995 if (interval != 0) {
1996 if (directReceiver != null) {
1997 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1998 }
1999 }
2000
Adam Lesinski182f73f2013-12-05 16:48:06 -08002001 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002002 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08002003 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002004 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07002005 }
2006
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002007 // No incoming callers can request either WAKE_FROM_IDLE or
2008 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
2009 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
2010 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
2011
2012 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
2013 // manager when to come out of idle mode, which is only for DeviceIdleController.
2014 if (callingUid != Process.SYSTEM_UID) {
2015 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
2016 }
2017
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002018 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002019 if (windowLength == AlarmManager.WINDOW_EXACT) {
2020 flags |= AlarmManager.FLAG_STANDALONE;
2021 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002022
2023 // If this alarm is for an alarm clock, then it must be standalone and we will
2024 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002025 if (alarmClock != null) {
2026 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002027
2028 // If the caller is a core system component or on the user's whitelist, and not calling
2029 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
2030 // This means we will allow these alarms to go off as normal even while idle, with no
2031 // timing restrictions.
2032 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08002033 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08002034 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07002035 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002036 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
2037 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002038 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002039
Christopher Tate14a7bb02015-10-01 10:24:31 -07002040 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
2041 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002042 }
Christopher Tate89779822012-08-31 14:40:03 -07002043
Adam Lesinski182f73f2013-12-05 16:48:06 -08002044 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08002045 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002046 getContext().enforceCallingOrSelfPermission(
2047 "android.permission.SET_TIME",
2048 "setTime");
2049
mswest463f4c99d2018-02-01 10:13:10 -08002050 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002051 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002052
2053 @Override
2054 public void setTimeZone(String tz) {
2055 getContext().enforceCallingOrSelfPermission(
2056 "android.permission.SET_TIME_ZONE",
2057 "setTimeZone");
2058
2059 final long oldId = Binder.clearCallingIdentity();
2060 try {
2061 setTimeZoneImpl(tz);
2062 } finally {
2063 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002064 }
2065 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07002066
Adam Lesinski182f73f2013-12-05 16:48:06 -08002067 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07002068 public void remove(PendingIntent operation, IAlarmListener listener) {
2069 if (operation == null && listener == null) {
2070 Slog.w(TAG, "remove() with no intent or listener");
2071 return;
2072 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002073
Christopher Tate14a7bb02015-10-01 10:24:31 -07002074 synchronized (mLock) {
2075 removeLocked(operation, listener);
2076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002077 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07002078
Adam Lesinski182f73f2013-12-05 16:48:06 -08002079 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002080 public long getNextWakeFromIdleTime() {
2081 return getNextWakeFromIdleTimeImpl();
2082 }
2083
2084 @Override
Jose Lima235510e2014-08-13 12:50:01 -07002085 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002086 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
2087 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
2088 "getNextAlarmClock", null);
2089
2090 return getNextAlarmClockImpl(userId);
2091 }
2092
2093 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07002094 public long currentNetworkTimeMillis() {
2095 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
2096 if (time.hasCache()) {
2097 return time.currentTimeMillis();
2098 } else {
2099 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
2100 }
2101 }
2102
2103 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08002104 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06002105 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07002106
2107 if (args.length > 0 && "--proto".equals(args[0])) {
2108 dumpProto(fd);
2109 } else {
2110 dumpImpl(pw);
2111 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07002112 }
mswest463f4c99d2018-02-01 10:13:10 -08002113
2114 @Override
2115 public void onShellCommand(FileDescriptor in, FileDescriptor out,
2116 FileDescriptor err, String[] args, ShellCallback callback,
2117 ResultReceiver resultReceiver) {
2118 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
2119 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002120 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07002121
Adam Lesinski182f73f2013-12-05 16:48:06 -08002122 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002123 synchronized (mLock) {
2124 pw.println("Current Alarm Manager state:");
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08002125 mConstants.dump(pw, " ");
Dianne Hackborna750a632015-06-16 17:18:23 -07002126 pw.println();
2127
Makoto Onukie4918212018-02-06 11:30:15 -08002128 if (mAppStateTracker != null) {
2129 mAppStateTracker.dump(pw, " ");
2130 pw.println();
2131 }
Makoto Onuki2206af32017-11-21 16:25:35 -08002132
Suprabh Shukla75edab12018-01-29 14:09:06 -08002133 pw.println(" App Standby Parole: " + mAppStandbyParole);
2134 pw.println();
2135
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002136 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002137 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07002138 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08002139 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002140
Dianne Hackborna750a632015-06-16 17:18:23 -07002141 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002142 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08002143 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002144 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002145 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07002146 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08002147 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08002148 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
2149 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08002150 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
2151 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002152
Christopher Tatec8b7f432018-09-28 16:23:10 -07002153 if (RECORD_ALARMS_IN_HISTORY) {
2154 pw.println();
2155 pw.println(" Recent TIME_TICK history:");
2156 int i = mNextTickHistory;
2157 do {
2158 i--;
2159 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
2160 final long time = mTickHistory[i];
2161 pw.print(" ");
2162 pw.println((time > 0)
2163 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
2164 : "-");
2165 } while (i != mNextTickHistory);
2166 pw.println();
2167 }
2168
Makoto Onukie8edbcf2018-03-02 16:49:29 -08002169 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
2170 if (ssm != null) {
2171 pw.println();
2172 pw.print(" RuntimeStarted=");
2173 pw.print(sdf.format(
2174 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
2175 if (ssm.isRuntimeRestarted()) {
2176 pw.print(" (Runtime restarted)");
2177 }
2178 pw.println();
2179 pw.print(" Runtime uptime (elapsed): ");
2180 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
2181 pw.println();
2182 pw.print(" Runtime uptime (uptime): ");
2183 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
2184 pw.println();
2185 }
2186
Dianne Hackbornc3527222015-05-13 14:03:20 -07002187 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002188 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002189 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002190 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
2191 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002192 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08002193 pw.print(" Max wakeup delay: ");
2194 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
2195 pw.println();
2196 pw.print(" Time since last dispatch: ");
2197 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
2198 pw.println();
2199 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002200 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08002201 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07002202
2203 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
2204 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07002205 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002206 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002207 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002208 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002209 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
2210 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08002211 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
2212 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002213 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002214 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002215 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07002216
2217 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002218 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002219 pw.println();
2220 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002221 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002222 pw.println();
2223
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002224 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002225 pw.print(" = "); pw.println(mLastWakeup);
2226 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2227 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002228 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002229
John Spurlock604a5ee2015-06-01 12:27:22 -04002230 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002231 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002232 final TreeSet<Integer> users = new TreeSet<>();
2233 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2234 users.add(mNextAlarmClockForUser.keyAt(i));
2235 }
2236 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2237 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2238 }
2239 for (int user : users) {
2240 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2241 final long time = next != null ? next.getTriggerTime() : 0;
2242 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002243 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002244 pw.print(" pendingSend:"); pw.print(pendingSend);
2245 pw.print(" time:"); pw.print(time);
2246 if (time > 0) {
2247 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2248 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2249 }
2250 pw.println();
2251 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002252 if (mAlarmBatches.size() > 0) {
2253 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002254 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002255 pw.println(mAlarmBatches.size());
2256 for (Batch b : mAlarmBatches) {
2257 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002258 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002259 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002260 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002261 pw.println();
2262 pw.println(" Pending user blocked background alarms: ");
2263 boolean blocked = false;
2264 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2265 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2266 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2267 blocked = true;
2268 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2269 }
2270 }
2271 if (!blocked) {
2272 pw.println(" none");
2273 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002274
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08002275 mAppWakeupHistory.dump(pw, " ", nowELAPSED);
Suprabh Shukla75edab12018-01-29 14:09:06 -08002276
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002277 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002278 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002279 pw.println(" Idle mode state:");
2280 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002281 if (mPendingIdleUntil != null) {
2282 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002283 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002284 } else {
2285 pw.println("null");
2286 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002287 pw.println(" Pending alarms:");
2288 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002289 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002290 if (mNextWakeFromIdle != null) {
2291 pw.println();
2292 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002293 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002294 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002295
2296 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002297 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002298 if (mPendingNonWakeupAlarms.size() > 0) {
2299 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002300 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002301 } else {
2302 pw.println("(none)");
2303 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002304 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002305 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2306 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002307 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002308 pw.print(", max non-interactive time: ");
2309 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2310 pw.println();
2311
2312 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002313 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002314 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2315 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2316 pw.print(" Listener send count: "); pw.println(mListenerCount);
2317 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002318 pw.println();
2319
Christopher Tate7f2a0352015-12-08 10:24:33 -08002320 if (mInFlight.size() > 0) {
2321 pw.println("Outstanding deliveries:");
2322 for (int i = 0; i < mInFlight.size(); i++) {
2323 pw.print(" #"); pw.print(i); pw.print(": ");
2324 pw.println(mInFlight.get(i));
2325 }
2326 pw.println();
2327 }
2328
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002329 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002330 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002331 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002332 pw.print(" UID ");
2333 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2334 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002335 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002336 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2337 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2338
2339 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2340 pw.print(" Next allowed:");
2341 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2342 pw.print(" (");
2343 TimeUtils.formatDuration(minInterval, 0, pw);
2344 pw.print(")");
2345
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002346 pw.println();
2347 }
2348 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002349
2350 pw.print(" mUseAllowWhileIdleShortTime: [");
2351 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2352 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2353 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2354 pw.print(" ");
2355 }
2356 }
2357 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002358 pw.println();
2359
Dianne Hackborn81038902012-11-26 17:04:09 -08002360 if (mLog.dump(pw, " Recent problems", " ")) {
2361 pw.println();
2362 }
2363
2364 final FilterStats[] topFilters = new FilterStats[10];
2365 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2366 @Override
2367 public int compare(FilterStats lhs, FilterStats rhs) {
2368 if (lhs.aggregateTime < rhs.aggregateTime) {
2369 return 1;
2370 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2371 return -1;
2372 }
2373 return 0;
2374 }
2375 };
2376 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002377 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002378 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2379 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2380 for (int ip=0; ip<uidStats.size(); ip++) {
2381 BroadcastStats bs = uidStats.valueAt(ip);
2382 for (int is=0; is<bs.filterStats.size(); is++) {
2383 FilterStats fs = bs.filterStats.valueAt(is);
2384 int pos = len > 0
2385 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2386 if (pos < 0) {
2387 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002388 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002389 if (pos < topFilters.length) {
2390 int copylen = topFilters.length - pos - 1;
2391 if (copylen > 0) {
2392 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2393 }
2394 topFilters[pos] = fs;
2395 if (len < topFilters.length) {
2396 len++;
2397 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002398 }
2399 }
2400 }
2401 }
2402 if (len > 0) {
2403 pw.println(" Top Alarms:");
2404 for (int i=0; i<len; i++) {
2405 FilterStats fs = topFilters[i];
2406 pw.print(" ");
2407 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2408 TimeUtils.formatDuration(fs.aggregateTime, pw);
2409 pw.print(" running, "); pw.print(fs.numWakeup);
2410 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002411 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2412 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002413 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002414 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002415 pw.println();
2416 }
2417 }
2418
2419 pw.println(" ");
2420 pw.println(" Alarm Stats:");
2421 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002422 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2423 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2424 for (int ip=0; ip<uidStats.size(); ip++) {
2425 BroadcastStats bs = uidStats.valueAt(ip);
2426 pw.print(" ");
2427 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2428 UserHandle.formatUid(pw, bs.mUid);
2429 pw.print(":");
2430 pw.print(bs.mPackageName);
2431 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2432 pw.print(" running, "); pw.print(bs.numWakeup);
2433 pw.println(" wakeups:");
2434 tmpFilters.clear();
2435 for (int is=0; is<bs.filterStats.size(); is++) {
2436 tmpFilters.add(bs.filterStats.valueAt(is));
2437 }
2438 Collections.sort(tmpFilters, comparator);
2439 for (int i=0; i<tmpFilters.size(); i++) {
2440 FilterStats fs = tmpFilters.get(i);
2441 pw.print(" ");
2442 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2443 TimeUtils.formatDuration(fs.aggregateTime, pw);
2444 pw.print(" "); pw.print(fs.numWakeup);
2445 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002446 pw.print(" alarms, last ");
2447 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2448 pw.println(":");
2449 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002450 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002451 pw.println();
2452 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002453 }
2454 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002455 pw.println();
2456 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002457
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002458 if (RECORD_DEVICE_IDLE_ALARMS) {
2459 pw.println();
2460 pw.println(" Allow while idle dispatches:");
2461 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2462 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2463 pw.print(" ");
2464 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2465 pw.print(": ");
2466 UserHandle.formatUid(pw, ent.uid);
2467 pw.print(":");
2468 pw.println(ent.pkg);
2469 if (ent.op != null) {
2470 pw.print(" ");
2471 pw.print(ent.op);
2472 pw.print(" / ");
2473 pw.print(ent.tag);
2474 if (ent.argRealtime != 0) {
2475 pw.print(" (");
2476 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2477 pw.print(")");
2478 }
2479 pw.println();
2480 }
2481 }
2482 }
2483
Christopher Tate18a75f12013-07-01 18:18:59 -07002484 if (WAKEUP_STATS) {
2485 pw.println();
2486 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002487 long last = -1;
2488 for (WakeupEvent event : mRecentWakeups) {
2489 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2490 pw.print('|');
2491 if (last < 0) {
2492 pw.print('0');
2493 } else {
2494 pw.print(event.when - last);
2495 }
2496 last = event.when;
2497 pw.print('|'); pw.print(event.uid);
2498 pw.print('|'); pw.print(event.action);
2499 pw.println();
2500 }
2501 pw.println();
2502 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002503 }
2504 }
2505
Kweku Adams61e03292017-10-19 14:27:12 -07002506 void dumpProto(FileDescriptor fd) {
2507 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2508
2509 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002510 final long nowRTC = mInjector.getCurrentTimeMillis();
2511 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002512 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2513 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2514 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002515 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002516 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002517 mLastTimeChangeRealtime);
2518
Yi Jin2b30f322018-02-20 15:41:47 -08002519 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002520
Makoto Onukie4918212018-02-06 11:30:15 -08002521 if (mAppStateTracker != null) {
2522 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002523 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002524 }
Kweku Adams61e03292017-10-19 14:27:12 -07002525
Yi Jin2b30f322018-02-20 15:41:47 -08002526 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002527 if (!mInteractive) {
2528 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002529 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002530 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002531 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002532 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002533 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002534 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002535 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002536 nowElapsed - mNextNonWakeupDeliveryTime);
2537 }
2538
Yi Jin2b30f322018-02-20 15:41:47 -08002539 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002540 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002541 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002542 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002543 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002544 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002545 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002546 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002547 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002548
2549 final TreeSet<Integer> users = new TreeSet<>();
2550 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2551 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2552 users.add(mNextAlarmClockForUser.keyAt(i));
2553 }
2554 final int pendingSendNextAlarmClockChangedForUserSize =
2555 mPendingSendNextAlarmClockChangedForUser.size();
2556 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2557 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2558 }
2559 for (int user : users) {
2560 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2561 final long time = next != null ? next.getTriggerTime() : 0;
2562 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002563 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002564 proto.write(AlarmClockMetadataProto.USER, user);
2565 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2566 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2567 proto.end(aToken);
2568 }
2569 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002570 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002571 nowElapsed, nowRTC);
2572 }
2573 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2574 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2575 if (blockedAlarms != null) {
2576 for (Alarm a : blockedAlarms) {
2577 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002578 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002579 nowElapsed, nowRTC);
2580 }
2581 }
2582 }
2583 if (mPendingIdleUntil != null) {
2584 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002585 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002586 }
2587 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002588 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002589 nowElapsed, nowRTC);
2590 }
2591 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002592 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002593 nowElapsed, nowRTC);
2594 }
2595
2596 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002597 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002598 nowElapsed, nowRTC);
2599 }
2600
Yi Jin2b30f322018-02-20 15:41:47 -08002601 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2602 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2603 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2604 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002605 mNonInteractiveTime);
2606
Yi Jin2b30f322018-02-20 15:41:47 -08002607 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2608 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2609 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2610 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2611 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002612
2613 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002614 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002615 }
2616
Kweku Adams61e03292017-10-19 14:27:12 -07002617 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2618 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002619 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002620 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2621 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2622
Yi Jin2b30f322018-02-20 15:41:47 -08002623 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2624 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2625 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002626 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002627 proto.end(token);
2628 }
2629
Makoto Onukiadb50d82018-01-29 16:20:30 -08002630 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2631 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002632 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002633 mUseAllowWhileIdleShortTime.keyAt(i));
2634 }
2635 }
2636
Yi Jin2b30f322018-02-20 15:41:47 -08002637 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002638
2639 final FilterStats[] topFilters = new FilterStats[10];
2640 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2641 @Override
2642 public int compare(FilterStats lhs, FilterStats rhs) {
2643 if (lhs.aggregateTime < rhs.aggregateTime) {
2644 return 1;
2645 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2646 return -1;
2647 }
2648 return 0;
2649 }
2650 };
2651 int len = 0;
2652 // Get the top 10 FilterStats, ordered by aggregateTime.
2653 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2654 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2655 for (int ip = 0; ip < uidStats.size(); ++ip) {
2656 BroadcastStats bs = uidStats.valueAt(ip);
2657 for (int is = 0; is < bs.filterStats.size(); ++is) {
2658 FilterStats fs = bs.filterStats.valueAt(is);
2659 int pos = len > 0
2660 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2661 if (pos < 0) {
2662 pos = -pos - 1;
2663 }
2664 if (pos < topFilters.length) {
2665 int copylen = topFilters.length - pos - 1;
2666 if (copylen > 0) {
2667 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2668 }
2669 topFilters[pos] = fs;
2670 if (len < topFilters.length) {
2671 len++;
2672 }
2673 }
2674 }
2675 }
2676 }
2677 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002678 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002679 FilterStats fs = topFilters[i];
2680
Yi Jin2b30f322018-02-20 15:41:47 -08002681 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2682 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002683 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002684 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002685
2686 proto.end(token);
2687 }
2688
2689 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2690 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2691 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2692 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002693 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002694
2695 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002696 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002697
2698 // uidStats is an ArrayMap, which we can't sort.
2699 tmpFilters.clear();
2700 for (int is = 0; is < bs.filterStats.size(); ++is) {
2701 tmpFilters.add(bs.filterStats.valueAt(is));
2702 }
2703 Collections.sort(tmpFilters, comparator);
2704 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002705 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002706 }
2707
2708 proto.end(token);
2709 }
2710 }
2711
2712 if (RECORD_DEVICE_IDLE_ALARMS) {
2713 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2714 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2715 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002716 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002717
2718 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2719 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2720 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2721 proto.write(IdleDispatchEntryProto.OP, ent.op);
2722 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2723 ent.elapsedRealtime);
2724 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2725
2726 proto.end(token);
2727 }
2728 }
2729
2730 if (WAKEUP_STATS) {
2731 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002732 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002733 proto.write(WakeupEventProto.UID, event.uid);
2734 proto.write(WakeupEventProto.ACTION, event.action);
2735 proto.write(WakeupEventProto.WHEN, event.when);
2736 proto.end(token);
2737 }
2738 }
2739 }
2740
2741 proto.flush();
2742 }
2743
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002744 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002745 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2746 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002747 final long nowRTC = mInjector.getCurrentTimeMillis();
2748 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002749 final int NZ = mAlarmBatches.size();
2750 for (int iz = 0; iz < NZ; iz++) {
2751 Batch bz = mAlarmBatches.get(iz);
2752 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002753 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002754 pw.flush();
2755 Slog.v(TAG, bs.toString());
2756 bs.reset();
2757 }
2758 }
2759
2760 private boolean validateConsistencyLocked() {
2761 if (DEBUG_VALIDATE) {
2762 long lastTime = Long.MIN_VALUE;
2763 final int N = mAlarmBatches.size();
2764 for (int i = 0; i < N; i++) {
2765 Batch b = mAlarmBatches.get(i);
2766 if (b.start >= lastTime) {
2767 // duplicate start times are okay because of standalone batches
2768 lastTime = b.start;
2769 } else {
2770 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002771 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2772 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002773 return false;
2774 }
2775 }
2776 }
2777 return true;
2778 }
2779
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002780 private Batch findFirstWakeupBatchLocked() {
2781 final int N = mAlarmBatches.size();
2782 for (int i = 0; i < N; i++) {
2783 Batch b = mAlarmBatches.get(i);
2784 if (b.hasWakeups()) {
2785 return b;
2786 }
2787 }
2788 return null;
2789 }
2790
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002791 long getNextWakeFromIdleTimeImpl() {
2792 synchronized (mLock) {
2793 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2794 }
2795 }
2796
2797 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002798 synchronized (mLock) {
2799 return mNextAlarmClockForUser.get(userId);
2800 }
2801 }
2802
2803 /**
2804 * Recomputes the next alarm clock for all users.
2805 */
2806 private void updateNextAlarmClockLocked() {
2807 if (!mNextAlarmClockMayChange) {
2808 return;
2809 }
2810 mNextAlarmClockMayChange = false;
2811
Jose Lima235510e2014-08-13 12:50:01 -07002812 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002813 nextForUser.clear();
2814
2815 final int N = mAlarmBatches.size();
2816 for (int i = 0; i < N; i++) {
2817 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2818 final int M = alarms.size();
2819
2820 for (int j = 0; j < M; j++) {
2821 Alarm a = alarms.get(j);
2822 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002823 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002824 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002825
2826 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002827 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002828 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002829 " for user " + userId);
2830 }
2831
2832 // Alarms and batches are sorted by time, no need to compare times here.
2833 if (nextForUser.get(userId) == null) {
2834 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002835 } else if (a.alarmClock.equals(current)
2836 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2837 // same/earlier time and it's the one we cited before, so stick with it
2838 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002839 }
2840 }
2841 }
2842 }
2843
2844 // Update mNextAlarmForUser with new values.
2845 final int NN = nextForUser.size();
2846 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002847 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002848 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002849 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002850 if (!newAlarm.equals(currentAlarm)) {
2851 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2852 }
2853 }
2854
2855 // Remove users without any alarm clocks scheduled.
2856 final int NNN = mNextAlarmClockForUser.size();
2857 for (int i = NNN - 1; i >= 0; i--) {
2858 int userId = mNextAlarmClockForUser.keyAt(i);
2859 if (nextForUser.get(userId) == null) {
2860 updateNextAlarmInfoForUserLocked(userId, null);
2861 }
2862 }
2863 }
2864
Jose Lima235510e2014-08-13 12:50:01 -07002865 private void updateNextAlarmInfoForUserLocked(int userId,
2866 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002867 if (alarmClock != null) {
2868 if (DEBUG_ALARM_CLOCK) {
2869 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002870 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002871 }
2872 mNextAlarmClockForUser.put(userId, alarmClock);
2873 } else {
2874 if (DEBUG_ALARM_CLOCK) {
2875 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2876 }
2877 mNextAlarmClockForUser.remove(userId);
2878 }
2879
2880 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2881 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2882 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2883 }
2884
2885 /**
2886 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2887 * for which alarm clocks have changed since the last call to this.
2888 *
2889 * Do not call with a lock held. Only call from mHandler's thread.
2890 *
2891 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2892 */
2893 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002894 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002895 pendingUsers.clear();
2896
2897 synchronized (mLock) {
2898 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2899 for (int i = 0; i < N; i++) {
2900 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2901 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2902 }
2903 mPendingSendNextAlarmClockChangedForUser.clear();
2904 }
2905
2906 final int N = pendingUsers.size();
2907 for (int i = 0; i < N; i++) {
2908 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002909 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002910 Settings.System.putStringForUser(getContext().getContentResolver(),
2911 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002912 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002913 userId);
2914
2915 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2916 new UserHandle(userId));
2917 }
2918 }
2919
2920 /**
2921 * Formats an alarm like platform/packages/apps/DeskClock used to.
2922 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002923 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2924 int userId) {
2925 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002926 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2927 return (info == null) ? "" :
2928 DateFormat.format(pattern, info.getTriggerTime()).toString();
2929 }
2930
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002931 /**
2932 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2933 * by more than half a minute, log a wtf.
2934 */
2935 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2936 final StringBuilder errorMsg = new StringBuilder();
2937 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002938 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002939 stuck = true;
2940 errorMsg.append("[mNextNonWakeup=");
2941 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002942 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002943 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002944 errorMsg.append(", mLastWakeup=");
2945 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002946 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002947 errorMsg.append("];");
2948 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002949 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002950 stuck = true;
2951 errorMsg.append("[mNextWakeup=");
2952 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002953 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002954 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002955 errorMsg.append(", mLastWakeup=");
2956 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2957 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002958 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002959 errorMsg.append("];");
2960 }
2961 if (stuck) {
2962 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2963 }
2964 }
2965
Adam Lesinski182f73f2013-12-05 16:48:06 -08002966 void rescheduleKernelAlarmsLocked() {
2967 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2968 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002969 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002970 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002971 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002972 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002973 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002974 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002975 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002976 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002977 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002978 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002979 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002980 if (firstBatch != firstWakeup) {
2981 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002982 }
2983 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002984 if (mPendingNonWakeupAlarms.size() > 0) {
2985 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2986 nextNonWakeup = mNextNonWakeupDeliveryTime;
2987 }
2988 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002989 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002990 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002991 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002992 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2993 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002994 }
2995
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002996 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002997 if (operation == null && directReceiver == null) {
2998 if (localLOGV) {
2999 Slog.w(TAG, "requested remove() of null operation",
3000 new RuntimeException("here"));
3001 }
3002 return;
3003 }
3004
Adam Lesinski182f73f2013-12-05 16:48:06 -08003005 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003006 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003007 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3008 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003009 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003010 if (b.size() == 0) {
3011 mAlarmBatches.remove(i);
3012 }
3013 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003014 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003015 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003016 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3017 mPendingWhileIdleAlarms.remove(i);
3018 }
3019 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003020 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3021 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3022 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3023 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
3024 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3025 alarmsForUid.remove(j);
3026 }
3027 }
3028 if (alarmsForUid.size() == 0) {
3029 mPendingBackgroundAlarms.removeAt(i);
3030 }
3031 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003032 if (didRemove) {
3033 if (DEBUG_BATCH) {
3034 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
3035 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003036 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003037 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003038 mPendingIdleUntil = null;
3039 restorePending = true;
3040 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003041 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003042 mNextWakeFromIdle = null;
3043 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003044 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003045 if (restorePending) {
3046 restorePendingWhileIdleAlarmsLocked();
3047 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003048 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003049 }
3050 }
3051
Christopher Tate1d99c392017-12-07 16:54:04 -08003052 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003053 if (uid == Process.SYSTEM_UID) {
3054 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
3055 return;
3056 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003057 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003058 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003059 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3060 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003061 didRemove |= b.remove(whichAlarms);
3062 if (b.size() == 0) {
3063 mAlarmBatches.remove(i);
3064 }
3065 }
3066 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
3067 final Alarm a = mPendingWhileIdleAlarms.get(i);
3068 if (a.uid == uid) {
3069 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3070 mPendingWhileIdleAlarms.remove(i);
3071 }
3072 }
3073 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
3074 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3075 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3076 if (alarmsForUid.get(j).uid == uid) {
3077 alarmsForUid.remove(j);
3078 }
3079 }
3080 if (alarmsForUid.size() == 0) {
3081 mPendingBackgroundAlarms.removeAt(i);
3082 }
3083 }
3084 if (didRemove) {
3085 if (DEBUG_BATCH) {
3086 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
3087 }
3088 rebatchAllAlarmsLocked(true);
3089 rescheduleKernelAlarmsLocked();
3090 updateNextAlarmClockLocked();
3091 }
3092 }
3093
3094 void removeLocked(final String packageName) {
3095 if (packageName == null) {
3096 if (localLOGV) {
3097 Slog.w(TAG, "requested remove() of null packageName",
3098 new RuntimeException("here"));
3099 }
3100 return;
3101 }
3102
3103 boolean didRemove = false;
3104 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08003105 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08003106 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3107 Batch b = mAlarmBatches.get(i);
3108 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003109 if (b.size() == 0) {
3110 mAlarmBatches.remove(i);
3111 }
3112 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08003113 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
3114 if (oldHasTick != newHasTick) {
3115 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
3116 }
3117
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003118 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003119 final Alarm a = mPendingWhileIdleAlarms.get(i);
3120 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003121 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3122 mPendingWhileIdleAlarms.remove(i);
3123 }
3124 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003125 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
3126 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
3127 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
3128 if (alarmsForUid.get(j).matches(packageName)) {
3129 alarmsForUid.remove(j);
3130 }
3131 }
3132 if (alarmsForUid.size() == 0) {
3133 mPendingBackgroundAlarms.removeAt(i);
3134 }
3135 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003136 if (didRemove) {
3137 if (DEBUG_BATCH) {
3138 Slog.v(TAG, "remove(package) changed bounds; rebatching");
3139 }
3140 rebatchAllAlarmsLocked(true);
3141 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003142 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003143 }
3144 }
3145
Christopher Tate1d99c392017-12-07 16:54:04 -08003146 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003147 if (uid == Process.SYSTEM_UID) {
3148 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
3149 return;
3150 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003151 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003152 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
3153 try {
3154 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
3155 uid, a.packageName)) {
3156 return true;
3157 }
3158 } catch (RemoteException e) { /* fall through */}
3159 return false;
3160 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003161 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3162 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003163 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003164 if (b.size() == 0) {
3165 mAlarmBatches.remove(i);
3166 }
3167 }
3168 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
3169 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003170 if (a.uid == uid) {
3171 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3172 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003173 }
3174 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003175 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3176 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
3177 mPendingBackgroundAlarms.removeAt(i);
3178 }
3179 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003180 if (didRemove) {
3181 if (DEBUG_BATCH) {
3182 Slog.v(TAG, "remove(package) changed bounds; rebatching");
3183 }
3184 rebatchAllAlarmsLocked(true);
3185 rescheduleKernelAlarmsLocked();
3186 updateNextAlarmClockLocked();
3187 }
3188 }
3189
Adam Lesinski182f73f2013-12-05 16:48:06 -08003190 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003191 if (userHandle == UserHandle.USER_SYSTEM) {
3192 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
3193 return;
3194 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003195 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08003196 final Predicate<Alarm> whichAlarms =
3197 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08003198 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
3199 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003200 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003201 if (b.size() == 0) {
3202 mAlarmBatches.remove(i);
3203 }
3204 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003205 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003206 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003207 == userHandle) {
3208 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3209 mPendingWhileIdleAlarms.remove(i);
3210 }
3211 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003212 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3213 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
3214 mPendingBackgroundAlarms.removeAt(i);
3215 }
3216 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003217 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3218 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3219 mLastAllowWhileIdleDispatch.removeAt(i);
3220 }
3221 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003222
3223 if (didRemove) {
3224 if (DEBUG_BATCH) {
3225 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3226 }
3227 rebatchAllAlarmsLocked(true);
3228 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003229 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003230 }
3231 }
3232
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003233 void interactiveStateChangedLocked(boolean interactive) {
3234 if (mInteractive != interactive) {
3235 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003236 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003237 if (interactive) {
3238 if (mPendingNonWakeupAlarms.size() > 0) {
3239 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3240 mTotalDelayTime += thisDelayTime;
3241 if (mMaxDelayTime < thisDelayTime) {
3242 mMaxDelayTime = thisDelayTime;
3243 }
3244 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3245 mPendingNonWakeupAlarms.clear();
3246 }
3247 if (mNonInteractiveStartTime > 0) {
3248 long dur = nowELAPSED - mNonInteractiveStartTime;
3249 if (dur > mNonInteractiveTime) {
3250 mNonInteractiveTime = dur;
3251 }
3252 }
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003253 // And send a TIME_TICK right now, since it is important to get the UI updated.
3254 mHandler.post(() ->
3255 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003256 } else {
3257 mNonInteractiveStartTime = nowELAPSED;
3258 }
3259 }
3260 }
3261
Adam Lesinski182f73f2013-12-05 16:48:06 -08003262 boolean lookForPackageLocked(String packageName) {
3263 for (int i = 0; i < mAlarmBatches.size(); i++) {
3264 Batch b = mAlarmBatches.get(i);
3265 if (b.hasPackage(packageName)) {
3266 return true;
3267 }
3268 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003269 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003270 final Alarm a = mPendingWhileIdleAlarms.get(i);
3271 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003272 return true;
3273 }
3274 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003275 return false;
3276 }
3277
3278 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003279 if (mInjector.isAlarmDriverPresent()) {
3280 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003281 } else {
3282 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003283 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003284
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003285 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003286 mHandler.sendMessageAtTime(msg, when);
3287 }
3288 }
3289
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003290 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003291 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003292 for (int i=list.size()-1; i>=0; i--) {
3293 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003294 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3295 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003296 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003299
3300 private static final String labelForType(int type) {
3301 switch (type) {
3302 case RTC: return "RTC";
3303 case RTC_WAKEUP : return "RTC_WAKEUP";
3304 case ELAPSED_REALTIME : return "ELAPSED";
3305 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003306 }
3307 return "--unknown--";
3308 }
3309
3310 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003311 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003312 for (int i=list.size()-1; i>=0; i--) {
3313 Alarm a = list.get(i);
3314 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003315 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3316 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003317 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003318 }
3319 }
3320
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003321 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003322 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003323 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003324 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003325 return false;
3326 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003327 if (alarm.operation != null) {
3328 if (alarm.operation.isActivity()) {
3329 // Don't defer starting actual UI
3330 return false;
3331 }
3332 if (alarm.operation.isForegroundService()) {
3333 // FG service alarms are nearly as important; consult AST policy
3334 exemptOnBatterySaver = true;
3335 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003336 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003337 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003338 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003339 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003340 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3341 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003342 }
3343
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003344 private static native long init();
3345 private static native void close(long nativeData);
3346 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3347 private static native int waitForAlarm(long nativeData);
3348 private static native int setKernelTime(long nativeData, long millis);
3349 private static native int setKernelTimezone(long nativeData, int minuteswest);
3350 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351
Makoto Onukiadb50d82018-01-29 16:20:30 -08003352 private long getWhileIdleMinIntervalLocked(int uid) {
3353 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003354 final boolean ebs = (mAppStateTracker != null)
3355 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003356 if (!dozing && !ebs) {
3357 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3358 }
3359 if (dozing) {
3360 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3361 }
3362 if (mUseAllowWhileIdleShortTime.get(uid)) {
3363 // if the last allow-while-idle went off while uid was fg, or the uid
3364 // recently came into fg, don't block the alarm for long.
3365 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3366 }
3367 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3368 }
3369
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003370 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003371 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003372 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003373 // batches are temporally sorted, so we need only pull from the
3374 // start of the list until we either empty it or hit a batch
3375 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003376 while (mAlarmBatches.size() > 0) {
3377 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003378 if (batch.start > nowELAPSED) {
3379 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003380 break;
3381 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382
Christopher Tatee0a22b32013-07-11 14:43:13 -07003383 // We will (re)schedule some alarms now; don't let that interfere
3384 // with delivery of this current batch
3385 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003386
Christopher Tatee0a22b32013-07-11 14:43:13 -07003387 final int N = batch.size();
3388 for (int i = 0; i < N; i++) {
3389 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003390
3391 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3392 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003393 // schedule such alarms. The first such alarm from an app is always delivered.
3394 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003395 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003396 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003397 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3398 // alarm went off for this app. Reschedule the alarm to be in the
3399 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003400 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003401 if (alarm.maxWhenElapsed < minTime) {
3402 alarm.maxWhenElapsed = minTime;
3403 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003404 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003405 if (RECORD_DEVICE_IDLE_ALARMS) {
3406 IdleDispatchEntry ent = new IdleDispatchEntry();
3407 ent.uid = alarm.uid;
3408 ent.pkg = alarm.operation.getCreatorPackage();
3409 ent.tag = alarm.operation.getTag("");
3410 ent.op = "RESCHEDULE";
3411 ent.elapsedRealtime = nowELAPSED;
3412 ent.argRealtime = lastTime;
3413 mAllowWhileIdleDispatches.add(ent);
3414 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003415 setImplLocked(alarm, true, false);
3416 continue;
3417 }
3418 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003419 if (isBackgroundRestricted(alarm)) {
3420 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3421 if (DEBUG_BG_LIMIT) {
3422 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3423 }
3424 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3425 if (alarmsForUid == null) {
3426 alarmsForUid = new ArrayList<>();
3427 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3428 }
3429 alarmsForUid.add(alarm);
3430 continue;
3431 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003432
Christopher Tatee0a22b32013-07-11 14:43:13 -07003433 alarm.count = 1;
3434 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003435 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3436 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003437 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003438 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003439 if (mPendingIdleUntil == alarm) {
3440 mPendingIdleUntil = null;
3441 rebatchAllAlarmsLocked(false);
3442 restorePendingWhileIdleAlarmsLocked();
3443 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003444 if (mNextWakeFromIdle == alarm) {
3445 mNextWakeFromIdle = null;
3446 rebatchAllAlarmsLocked(false);
3447 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003448
3449 // Recurring alarms may have passed several alarm intervals while the
3450 // phone was asleep or off, so pass a trigger count when sending them.
3451 if (alarm.repeatInterval > 0) {
3452 // this adjustment will be zero if we're late by
3453 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003454 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003455
3456 // Also schedule its next recurrence
3457 final long delta = alarm.count * alarm.repeatInterval;
3458 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003459 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003460 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003461 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3462 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003463 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003464
Christopher Tate864d42e2014-12-02 11:48:53 -08003465 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003466 hasWakeup = true;
3467 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003468
3469 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3470 if (alarm.alarmClock != null) {
3471 mNextAlarmClockMayChange = true;
3472 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003473 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003474 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003475
Christopher Tate1590f1e2014-10-02 17:27:57 -07003476 // This is a new alarm delivery set; bump the sequence number to indicate that
3477 // all apps' alarm delivery classes should be recalculated.
3478 mCurrentSeq++;
3479 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003480 Collections.sort(triggerList, mAlarmDispatchComparator);
3481
3482 if (localLOGV) {
3483 for (int i=0; i<triggerList.size(); i++) {
3484 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3485 }
3486 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003487
3488 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003490
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 /**
3492 * This Comparator sorts Alarms into increasing time order.
3493 */
3494 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3495 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003496 long when1 = a1.whenElapsed;
3497 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003498 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003499 return 1;
3500 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003501 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502 return -1;
3503 }
3504 return 0;
3505 }
3506 }
Kweku Adams61e03292017-10-19 14:27:12 -07003507
Makoto Onuki2206af32017-11-21 16:25:35 -08003508 @VisibleForTesting
3509 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003510 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003511 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003512 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003513 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003514 public final IAlarmListener listener;
3515 public final String listenerTag;
3516 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003517 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003518 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003519 public final AlarmManager.AlarmClockInfo alarmClock;
3520 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003521 public final int creatorUid;
3522 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003523 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524 public int count;
3525 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003526 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003527 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003528 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003529 // Expected alarm expiry time before app standby deferring is applied.
3530 public long expectedWhenElapsed;
3531 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003533 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003534
Christopher Tate3e04b472013-10-21 17:51:31 -07003535 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003536 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3537 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3538 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003539 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003540 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003541 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3542 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003543 when = _when;
3544 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003545 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003546 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003547 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003548 repeatInterval = _interval;
3549 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003550 listener = _rec;
3551 listenerTag = _listenerTag;
3552 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003553 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003554 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003555 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003556 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003557 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003558 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003559 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003560 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003561
Christopher Tate14a7bb02015-10-01 10:24:31 -07003562 public static String makeTag(PendingIntent pi, String tag, int type) {
3563 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3564 ? "*walarm*:" : "*alarm*:";
3565 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3566 }
3567
3568 public WakeupEvent makeWakeupEvent(long nowRTC) {
3569 return new WakeupEvent(nowRTC, creatorUid,
3570 (operation != null)
3571 ? operation.getIntent().getAction()
3572 : ("<listener>:" + listenerTag));
3573 }
3574
3575 // Returns true if either matches
3576 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3577 return (operation != null)
3578 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003579 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003580 }
3581
3582 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003583 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003584 }
3585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003587 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003588 StringBuilder sb = new StringBuilder(128);
3589 sb.append("Alarm{");
3590 sb.append(Integer.toHexString(System.identityHashCode(this)));
3591 sb.append(" type ");
3592 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003593 sb.append(" when ");
3594 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003595 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003596 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003597 sb.append('}');
3598 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003599 }
3600
Kweku Adams61e03292017-10-19 14:27:12 -07003601 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003602 SimpleDateFormat sdf) {
3603 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003604 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003605 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003606 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3607 expectedWhenElapsed, nowELAPSED, pw);
3608 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3609 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003610 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3611 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003612 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3613 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003614 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003615 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003616 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003617 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003618 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003619 }
3620 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003621 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003622 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003623 pw.print(" count="); pw.print(count);
3624 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003625 if (alarmClock != null) {
3626 pw.print(prefix); pw.println("Alarm clock:");
3627 pw.print(prefix); pw.print(" triggerTime=");
3628 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3629 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3630 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003631 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003632 if (listener != null) {
3633 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003635 }
Kweku Adams61e03292017-10-19 14:27:12 -07003636
3637 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3638 long nowRTC) {
3639 final long token = proto.start(fieldId);
3640
3641 proto.write(AlarmProto.TAG, statsTag);
3642 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003643 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003644 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3645 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3646 proto.write(AlarmProto.COUNT, count);
3647 proto.write(AlarmProto.FLAGS, flags);
3648 if (alarmClock != null) {
3649 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3650 }
3651 if (operation != null) {
3652 operation.writeToProto(proto, AlarmProto.OPERATION);
3653 }
3654 if (listener != null) {
3655 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3656 }
3657
3658 proto.end(token);
3659 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003661
Christopher Tatee0a22b32013-07-11 14:43:13 -07003662 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3663 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003664 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3665 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003666 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003667 break;
3668 }
3669
Christopher Tatee0a22b32013-07-11 14:43:13 -07003670 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003671 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3672 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003673 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003674 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003675 }
3676 }
3677
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003678 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3679 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3680 if (timeSinceOn < 5*60*1000) {
3681 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3682 return 2*60*1000;
3683 } else if (timeSinceOn < 30*60*1000) {
3684 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3685 return 15*60*1000;
3686 } else {
3687 // Otherwise, we will delay by at most an hour.
3688 return 60*60*1000;
3689 }
3690 }
3691
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003692 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003693 if (duration < 15*60*1000) {
3694 // If the duration until the time is less than 15 minutes, the maximum fuzz
3695 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003696 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003697 } else if (duration < 90*60*1000) {
3698 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3699 return 15*60*1000;
3700 } else {
3701 // Otherwise, we will fuzz by at most half an hour.
3702 return 30*60*1000;
3703 }
3704 }
3705
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003706 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3707 if (mInteractive) {
3708 return false;
3709 }
3710 if (mLastAlarmDeliveryTime <= 0) {
3711 return false;
3712 }
minho.choo649acab2014-12-12 16:13:55 +09003713 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003714 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3715 // and the next delivery time is in the past, then just deliver them all. This
3716 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3717 return false;
3718 }
3719 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3720 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3721 }
3722
3723 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3724 mLastAlarmDeliveryTime = nowELAPSED;
3725 for (int i=0; i<triggerList.size(); i++) {
3726 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003727 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003728 if (alarm.wakeup) {
3729 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3730 } else {
3731 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3732 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003733 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003734 if (localLOGV) {
3735 Slog.v(TAG, "sending alarm " + alarm);
3736 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003737 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003738 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3739 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003740 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003742 } catch (RuntimeException e) {
3743 Slog.w(TAG, "Failure sending alarm.", e);
3744 }
Tim Murray175c0f92017-11-28 15:01:04 -08003745 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003746 }
3747 }
3748
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003749 private boolean isExemptFromAppStandby(Alarm a) {
3750 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3751 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3752 }
3753
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003754 @VisibleForTesting
3755 static class Injector {
3756 private long mNativeData;
3757 private Context mContext;
3758
3759 Injector(Context context) {
3760 mContext = context;
3761 }
3762
3763 void init() {
3764 mNativeData = AlarmManagerService.init();
3765 }
3766
3767 int waitForAlarm() {
3768 return AlarmManagerService.waitForAlarm(mNativeData);
3769 }
3770
3771 boolean isAlarmDriverPresent() {
3772 return mNativeData != 0;
3773 }
3774
3775 void setAlarm(int type, long millis) {
3776 // The kernel never triggers alarms with negative wakeup times
3777 // so we ensure they are positive.
3778 final long alarmSeconds, alarmNanoseconds;
3779 if (millis < 0) {
3780 alarmSeconds = 0;
3781 alarmNanoseconds = 0;
3782 } else {
3783 alarmSeconds = millis / 1000;
3784 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3785 }
3786
3787 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3788 alarmNanoseconds);
3789 if (result != 0) {
3790 final long nowElapsed = SystemClock.elapsedRealtime();
3791 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3792 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3793 + "), ret = " + result + " = " + Os.strerror(result));
3794 }
3795 }
3796
3797 long getNextAlarm(int type) {
3798 return AlarmManagerService.getNextAlarm(mNativeData, type);
3799 }
3800
3801 void setKernelTimezone(int minutesWest) {
3802 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3803 }
3804
3805 void setKernelTime(long millis) {
3806 if (mNativeData != 0) {
3807 AlarmManagerService.setKernelTime(mNativeData, millis);
3808 }
3809 }
3810
3811 void close() {
3812 AlarmManagerService.close(mNativeData);
3813 }
3814
3815 long getElapsedRealtime() {
3816 return SystemClock.elapsedRealtime();
3817 }
3818
3819 long getCurrentTimeMillis() {
3820 return System.currentTimeMillis();
3821 }
3822
3823 PowerManager.WakeLock getAlarmWakeLock() {
3824 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3825 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3826 }
3827
3828 int getSystemUiUid() {
3829 int sysUiUid = -1;
3830 final PackageManager pm = mContext.getPackageManager();
3831 try {
3832 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3833 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3834 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3835 sysUiUid = sysUi.uid;
3836 } else {
3837 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3838 + " defined by non-privileged app " + sysUi.packageName
3839 + " - ignoring");
3840 }
3841 } catch (NameNotFoundException e) {
3842 }
3843 return sysUiUid;
3844 }
3845
3846 ClockReceiver getClockReceiver(AlarmManagerService service) {
3847 return service.new ClockReceiver();
3848 }
3849 }
3850
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003851 private class AlarmThread extends Thread
3852 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003853 private int mFalseWakeups;
3854 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003855 public AlarmThread()
3856 {
3857 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003858 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003859 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003860 }
Kweku Adams61e03292017-10-19 14:27:12 -07003861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003862 public void run()
3863 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003864 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3865
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003866 while (true)
3867 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003868 int result = mInjector.waitForAlarm();
3869 final long nowRTC = mInjector.getCurrentTimeMillis();
3870 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003871 synchronized (mLock) {
3872 mLastWakeup = nowELAPSED;
3873 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003874 if (result == 0) {
3875 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3876 + ", nowElapsed = " + nowELAPSED);
3877 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003878 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003879
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003880 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003881 // The kernel can give us spurious time change notifications due to
3882 // small adjustments it makes internally; we want to filter those out.
3883 final long lastTimeChangeClockTime;
3884 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003885 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003886 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3887 expectedClockTime = lastTimeChangeClockTime
3888 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003889 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003890 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3891 || nowRTC > (expectedClockTime+1000)) {
3892 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003893 // let's do it!
3894 if (DEBUG_BATCH) {
3895 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3896 }
Bookatz7948c872018-09-04 12:58:33 -07003897 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3898 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003899 removeImpl(null, mTimeTickTrigger);
3900 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003901 rebatchAllAlarms();
3902 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003903 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003904 synchronized (mLock) {
3905 mNumTimeChanged++;
3906 mLastTimeChangeClockTime = nowRTC;
3907 mLastTimeChangeRealtime = nowELAPSED;
3908 }
3909 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3910 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003911 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003912 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3913 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003914 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3915
3916 // The world has changed on us, so we need to re-evaluate alarms
3917 // regardless of whether the kernel has told us one went off.
3918 result |= IS_WAKEUP_MASK;
3919 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921
Dianne Hackbornc3527222015-05-13 14:03:20 -07003922 if (result != TIME_CHANGED_MASK) {
3923 // If this was anything besides just a time change, then figure what if
3924 // anything to do about alarms.
3925 synchronized (mLock) {
3926 if (localLOGV) Slog.v(
3927 TAG, "Checking for alarms... rtc=" + nowRTC
3928 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003929
Dianne Hackbornc3527222015-05-13 14:03:20 -07003930 if (WAKEUP_STATS) {
3931 if ((result & IS_WAKEUP_MASK) != 0) {
3932 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3933 int n = 0;
3934 for (WakeupEvent event : mRecentWakeups) {
3935 if (event.when > newEarliest) break;
3936 n++; // number of now-stale entries at the list head
3937 }
3938 for (int i = 0; i < n; i++) {
3939 mRecentWakeups.remove();
3940 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003941
Dianne Hackbornc3527222015-05-13 14:03:20 -07003942 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003943 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003944 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003945
Christopher Tate8b98ade2018-02-09 11:13:19 -08003946 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003947 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3948 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3949 // if there are no wakeup alarms and the screen is off, we can
3950 // delay what we have so far until the future.
3951 if (mPendingNonWakeupAlarms.size() == 0) {
3952 mStartCurrentDelayTime = nowELAPSED;
3953 mNextNonWakeupDeliveryTime = nowELAPSED
3954 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3955 }
3956 mPendingNonWakeupAlarms.addAll(triggerList);
3957 mNumDelayedAlarms += triggerList.size();
3958 rescheduleKernelAlarmsLocked();
3959 updateNextAlarmClockLocked();
3960 } else {
3961 // now deliver the alarm intents; if there are pending non-wakeup
3962 // alarms, we need to merge them in to the list. note we don't
3963 // just deliver them first because we generally want non-wakeup
3964 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003965 if (mPendingNonWakeupAlarms.size() > 0) {
3966 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3967 triggerList.addAll(mPendingNonWakeupAlarms);
3968 Collections.sort(triggerList, mAlarmDispatchComparator);
3969 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3970 mTotalDelayTime += thisDelayTime;
3971 if (mMaxDelayTime < thisDelayTime) {
3972 mMaxDelayTime = thisDelayTime;
3973 }
3974 mPendingNonWakeupAlarms.clear();
3975 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003976 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3977 if (++mFalseWakeups >= mWtfThreshold) {
3978 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3979 + ") false wakeups, nowElapsed=" + nowELAPSED);
3980 if (mWtfThreshold < 100_000) {
3981 mWtfThreshold *= 10;
3982 } else {
3983 mFalseWakeups = 0;
3984 }
3985 }
3986 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003987 final ArraySet<Pair<String, Integer>> triggerPackages =
3988 new ArraySet<>();
3989 for (int i = 0; i < triggerList.size(); i++) {
3990 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003991 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003992 triggerPackages.add(Pair.create(
3993 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003994 }
3995 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003996 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003997 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3998 rescheduleKernelAlarmsLocked();
3999 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07004000 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004001 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07004002
4003 } else {
4004 // Just in case -- even though no wakeup flag was set, make sure
4005 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07004006 synchronized (mLock) {
4007 rescheduleKernelAlarmsLocked();
4008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 }
4010 }
4011 }
4012 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07004013
David Christieebe51fc2013-07-26 13:23:29 -07004014 /**
4015 * Attribute blame for a WakeLock.
4016 * @param pi PendingIntent to attribute blame to if ws is null.
4017 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07004018 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07004019 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07004020 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07004021 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07004022 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07004023 mWakeLock.setHistoryTag(first ? tag : null);
4024
David Christieebe51fc2013-07-26 13:23:29 -07004025 if (ws != null) {
4026 mWakeLock.setWorkSource(ws);
4027 return;
4028 }
4029
Christopher Tate14a7bb02015-10-01 10:24:31 -07004030 final int uid = (knownUid >= 0)
4031 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08004032 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07004033 if (uid >= 0) {
4034 mWakeLock.setWorkSource(new WorkSource(uid));
4035 return;
4036 }
4037 } catch (Exception e) {
4038 }
4039
4040 // Something went wrong; fall back to attributing the lock to the OS
4041 mWakeLock.setWorkSource(null);
4042 }
4043
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004044 @VisibleForTesting
4045 class AlarmHandler extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004046 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004047 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
4048 public static final int LISTENER_TIMEOUT = 3;
4049 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08004050 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
4051 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08004052 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07004053
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004054 AlarmHandler() {
4055 super(Looper.myLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004056 }
Kweku Adams61e03292017-10-19 14:27:12 -07004057
Makoto Onuki4d298b52018-02-05 10:54:58 -08004058 public void postRemoveForStopped(int uid) {
4059 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
4060 }
4061
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004062 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004063 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004064 switch (msg.what) {
4065 case ALARM_EVENT: {
4066 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
4067 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004068 final long nowRTC = mInjector.getCurrentTimeMillis();
4069 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004070 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
4071 updateNextAlarmClockLocked();
4072 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02004073
Christopher Tate14a7bb02015-10-01 10:24:31 -07004074 // now trigger the alarms without the lock held
4075 for (int i=0; i<triggerList.size(); i++) {
4076 Alarm alarm = triggerList.get(i);
4077 try {
4078 alarm.operation.send();
4079 } catch (PendingIntent.CanceledException e) {
4080 if (alarm.repeatInterval > 0) {
4081 // This IntentSender is no longer valid, but this
4082 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07004083 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004084 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004085 }
4086 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004087 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004089
4090 case SEND_NEXT_ALARM_CLOCK_CHANGED:
4091 sendNextAlarmClockChanged();
4092 break;
4093
4094 case LISTENER_TIMEOUT:
4095 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
4096 break;
4097
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004098 case REPORT_ALARMS_ACTIVE:
4099 if (mLocalDeviceIdleController != null) {
4100 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
4101 }
4102 break;
4103
Suprabh Shukla75edab12018-01-29 14:09:06 -08004104 case APP_STANDBY_PAROLE_CHANGED:
4105 synchronized (mLock) {
4106 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004107 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
4108 rescheduleKernelAlarmsLocked();
4109 updateNextAlarmClockLocked();
4110 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004111 }
4112 break;
4113
4114 case APP_STANDBY_BUCKET_CHANGED:
4115 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004116 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
4117 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
4118 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
4119 rescheduleKernelAlarmsLocked();
4120 updateNextAlarmClockLocked();
4121 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004122 }
4123 break;
4124
Makoto Onuki4d298b52018-02-05 10:54:58 -08004125 case REMOVE_FOR_STOPPED:
4126 synchronized (mLock) {
4127 removeForStoppedLocked(msg.arg1);
4128 }
4129 break;
4130
Christopher Tate14a7bb02015-10-01 10:24:31 -07004131 default:
4132 // nope, just ignore it
4133 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
4135 }
4136 }
Kweku Adams61e03292017-10-19 14:27:12 -07004137
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004138 class ClockReceiver extends BroadcastReceiver {
4139 public ClockReceiver() {
4140 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004141 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004142 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004143 }
Kweku Adams61e03292017-10-19 14:27:12 -07004144
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004145 @Override
4146 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07004147 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 // Since the kernel does not keep track of DST, we need to
4149 // reset the TZ information at the beginning of each day
4150 // based off of the current Zone gmt offset + userspace tracked
4151 // daylight savings information.
4152 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004153 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
4154 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07004155 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004156 }
4157 }
Kweku Adams61e03292017-10-19 14:27:12 -07004158
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004159 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004160 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09004161 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07004162
4163 // Schedule this event for the amount of time that it would take to get to
4164 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09004165 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07004166
David Christieebe51fc2013-07-26 13:23:29 -07004167 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004168 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Suprabh Shukla12bd0162018-11-12 18:00:18 -08004169 0, null, mTimeTickTrigger, "TIME_TICK", AlarmManager.FLAG_STANDALONE,
4170 workSource, null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08004171
4172 // Finally, remember when we set the tick alarm
4173 synchronized (mLock) {
4174 mLastTickSet = currentTime;
4175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004176 }
Christopher Tate385e4982013-07-23 18:22:29 -07004177
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 public void scheduleDateChangedEvent() {
4179 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004180 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07004181 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004182 calendar.set(Calendar.MINUTE, 0);
4183 calendar.set(Calendar.SECOND, 0);
4184 calendar.set(Calendar.MILLISECOND, 0);
4185 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07004186
4187 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07004188 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
4189 AlarmManager.FLAG_STANDALONE, workSource, null,
4190 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004191 }
4192 }
Kweku Adams61e03292017-10-19 14:27:12 -07004193
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07004194 class InteractiveStateReceiver extends BroadcastReceiver {
4195 public InteractiveStateReceiver() {
4196 IntentFilter filter = new IntentFilter();
4197 filter.addAction(Intent.ACTION_SCREEN_OFF);
4198 filter.addAction(Intent.ACTION_SCREEN_ON);
4199 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
4200 getContext().registerReceiver(this, filter);
4201 }
4202
4203 @Override
4204 public void onReceive(Context context, Intent intent) {
4205 synchronized (mLock) {
4206 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
4207 }
4208 }
4209 }
4210
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004211 class UninstallReceiver extends BroadcastReceiver {
4212 public UninstallReceiver() {
4213 IntentFilter filter = new IntentFilter();
4214 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
4215 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004216 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004217 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08004218 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004219 // Register for events related to sdcard installation.
4220 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004221 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004222 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004223 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004224 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004225 }
Kweku Adams61e03292017-10-19 14:27:12 -07004226
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004227 @Override
4228 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004229 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004230 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004231 String pkgList[] = null;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004232 switch (intent.getAction()) {
4233 case Intent.ACTION_QUERY_PACKAGE_RESTART:
4234 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4235 for (String packageName : pkgList) {
4236 if (lookForPackageLocked(packageName)) {
4237 setResultCode(Activity.RESULT_OK);
4238 return;
Suprabh Shukla75edab12018-01-29 14:09:06 -08004239 }
4240 }
Dianne Hackborn409578f2010-03-10 17:23:43 -08004241 return;
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004242 case Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE:
4243 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
4244 break;
4245 case Intent.ACTION_USER_STOPPED:
4246 final int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4247 if (userHandle >= 0) {
4248 removeUserLocked(userHandle);
4249 mAppWakeupHistory.removeForUser(userHandle);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004250 }
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004251 return;
4252 case Intent.ACTION_UID_REMOVED:
4253 if (uid >= 0) {
4254 mLastAllowWhileIdleDispatch.delete(uid);
4255 mUseAllowWhileIdleShortTime.delete(uid);
4256 }
4257 return;
4258 case Intent.ACTION_PACKAGE_REMOVED:
4259 if (intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4260 // This package is being updated; don't kill its alarms.
4261 return;
4262 }
4263 // Intentional fall-through.
4264 case Intent.ACTION_PACKAGE_RESTARTED:
4265 final Uri data = intent.getData();
4266 if (data != null) {
4267 final String pkg = data.getSchemeSpecificPart();
4268 if (pkg != null) {
4269 pkgList = new String[]{pkg};
4270 }
4271 }
4272 break;
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004273 }
4274 if (pkgList != null && (pkgList.length > 0)) {
4275 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004276 if (uid >= 0) {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004277 // package-removed and package-restarted case
4278 mAppWakeupHistory.removeForPackage(pkg, UserHandle.getUserId(uid));
Christopher Tate1d99c392017-12-07 16:54:04 -08004279 removeLocked(uid);
4280 } else {
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004281 // external-applications-unavailable case
Christopher Tate1d99c392017-12-07 16:54:04 -08004282 removeLocked(pkg);
4283 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004284 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004285 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4286 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4287 if (uidStats.remove(pkg) != null) {
4288 if (uidStats.size() <= 0) {
4289 mBroadcastStats.removeAt(i);
4290 }
4291 }
4292 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004293 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004294 }
4295 }
4296 }
4297 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004298
4299 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004300 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004301 }
4302
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004303 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004304 if (disabled) {
4305 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004306 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004307 }
4308
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004309 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004310 }
4311
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004312 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004313 if (disabled) {
4314 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004315 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004316 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004317
4318 @Override public void onUidCachedChanged(int uid, boolean cached) {
4319 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004320 };
4321
Suprabh Shukla75edab12018-01-29 14:09:06 -08004322 /**
4323 * Tracking of app assignments to standby buckets
4324 */
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004325 private final class AppStandbyTracker extends
4326 UsageStatsManagerInternal.AppIdleStateChangeListener {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004327 @Override
4328 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004329 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004330 if (DEBUG_STANDBY) {
4331 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4332 bucket);
4333 }
4334 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004335 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4336 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004337 }
4338
4339 @Override
4340 public void onParoleStateChanged(boolean isParoleOn) {
4341 if (DEBUG_STANDBY) {
4342 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4343 }
4344 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4345 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4346 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4347 Boolean.valueOf(isParoleOn)).sendToTarget();
4348 }
4349 };
4350
Makoto Onuki2206af32017-11-21 16:25:35 -08004351 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004352 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004353 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004354 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004355 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004356 }
4357 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004358
4359 @Override
4360 public void unblockAlarmsForUid(int uid) {
4361 synchronized (mLock) {
4362 sendPendingBackgroundAlarmsLocked(uid, null);
4363 }
4364 }
4365
4366 @Override
4367 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4368 synchronized (mLock) {
4369 sendPendingBackgroundAlarmsLocked(uid, packageName);
4370 }
4371 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004372
4373 @Override
4374 public void onUidForeground(int uid, boolean foreground) {
4375 synchronized (mLock) {
4376 if (foreground) {
4377 mUseAllowWhileIdleShortTime.put(uid, true);
4378
4379 // Note we don't have to drain the pending while-idle alarms here, because
4380 // this event should coincide with unblockAlarmsForUid().
4381 }
4382 }
4383 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004384 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004386 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004387 String pkg = pi.getCreatorPackage();
4388 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004389 return getStatsLocked(uid, pkg);
4390 }
4391
4392 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004393 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4394 if (uidStats == null) {
4395 uidStats = new ArrayMap<String, BroadcastStats>();
4396 mBroadcastStats.put(uid, uidStats);
4397 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004398 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004399 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004400 bs = new BroadcastStats(uid, pkgName);
4401 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004402 }
4403 return bs;
4404 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004405
Christopher Tate21e9f192017-08-08 13:49:11 -07004406 /**
4407 * Canonical count of (operation.send() - onSendFinished()) and
4408 * listener send/complete/timeout invocations.
4409 * Guarded by the usual lock.
4410 */
4411 @GuardedBy("mLock")
4412 private int mSendCount = 0;
4413 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004414 private int mSendFinishCount = 0;
4415 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004416 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004417 @GuardedBy("mLock")
4418 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004419
Christopher Tate14a7bb02015-10-01 10:24:31 -07004420 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004421
Christopher Tate14a7bb02015-10-01 10:24:31 -07004422 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4423 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004424 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004425 return mInFlight.remove(i);
4426 }
4427 }
4428 mLog.w("No in-flight alarm for " + pi + " " + intent);
4429 return null;
4430 }
4431
4432 private InFlight removeLocked(IBinder listener) {
4433 for (int i = 0; i < mInFlight.size(); i++) {
4434 if (mInFlight.get(i).mListener == listener) {
4435 return mInFlight.remove(i);
4436 }
4437 }
4438 mLog.w("No in-flight alarm for listener " + listener);
4439 return null;
4440 }
4441
4442 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004443 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004444 BroadcastStats bs = inflight.mBroadcastStats;
4445 bs.nesting--;
4446 if (bs.nesting <= 0) {
4447 bs.nesting = 0;
4448 bs.aggregateTime += nowELAPSED - bs.startTime;
4449 }
4450 FilterStats fs = inflight.mFilterStats;
4451 fs.nesting--;
4452 if (fs.nesting <= 0) {
4453 fs.nesting = 0;
4454 fs.aggregateTime += nowELAPSED - fs.startTime;
4455 }
4456 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004457 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4458 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004459 }
4460 }
4461
4462 private void updateTrackingLocked(InFlight inflight) {
4463 if (inflight != null) {
4464 updateStatsLocked(inflight);
4465 }
4466 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004467 if (DEBUG_WAKELOCK) {
4468 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4469 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004470 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004471 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004472 mWakeLock.release();
4473 if (mInFlight.size() > 0) {
4474 mLog.w("Finished all dispatches with " + mInFlight.size()
4475 + " remaining inflights");
4476 for (int i=0; i<mInFlight.size(); i++) {
4477 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4478 }
4479 mInFlight.clear();
4480 }
4481 } else {
4482 // the next of our alarms is now in flight. reattribute the wakelock.
4483 if (mInFlight.size() > 0) {
4484 InFlight inFlight = mInFlight.get(0);
4485 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4486 inFlight.mAlarmType, inFlight.mTag, -1, false);
4487 } else {
4488 // should never happen
4489 mLog.w("Alarm wakelock still held but sent queue empty");
4490 mWakeLock.setWorkSource(null);
4491 }
4492 }
4493 }
4494
4495 /**
4496 * Callback that arrives when a direct-call alarm reports that delivery has finished
4497 */
4498 @Override
4499 public void alarmComplete(IBinder who) {
4500 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004501 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004502 + " pid=" + Binder.getCallingPid());
4503 return;
4504 }
4505
4506 final long ident = Binder.clearCallingIdentity();
4507 try {
4508 synchronized (mLock) {
4509 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4510 InFlight inflight = removeLocked(who);
4511 if (inflight != null) {
4512 if (DEBUG_LISTENER_CALLBACK) {
4513 Slog.i(TAG, "alarmComplete() from " + who);
4514 }
4515 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004516 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004517 } else {
4518 // Delivery timed out, and the timeout handling already took care of
4519 // updating our tracking here, so we needn't do anything further.
4520 if (DEBUG_LISTENER_CALLBACK) {
4521 Slog.i(TAG, "Late alarmComplete() from " + who);
4522 }
4523 }
4524 }
4525 } finally {
4526 Binder.restoreCallingIdentity(ident);
4527 }
4528 }
4529
4530 /**
4531 * Callback that arrives when a PendingIntent alarm has finished delivery
4532 */
4533 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004534 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4535 String resultData, Bundle resultExtras) {
4536 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004537 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004538 updateTrackingLocked(removeLocked(pi, intent));
4539 }
4540 }
4541
4542 /**
4543 * Timeout of a direct-call alarm delivery
4544 */
4545 public void alarmTimedOut(IBinder who) {
4546 synchronized (mLock) {
4547 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004548 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004549 // TODO: implement ANR policy for the target
4550 if (DEBUG_LISTENER_CALLBACK) {
4551 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004552 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004553 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004554 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004555 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004556 if (DEBUG_LISTENER_CALLBACK) {
4557 Slog.i(TAG, "Spurious timeout of listener " + who);
4558 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004559 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004560 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004561 }
4562 }
4563
4564 /**
4565 * Deliver an alarm and set up the post-delivery handling appropriately
4566 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004567 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004568 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4569 if (alarm.operation != null) {
4570 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004571 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004572
Christopher Tate14a7bb02015-10-01 10:24:31 -07004573 try {
4574 alarm.operation.send(getContext(), 0,
4575 mBackgroundIntent.putExtra(
4576 Intent.EXTRA_ALARM_COUNT, alarm.count),
4577 mDeliveryTracker, mHandler, null,
4578 allowWhileIdle ? mIdleOptions : null);
4579 } catch (PendingIntent.CanceledException e) {
4580 if (alarm.repeatInterval > 0) {
4581 // This IntentSender is no longer valid, but this
4582 // is a repeating alarm, so toss it
Christopher Tatec8b7f432018-09-28 16:23:10 -07004583 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004584 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004585 // No actual delivery was possible, so the delivery tracker's
4586 // 'finished' callback won't be invoked. We also don't need
4587 // to do any wakelock or stats tracking, so we have nothing
4588 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004589 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004590 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004591 }
4592 } else {
4593 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004594 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004595
4596 if (RECORD_ALARMS_IN_HISTORY) {
4597 if (alarm.listener == mTimeTickTrigger) {
4598 mTickHistory[mNextTickHistory++] = nowELAPSED;
4599 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4600 mNextTickHistory = 0;
4601 }
4602 }
4603 }
4604
Christopher Tate14a7bb02015-10-01 10:24:31 -07004605 try {
4606 if (DEBUG_LISTENER_CALLBACK) {
4607 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4608 + " listener=" + alarm.listener.asBinder());
4609 }
4610 alarm.listener.doAlarm(this);
4611 mHandler.sendMessageDelayed(
4612 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4613 alarm.listener.asBinder()),
4614 mConstants.LISTENER_TIMEOUT);
4615 } catch (Exception e) {
4616 if (DEBUG_LISTENER_CALLBACK) {
4617 Slog.i(TAG, "Alarm undeliverable to listener "
4618 + alarm.listener.asBinder(), e);
4619 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004620 // As in the PendingIntent.CanceledException case, delivery of the
4621 // alarm was not possible, so we have no wakelock or timeout or
4622 // stats management to do. It threw before we posted the delayed
4623 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004624 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004625 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004626 }
4627 }
4628
4629 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004630 if (DEBUG_WAKELOCK) {
4631 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4632 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004633 if (mBroadcastRefCount == 0) {
4634 setWakelockWorkSource(alarm.operation, alarm.workSource,
4635 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4636 true);
4637 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004638 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004639 }
4640 final InFlight inflight = new InFlight(AlarmManagerService.this,
4641 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4642 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4643 mInFlight.add(inflight);
4644 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004645 if (allowWhileIdle) {
4646 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004647 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004648 if ((mAppStateTracker == null)
4649 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004650 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4651 } else {
4652 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4653 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004654 if (RECORD_DEVICE_IDLE_ALARMS) {
4655 IdleDispatchEntry ent = new IdleDispatchEntry();
4656 ent.uid = alarm.uid;
4657 ent.pkg = alarm.packageName;
4658 ent.tag = alarm.statsTag;
4659 ent.op = "DELIVER";
4660 ent.elapsedRealtime = nowELAPSED;
4661 mAllowWhileIdleDispatches.add(ent);
4662 }
4663 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004664 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004665 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4666 UserHandle.getUserId(alarm.creatorUid));
Suprabh Shukla47ca6fc2019-01-15 18:15:10 -08004667 mAppWakeupHistory.recordAlarmForPackage(alarm.sourcePackage,
4668 UserHandle.getUserId(alarm.creatorUid), nowELAPSED);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004669 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004670
4671 final BroadcastStats bs = inflight.mBroadcastStats;
4672 bs.count++;
4673 if (bs.nesting == 0) {
4674 bs.nesting = 1;
4675 bs.startTime = nowELAPSED;
4676 } else {
4677 bs.nesting++;
4678 }
4679 final FilterStats fs = inflight.mFilterStats;
4680 fs.count++;
4681 if (fs.nesting == 0) {
4682 fs.nesting = 1;
4683 fs.startTime = nowELAPSED;
4684 } else {
4685 fs.nesting++;
4686 }
4687 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4688 || alarm.type == RTC_WAKEUP) {
4689 bs.numWakeup++;
4690 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004691 ActivityManager.noteWakeupAlarm(
4692 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4693 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004694 }
4695 }
4696 }
mswest463f4c99d2018-02-01 10:13:10 -08004697
4698 private class ShellCmd extends ShellCommand {
4699
4700 IAlarmManager getBinderService() {
4701 return IAlarmManager.Stub.asInterface(mService);
4702 }
4703
4704 @Override
4705 public int onCommand(String cmd) {
4706 if (cmd == null) {
4707 return handleDefaultCommands(cmd);
4708 }
4709
4710 final PrintWriter pw = getOutPrintWriter();
4711 try {
4712 switch (cmd) {
4713 case "set-time":
4714 final long millis = Long.parseLong(getNextArgRequired());
4715 return (getBinderService().setTime(millis)) ? 0 : -1;
4716 case "set-timezone":
4717 final String tz = getNextArgRequired();
4718 getBinderService().setTimeZone(tz);
4719 return 0;
4720 default:
4721 return handleDefaultCommands(cmd);
4722 }
4723 } catch (Exception e) {
4724 pw.println(e);
4725 }
4726 return -1;
4727 }
4728
4729 @Override
4730 public void onHelp() {
4731 PrintWriter pw = getOutPrintWriter();
4732 pw.println("Alarm manager service (alarm) commands:");
4733 pw.println(" help");
4734 pw.println(" Print this help text.");
4735 pw.println(" set-time TIME");
4736 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4737 pw.println(" since the Epoch.");
4738 pw.println(" set-timezone TZ");
4739 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4740 }
4741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004742}