blob: 64bbbb9b15563c192202d41c9d28fe028b95784e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Suprabh Shukla75edab12018-01-29 14:09:06 -080019import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080020import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020021import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070022import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070023import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070024import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070025import android.app.IAlarmCompleteListener;
26import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070028import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080029import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080030import android.app.usage.UsageStatsManager;
31import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070033import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.content.Context;
35import android.content.Intent;
36import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070037import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070039import android.content.pm.PackageManager.NameNotFoundException;
40import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070041import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.net.Uri;
43import android.os.Binder;
44import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070045import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080047import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.os.Message;
49import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070050import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070051import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.SystemClock;
53import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080054import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070055import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070056import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020057import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020059import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080060import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070061import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020062import android.util.Log;
Suprabh Shukla75edab12018-01-29 14:09:06 -080063import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080064import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080065import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020066import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070067import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070068import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070069import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070
Christopher Tate4cb338d2013-07-26 13:11:31 -070071import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.io.FileDescriptor;
73import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070074import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080076import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import java.util.Calendar;
78import java.util.Collections;
79import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050080import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070081import java.util.HashMap;
Suprabh Shukla75edab12018-01-29 14:09:06 -080082import java.util.HashSet;
Christopher Tate18a75f12013-07-01 18:18:59 -070083import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020084import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070085import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040087import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -080088import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Suprabh Shuklac25447d2018-01-19 16:43:35 -080090import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Christopher Tatee0a22b32013-07-11 14:43:13 -070091import static android.app.AlarmManager.RTC_WAKEUP;
92import static android.app.AlarmManager.RTC;
93import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
94import static android.app.AlarmManager.ELAPSED_REALTIME;
95
Christopher Tate21e9f192017-08-08 13:49:11 -070096import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080097import com.android.internal.annotations.VisibleForTesting;
Makoto Onuki5d93b832018-01-10 16:12:39 -080098import com.android.internal.util.ArrayUtils;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060099import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -0800100import com.android.internal.util.LocalLog;
Makoto Onuki2206af32017-11-21 16:25:35 -0800101import com.android.server.ForceAppStandbyTracker.Listener;
Dianne Hackborn81038902012-11-26 17:04:09 -0800102
Makoto Onuki2206af32017-11-21 16:25:35 -0800103/**
104 * Alarm manager implementaion.
105 *
106 * Unit test:
107 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
108 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700110 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
111 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700113 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final int TIME_CHANGED_MASK = 1 << 16;
115 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800116
Christopher Tatee0a22b32013-07-11 14:43:13 -0700117 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800119
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 static final boolean localLOGV = false;
122 static final boolean DEBUG_BATCH = localLOGV || false;
123 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200124 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700125 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800126 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700127 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800128 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700129 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700130 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 static final int ALARM_EVENT = 1;
132 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200133
Christopher Tate14a7bb02015-10-01 10:24:31 -0700134 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800136 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700137
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700139
Christopher Tate24cd46f2016-02-02 14:28:01 -0800140 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
141 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700142 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
143 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200144
Adam Lesinski182f73f2013-12-05 16:48:06 -0800145 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800146
Christopher Tate14a7bb02015-10-01 10:24:31 -0700147 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800148 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800149 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700150
Adam Lesinski182f73f2013-12-05 16:48:06 -0800151 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800152
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700153 // List of alarms per uid deferred due to user applied background restrictions on the source app
154 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800155 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800156 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700157 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700158 private long mLastWakeupSet;
159 private long mLastWakeup;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800160 private long mLastTickSet;
161 private long mLastTickIssued; // elapsed
162 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800163 private long mLastTickAdded;
164 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800165 int mBroadcastRefCount = 0;
166 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700167 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700168 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
169 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800170 final AlarmHandler mHandler = new AlarmHandler();
171 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700172 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700174 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800175 PendingIntent mTimeTickSender;
176 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700177 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700178 boolean mInteractive = true;
179 long mNonInteractiveStartTime;
180 long mNonInteractiveTime;
181 long mLastAlarmDeliveryTime;
182 long mStartCurrentDelayTime;
183 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700184 long mLastTimeChangeClockTime;
185 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700186 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800187
Christopher Tatebb9cce52017-04-18 14:19:43 -0700188 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
189
190 /**
191 * This permission must be defined by the canonical System UI package,
192 * with protection level "signature".
193 */
194 private static final String SYSTEM_UI_SELF_PERMISSION =
195 "android.permission.systemui.IDENTITY";
196
197 /**
198 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
199 */
200 int mSystemUiUid;
201
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700202 /**
203 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700204 * used to determine the earliest we can dispatch the next such alarm. Times are in the
205 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700206 */
207 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
208
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800209 /**
210 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
211 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
212 */
213 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
214
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700215 final static class IdleDispatchEntry {
216 int uid;
217 String pkg;
218 String tag;
219 String op;
220 long elapsedRealtime;
221 long argRealtime;
222 }
223 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
224
Suprabh Shukla75edab12018-01-29 14:09:06 -0800225 interface Stats {
226 int REBATCH_ALL_ALARMS = 0;
227 }
228
229 private final StatLogger mStatLogger = new StatLogger(new String[] {
230 "REBATCH_ALL_ALARMS",
231 });
232
Dianne Hackborna750a632015-06-16 17:18:23 -0700233 /**
234 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
235 */
236 Bundle mIdleOptions;
237
Jose Lima235510e2014-08-13 12:50:01 -0700238 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
239 new SparseArray<>();
240 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
241 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200242 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
243 new SparseBooleanArray();
244 private boolean mNextAlarmClockMayChange;
245
246 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700247 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
248 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200249
Makoto Onuki2206af32017-11-21 16:25:35 -0800250 private final ForceAppStandbyTracker mForceAppStandbyTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800251 private boolean mAppStandbyParole;
252 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800253
Dianne Hackborna750a632015-06-16 17:18:23 -0700254 /**
255 * All times are in milliseconds. These constants are kept synchronized with the system
256 * global Settings. Any access to this class or its fields should be done while
257 * holding the AlarmManagerService.mLock lock.
258 */
259 private final class Constants extends ContentObserver {
260 // Key names stored in the settings value.
261 private static final String KEY_MIN_FUTURITY = "min_futurity";
262 private static final String KEY_MIN_INTERVAL = "min_interval";
263 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
264 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
265 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
266 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700267 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700268
Suprabh Shukla75edab12018-01-29 14:09:06 -0800269 // Keys for specifying throttling delay based on app standby bucketing
270 private final String[] KEYS_APP_STANDBY_DELAY = {
271 "standby_active_delay",
272 "standby_working_delay",
273 "standby_frequent_delay",
274 "standby_rare_delay",
275 "standby_never_delay",
276 };
277
Dianne Hackborna750a632015-06-16 17:18:23 -0700278 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
279 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700280 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700281 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700282 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700283 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800284 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
285 0, // Active
286 6 * 60_000, // Working
287 30 * 60_000, // Frequent
288 2 * 60 * 60_000, // Rare
289 10 * 24 * 60 * 60_000 // Never
290 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700291
Dianne Hackborna750a632015-06-16 17:18:23 -0700292 // Minimum futurity of a new alarm
293 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
294
295 // Minimum alarm recurrence interval
296 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
297
298 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
299 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
300
301 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
302 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
303
304 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
305 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
306 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
307
Christopher Tate14a7bb02015-10-01 10:24:31 -0700308 // Direct alarm listener callback timeout
309 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
310
Suprabh Shukla75edab12018-01-29 14:09:06 -0800311 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
312
Dianne Hackborna750a632015-06-16 17:18:23 -0700313 private ContentResolver mResolver;
314 private final KeyValueListParser mParser = new KeyValueListParser(',');
315 private long mLastAllowWhileIdleWhitelistDuration = -1;
316
317 public Constants(Handler handler) {
318 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700319 updateAllowWhileIdleWhitelistDurationLocked();
320 }
321
322 public void start(ContentResolver resolver) {
323 mResolver = resolver;
324 mResolver.registerContentObserver(Settings.Global.getUriFor(
325 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
326 updateConstants();
327 }
328
Dianne Hackborna750a632015-06-16 17:18:23 -0700329 public void updateAllowWhileIdleWhitelistDurationLocked() {
330 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
331 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
332 BroadcastOptions opts = BroadcastOptions.makeBasic();
333 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
334 mIdleOptions = opts.toBundle();
335 }
336 }
337
338 @Override
339 public void onChange(boolean selfChange, Uri uri) {
340 updateConstants();
341 }
342
343 private void updateConstants() {
344 synchronized (mLock) {
345 try {
346 mParser.setString(Settings.Global.getString(mResolver,
347 Settings.Global.ALARM_MANAGER_CONSTANTS));
348 } catch (IllegalArgumentException e) {
349 // Failed to parse the settings string, log this and move on
350 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800351 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700352 }
353
354 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
355 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
356 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
357 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
358 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
359 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
360 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
361 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
362 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700363 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
364 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800365 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
366 DEFAULT_APP_STANDBY_DELAYS[0]);
367 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
368 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
369 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
370 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700371 updateAllowWhileIdleWhitelistDurationLocked();
372 }
373 }
374
375 void dump(PrintWriter pw) {
376 pw.println(" Settings:");
377
378 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
379 TimeUtils.formatDuration(MIN_FUTURITY, pw);
380 pw.println();
381
382 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
383 TimeUtils.formatDuration(MIN_INTERVAL, pw);
384 pw.println();
385
Christopher Tate14a7bb02015-10-01 10:24:31 -0700386 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
387 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
388 pw.println();
389
Dianne Hackborna750a632015-06-16 17:18:23 -0700390 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
391 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
392 pw.println();
393
394 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
395 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
396 pw.println();
397
398 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
399 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
400 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800401
402 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
403 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
404 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
405 pw.println();
406 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700407 }
Kweku Adams61e03292017-10-19 14:27:12 -0700408
409 void dumpProto(ProtoOutputStream proto, long fieldId) {
410 final long token = proto.start(fieldId);
411
412 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
413 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
414 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
415 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
416 ALLOW_WHILE_IDLE_SHORT_TIME);
417 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
418 ALLOW_WHILE_IDLE_LONG_TIME);
419 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
420 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
421
422 proto.end(token);
423 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700424 }
425
426 final Constants mConstants;
427
Christopher Tate1590f1e2014-10-02 17:27:57 -0700428 // Alarm delivery ordering bookkeeping
429 static final int PRIO_TICK = 0;
430 static final int PRIO_WAKEUP = 1;
431 static final int PRIO_NORMAL = 2;
432
Dianne Hackborna750a632015-06-16 17:18:23 -0700433 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700434 int seq;
435 int priority;
436
437 PriorityClass() {
438 seq = mCurrentSeq - 1;
439 priority = PRIO_NORMAL;
440 }
441 }
442
Dianne Hackborna750a632015-06-16 17:18:23 -0700443 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700444 int mCurrentSeq = 0;
445
Dianne Hackborna750a632015-06-16 17:18:23 -0700446 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700447 public long when;
448 public int uid;
449 public String action;
450
451 public WakeupEvent(long theTime, int theUid, String theAction) {
452 when = theTime;
453 uid = theUid;
454 action = theAction;
455 }
456 }
457
Adam Lesinski182f73f2013-12-05 16:48:06 -0800458 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
459 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700460
Adrian Roosc42a1e12014-07-07 23:35:53 +0200461 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462 long start; // These endpoints are always in ELAPSED
463 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700464 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465
466 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
467
468 Batch() {
469 start = 0;
470 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700471 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700472 }
473
474 Batch(Alarm seed) {
475 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700476 end = seed.maxWhenElapsed;
477 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700478 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800479 if (seed.operation == mTimeTickSender) {
480 mLastTickAdded = System.currentTimeMillis();
481 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 }
483
484 int size() {
485 return alarms.size();
486 }
487
488 Alarm get(int index) {
489 return alarms.get(index);
490 }
491
492 boolean canHold(long whenElapsed, long maxWhen) {
493 return (end >= whenElapsed) && (start <= maxWhen);
494 }
495
496 boolean add(Alarm alarm) {
497 boolean newStart = false;
498 // narrows the batch if necessary; presumes that canHold(alarm) is true
499 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
500 if (index < 0) {
501 index = 0 - index - 1;
502 }
503 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800504 if (alarm.operation == mTimeTickSender) {
505 mLastTickAdded = System.currentTimeMillis();
506 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700507 if (DEBUG_BATCH) {
508 Slog.v(TAG, "Adding " + alarm + " to " + this);
509 }
510 if (alarm.whenElapsed > start) {
511 start = alarm.whenElapsed;
512 newStart = true;
513 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700514 if (alarm.maxWhenElapsed < end) {
515 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700516 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700517 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700518
519 if (DEBUG_BATCH) {
520 Slog.v(TAG, " => now " + this);
521 }
522 return newStart;
523 }
524
Christopher Tate1d99c392017-12-07 16:54:04 -0800525 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700526 boolean didRemove = false;
527 long newStart = 0; // recalculate endpoints as we go
528 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700529 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700530 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800532 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700533 alarms.remove(i);
534 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200535 if (alarm.alarmClock != null) {
536 mNextAlarmClockMayChange = true;
537 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800538 if (alarm.operation == mTimeTickSender) {
539 mLastTickRemoved = System.currentTimeMillis();
540 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541 } else {
542 if (alarm.whenElapsed > newStart) {
543 newStart = alarm.whenElapsed;
544 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700545 if (alarm.maxWhenElapsed < newEnd) {
546 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700547 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700548 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 i++;
550 }
551 }
552 if (didRemove) {
553 // commit the new batch bounds
554 start = newStart;
555 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700556 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557 }
558 return didRemove;
559 }
560
Christopher Tatee0a22b32013-07-11 14:43:13 -0700561 boolean hasPackage(final String packageName) {
562 final int N = alarms.size();
563 for (int i = 0; i < N; i++) {
564 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700565 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700566 return true;
567 }
568 }
569 return false;
570 }
571
572 boolean hasWakeups() {
573 final int N = alarms.size();
574 for (int i = 0; i < N; i++) {
575 Alarm a = alarms.get(i);
576 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
577 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
578 return true;
579 }
580 }
581 return false;
582 }
583
584 @Override
585 public String toString() {
586 StringBuilder b = new StringBuilder(40);
587 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
588 b.append(" num="); b.append(size());
589 b.append(" start="); b.append(start);
590 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700591 if (flags != 0) {
592 b.append(" flgs=0x");
593 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700594 }
595 b.append('}');
596 return b.toString();
597 }
Kweku Adams61e03292017-10-19 14:27:12 -0700598
599 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
600 long nowRTC) {
601 final long token = proto.start(fieldId);
602
603 proto.write(BatchProto.START_REALTIME, start);
604 proto.write(BatchProto.END_REALTIME, end);
605 proto.write(BatchProto.FLAGS, flags);
606 for (Alarm a : alarms) {
607 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
608 }
609
610 proto.end(token);
611 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700612 }
613
614 static class BatchTimeOrder implements Comparator<Batch> {
615 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800616 long when1 = b1.start;
617 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800618 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700619 return 1;
620 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800621 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700622 return -1;
623 }
624 return 0;
625 }
626 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800627
628 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
629 @Override
630 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700631 // priority class trumps everything. TICK < WAKEUP < NORMAL
632 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
633 return -1;
634 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
635 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800636 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700637
638 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800639 if (lhs.whenElapsed < rhs.whenElapsed) {
640 return -1;
641 } else if (lhs.whenElapsed > rhs.whenElapsed) {
642 return 1;
643 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700644
645 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800646 return 0;
647 }
648 };
649
Christopher Tate1590f1e2014-10-02 17:27:57 -0700650 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
651 final int N = alarms.size();
652 for (int i = 0; i < N; i++) {
653 Alarm a = alarms.get(i);
654
655 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700656 if (a.operation != null
657 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700658 alarmPrio = PRIO_TICK;
659 } else if (a.wakeup) {
660 alarmPrio = PRIO_WAKEUP;
661 } else {
662 alarmPrio = PRIO_NORMAL;
663 }
664
665 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800666 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700667 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700668 if (packagePrio == null) {
669 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700670 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700671 }
672 a.priorityClass = packagePrio;
673
674 if (packagePrio.seq != mCurrentSeq) {
675 // first alarm we've seen in the current delivery generation from this package
676 packagePrio.priority = alarmPrio;
677 packagePrio.seq = mCurrentSeq;
678 } else {
679 // Multiple alarms from this package being delivered in this generation;
680 // bump the package's delivery class if it's warranted.
681 // TICK < WAKEUP < NORMAL
682 if (alarmPrio < packagePrio.priority) {
683 packagePrio.priority = alarmPrio;
684 }
685 }
686 }
687 }
688
Christopher Tatee0a22b32013-07-11 14:43:13 -0700689 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800690 static final long MIN_FUZZABLE_INTERVAL = 10000;
691 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700692 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
693
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700694 // 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 -0700695 // to run during this time are placed in mPendingWhileIdleAlarms
696 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700697 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700698 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699
Jeff Brownb880d882014-02-10 19:47:07 -0800700 public AlarmManagerService(Context context) {
701 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700702 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800703
704 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
705 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Christopher Tate1d99c392017-12-07 16:54:04 -0800706
707 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800708 }
709
Christopher Tatee0a22b32013-07-11 14:43:13 -0700710 static long convertToElapsed(long when, int type) {
711 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
712 if (isRtc) {
713 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
714 }
715 return when;
716 }
717
718 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
719 // calculate the end of our nominal delivery window for the alarm.
720 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
721 // Current heuristic: batchable window is 75% of either the recurrence interval
722 // [for a periodic alarm] or of the time from now to the desired delivery time,
723 // with a minimum delay/interval of 10 seconds, under which we will simply not
724 // defer the alarm.
725 long futurity = (interval == 0)
726 ? (triggerAtTime - now)
727 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700728 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700729 futurity = 0;
730 }
731 return triggerAtTime + (long)(.75 * futurity);
732 }
733
734 // returns true if the batch was added at the head
735 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
736 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
737 if (index < 0) {
738 index = 0 - index - 1;
739 }
740 list.add(index, newBatch);
741 return (index == 0);
742 }
743
Christopher Tate385e4982013-07-23 18:22:29 -0700744 // Return the index of the matching batch, or -1 if none found.
745 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700746 final int N = mAlarmBatches.size();
747 for (int i = 0; i < N; i++) {
748 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700749 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700750 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700751 }
752 }
Christopher Tate385e4982013-07-23 18:22:29 -0700753 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700754 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800755 /** @return total count of the alarms in a set of alarm batches. */
756 static int getAlarmCount(ArrayList<Batch> batches) {
757 int ret = 0;
758
759 final int size = batches.size();
760 for (int i = 0; i < size; i++) {
761 ret += batches.get(i).size();
762 }
763 return ret;
764 }
765
766 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
767 if (alarms.size() == 0) {
768 return false;
769 }
770 final int batchSize = alarms.size();
771 for (int j = 0; j < batchSize; j++) {
772 if (alarms.get(j).operation == mTimeTickSender) {
773 return true;
774 }
775 }
776 return false;
777 }
778
779 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
780 final int numBatches = batches.size();
781 for (int i = 0; i < numBatches; i++) {
782 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
783 return true;
784 }
785 }
786 return false;
787 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700788
789 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
790 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700791 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700792 rebatchAllAlarmsLocked(true);
793 }
794 }
795
796 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800797 long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800798 final int oldCount =
799 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
800 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
801 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
802
Christopher Tate4cb338d2013-07-26 13:11:31 -0700803 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
804 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700805 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700806 final long nowElapsed = SystemClock.elapsedRealtime();
807 final int oldBatches = oldSet.size();
808 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
809 Batch batch = oldSet.get(batchNum);
810 final int N = batch.size();
811 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700812 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700813 }
814 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700815 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
816 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
817 + " to " + mPendingIdleUntil);
818 if (mPendingIdleUntil == null) {
819 // Somehow we lost this... we need to restore all of the pending alarms.
820 restorePendingWhileIdleAlarmsLocked();
821 }
822 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800823 final int newCount =
824 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
825 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
826 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
827
828 if (oldCount != newCount) {
829 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
830 }
831 if (oldHasTick != newHasTick) {
832 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
833 }
834
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700835 rescheduleKernelAlarmsLocked();
836 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800837 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700838 }
839
840 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
841 a.when = a.origWhen;
842 long whenElapsed = convertToElapsed(a.when, a.type);
843 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700844 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700845 // Exact
846 maxElapsed = whenElapsed;
847 } else {
848 // Not exact. Preserve any explicit window, otherwise recalculate
849 // the window based on the alarm's new futurity. Note that this
850 // reflects a policy of preferring timely to deferred delivery.
851 maxElapsed = (a.windowLength > 0)
852 ? (whenElapsed + a.windowLength)
853 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
854 }
855 a.whenElapsed = whenElapsed;
856 a.maxWhenElapsed = maxElapsed;
857 setImplLocked(a, true, doValidate);
858 }
859
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700860 /**
861 * Sends alarms that were blocked due to user applied background restrictions - either because
862 * the user lifted those or the uid came to foreground.
863 *
864 * @param uid uid to filter on
865 * @param packageName package to filter on, or null for all packages in uid
866 */
867 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
868 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
869 if (alarmsForUid == null || alarmsForUid.size() == 0) {
870 return;
871 }
872 final ArrayList<Alarm> alarmsToDeliver;
873 if (packageName != null) {
874 if (DEBUG_BG_LIMIT) {
875 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
876 }
877 alarmsToDeliver = new ArrayList<>();
878 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
879 final Alarm a = alarmsForUid.get(i);
880 if (a.matches(packageName)) {
881 alarmsToDeliver.add(alarmsForUid.remove(i));
882 }
883 }
884 if (alarmsForUid.size() == 0) {
885 mPendingBackgroundAlarms.remove(uid);
886 }
887 } else {
888 if (DEBUG_BG_LIMIT) {
889 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
890 }
891 alarmsToDeliver = alarmsForUid;
892 mPendingBackgroundAlarms.remove(uid);
893 }
894 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
895 }
896
Makoto Onuki2206af32017-11-21 16:25:35 -0800897 /**
898 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
899 * restricted.
900 *
901 * This is only called when the global "force all apps-standby" flag changes or when the
902 * power save whitelist changes, so it's okay to be slow.
903 */
904 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700905 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800906
907 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
908 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
909
910 if (alarmsToDeliver.size() > 0) {
911 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
912 }
913 }
914
915 @VisibleForTesting
916 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
917 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
918 Predicate<Alarm> isBackgroundRestricted) {
919
920 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
921 final int uid = pendingAlarms.keyAt(uidIndex);
922 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
923
924 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
925 final Alarm alarm = alarmsForUid.get(alarmIndex);
926
927 if (isBackgroundRestricted.test(alarm)) {
928 continue;
929 }
930
931 unrestrictedAlarms.add(alarm);
932 alarmsForUid.remove(alarmIndex);
933 }
934
935 if (alarmsForUid.size() == 0) {
936 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700937 }
938 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700939 }
940
941 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
942 final int N = alarms.size();
943 boolean hasWakeup = false;
944 for (int i = 0; i < N; i++) {
945 final Alarm alarm = alarms.get(i);
946 if (alarm.wakeup) {
947 hasWakeup = true;
948 }
949 alarm.count = 1;
950 // Recurring alarms may have passed several alarm intervals while the
951 // alarm was kept pending. Send the appropriate trigger count.
952 if (alarm.repeatInterval > 0) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800953 alarm.count += (nowELAPSED - alarm.requestedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700954 // Also schedule its next recurrence
955 final long delta = alarm.count * alarm.repeatInterval;
956 final long nextElapsed = alarm.whenElapsed + delta;
957 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
958 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
959 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
960 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
961 // Kernel alarms will be rescheduled as needed in setImplLocked
962 }
963 }
964 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
965 // No need to wakeup for non wakeup alarms
966 if (mPendingNonWakeupAlarms.size() == 0) {
967 mStartCurrentDelayTime = nowELAPSED;
968 mNextNonWakeupDeliveryTime = nowELAPSED
969 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
970 }
971 mPendingNonWakeupAlarms.addAll(alarms);
972 mNumDelayedAlarms += alarms.size();
973 } else {
974 if (DEBUG_BG_LIMIT) {
975 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
976 }
977 // Since we are waking up, also deliver any pending non wakeup alarms we have.
978 if (mPendingNonWakeupAlarms.size() > 0) {
979 alarms.addAll(mPendingNonWakeupAlarms);
980 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
981 mTotalDelayTime += thisDelayTime;
982 if (mMaxDelayTime < thisDelayTime) {
983 mMaxDelayTime = thisDelayTime;
984 }
985 mPendingNonWakeupAlarms.clear();
986 }
987 calculateDeliveryPriorities(alarms);
988 Collections.sort(alarms, mAlarmDispatchComparator);
989 deliverAlarmsLocked(alarms, nowELAPSED);
990 }
991 }
992
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700993 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700994 if (RECORD_DEVICE_IDLE_ALARMS) {
995 IdleDispatchEntry ent = new IdleDispatchEntry();
996 ent.uid = 0;
997 ent.pkg = "FINISH IDLE";
998 ent.elapsedRealtime = SystemClock.elapsedRealtime();
999 mAllowWhileIdleDispatches.add(ent);
1000 }
1001
Dianne Hackborn35d54032015-04-23 10:30:43 -07001002 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001003 if (mPendingWhileIdleAlarms.size() > 0) {
1004 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1005 mPendingWhileIdleAlarms = new ArrayList<>();
1006 final long nowElapsed = SystemClock.elapsedRealtime();
1007 for (int i=alarms.size() - 1; i >= 0; i--) {
1008 Alarm a = alarms.get(i);
1009 reAddAlarmLocked(a, nowElapsed, false);
1010 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001011 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001012
1013 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001014 rescheduleKernelAlarmsLocked();
1015 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001016
1017 // And send a TIME_TICK right now, since it is important to get the UI updated.
1018 try {
1019 mTimeTickSender.send();
1020 } catch (PendingIntent.CanceledException e) {
1021 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001022 }
1023
Christopher Tate14a7bb02015-10-01 10:24:31 -07001024 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001025 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001026 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001027 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001028 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001029 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001030 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001031 final BroadcastStats mBroadcastStats;
1032 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001033 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001034
Christopher Tate14a7bb02015-10-01 10:24:31 -07001035 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1036 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1037 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001038 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001039 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001040 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001041 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001042 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001043 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001044 mBroadcastStats = (pendingIntent != null)
1045 ? service.getStatsLocked(pendingIntent)
1046 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001047 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001048 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001049 fs = new FilterStats(mBroadcastStats, mTag);
1050 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001051 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001052 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001053 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001054 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001055 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001056
1057 @Override
1058 public String toString() {
1059 return "InFlight{"
1060 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001061 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001062 + ", workSource=" + mWorkSource
1063 + ", uid=" + mUid
1064 + ", tag=" + mTag
1065 + ", broadcastStats=" + mBroadcastStats
1066 + ", filterStats=" + mFilterStats
1067 + ", alarmType=" + mAlarmType
1068 + "}";
1069 }
Kweku Adams61e03292017-10-19 14:27:12 -07001070
1071 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1072 final long token = proto.start(fieldId);
1073
1074 proto.write(InFlightProto.UID, mUid);
1075 proto.write(InFlightProto.TAG, mTag);
1076 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1077 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1078 if (mPendingIntent != null) {
1079 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1080 }
1081 if (mBroadcastStats != null) {
1082 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1083 }
1084 if (mFilterStats != null) {
1085 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1086 }
1087 if (mWorkSource != null) {
1088 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1089 }
1090
1091 proto.end(token);
1092 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001093 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001094
Adam Lesinski182f73f2013-12-05 16:48:06 -08001095 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001096 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001097 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001098
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001099 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001101 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 int numWakeup;
1103 long startTime;
1104 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001105
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001106 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001107 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001108 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001109 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001110
1111 @Override
1112 public String toString() {
1113 return "FilterStats{"
1114 + "tag=" + mTag
1115 + ", lastTime=" + lastTime
1116 + ", aggregateTime=" + aggregateTime
1117 + ", count=" + count
1118 + ", numWakeup=" + numWakeup
1119 + ", startTime=" + startTime
1120 + ", nesting=" + nesting
1121 + "}";
1122 }
Kweku Adams61e03292017-10-19 14:27:12 -07001123
1124 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1125 final long token = proto.start(fieldId);
1126
1127 proto.write(FilterStatsProto.TAG, mTag);
1128 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1129 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1130 proto.write(FilterStatsProto.COUNT, count);
1131 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1132 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1133 proto.write(FilterStatsProto.NESTING, nesting);
1134
1135 proto.end(token);
1136 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001137 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001138
Adam Lesinski182f73f2013-12-05 16:48:06 -08001139 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001140 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001141 final String mPackageName;
1142
1143 long aggregateTime;
1144 int count;
1145 int numWakeup;
1146 long startTime;
1147 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001148 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001149
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001150 BroadcastStats(int uid, String packageName) {
1151 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001152 mPackageName = packageName;
1153 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001154
1155 @Override
1156 public String toString() {
1157 return "BroadcastStats{"
1158 + "uid=" + mUid
1159 + ", packageName=" + mPackageName
1160 + ", aggregateTime=" + aggregateTime
1161 + ", count=" + count
1162 + ", numWakeup=" + numWakeup
1163 + ", startTime=" + startTime
1164 + ", nesting=" + nesting
1165 + "}";
1166 }
Kweku Adams61e03292017-10-19 14:27:12 -07001167
1168 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1169 final long token = proto.start(fieldId);
1170
1171 proto.write(BroadcastStatsProto.UID, mUid);
1172 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1173 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1174 proto.write(BroadcastStatsProto.COUNT, count);
1175 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1176 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1177 proto.write(BroadcastStatsProto.NESTING, nesting);
1178
1179 proto.end(token);
1180 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001182
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001183 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1184 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001185
1186 int mNumDelayedAlarms = 0;
1187 long mTotalDelayTime = 0;
1188 long mMaxDelayTime = 0;
1189
Adam Lesinski182f73f2013-12-05 16:48:06 -08001190 @Override
1191 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001192 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001193 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001194
1195 // We have to set current TimeZone info to kernel
1196 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001197 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001198
Christopher Tate247571462017-04-10 11:45:05 -07001199 // Also sure that we're booting with a halfway sensible current time
1200 if (mNativeData != 0) {
1201 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1202 if (System.currentTimeMillis() < systemBuildTime) {
1203 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1204 + ", advancing to build time " + systemBuildTime);
1205 setKernelTime(mNativeData, systemBuildTime);
1206 }
1207 }
1208
Christopher Tatebb9cce52017-04-18 14:19:43 -07001209 // Determine SysUI's uid
1210 final PackageManager packMan = getContext().getPackageManager();
1211 try {
1212 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1213 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1214 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1215 mSystemUiUid = sysUi.uid;
1216 } else {
1217 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1218 + " defined by non-privileged app " + sysUi.packageName
1219 + " - ignoring");
1220 }
1221 } catch (NameNotFoundException e) {
1222 }
1223
1224 if (mSystemUiUid <= 0) {
1225 Slog.wtf(TAG, "SysUI package not found!");
1226 }
1227
Adam Lesinski182f73f2013-12-05 16:48:06 -08001228 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001229 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001230
Adam Lesinski182f73f2013-12-05 16:48:06 -08001231 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001233 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001234 | Intent.FLAG_RECEIVER_FOREGROUND
1235 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001236 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001237 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001238 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1239 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001240 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001241 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001242
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001244 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001245 mClockReceiver.scheduleTimeTickEvent();
1246 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001247 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001248 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001249
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001250 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001251 AlarmThread waitThread = new AlarmThread();
1252 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001253 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001254 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001256
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001257 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001258 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001259 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1260 | ActivityManager.UID_OBSERVER_ACTIVE,
1261 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001262 } catch (RemoteException e) {
1263 // ignored; both services live in system_server
1264 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001265 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001267
1268 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001269 public void onBootPhase(int phase) {
1270 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla4deb8522018-01-08 16:27:10 -08001271 mForceAppStandbyTracker.start();
Dianne Hackborna750a632015-06-16 17:18:23 -07001272 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001273 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001274 mLocalDeviceIdleController
1275 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001276 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1277 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Dianne Hackborna750a632015-06-16 17:18:23 -07001278 }
1279 }
1280
1281 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 protected void finalize() throws Throwable {
1283 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001284 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001285 } finally {
1286 super.finalize();
1287 }
1288 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001289
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 void setTimeZoneImpl(String tz) {
1291 if (TextUtils.isEmpty(tz)) {
1292 return;
David Christieebe51fc2013-07-26 13:23:29 -07001293 }
1294
Adam Lesinski182f73f2013-12-05 16:48:06 -08001295 TimeZone zone = TimeZone.getTimeZone(tz);
1296 // Prevent reentrant calls from stepping on each other when writing
1297 // the time zone property
1298 boolean timeZoneWasChanged = false;
1299 synchronized (this) {
1300 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1301 if (current == null || !current.equals(zone.getID())) {
1302 if (localLOGV) {
1303 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1304 }
1305 timeZoneWasChanged = true;
1306 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1307 }
1308
1309 // Update the kernel timezone information
1310 // Kernel tracks time offsets as 'minutes west of GMT'
1311 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001312 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001313 }
1314
1315 TimeZone.setDefault(null);
1316
1317 if (timeZoneWasChanged) {
1318 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001319 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001320 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001321 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001322 intent.putExtra("time-zone", zone.getID());
1323 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1324 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001326
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327 void removeImpl(PendingIntent operation) {
1328 if (operation == null) {
1329 return;
1330 }
1331 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001332 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001333 }
1334 }
1335
1336 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001337 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1338 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1339 int callingUid, String callingPackage) {
1340 // must be *either* PendingIntent or AlarmReceiver, but not both
1341 if ((operation == null && directReceiver == null)
1342 || (operation != null && directReceiver != null)) {
1343 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1344 // NB: previous releases failed silently here, so we are continuing to do the same
1345 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 return;
1347 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001348
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001349 // Sanity check the window length. This will catch people mistakenly
1350 // trying to pass an end-of-window timestamp rather than a duration.
1351 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1352 Slog.w(TAG, "Window length " + windowLength
1353 + "ms suspiciously long; limiting to 1 hour");
1354 windowLength = AlarmManager.INTERVAL_HOUR;
1355 }
1356
Christopher Tate498c6cb2014-11-17 16:09:27 -08001357 // Sanity check the recurrence interval. This will catch people who supply
1358 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001359 final long minInterval = mConstants.MIN_INTERVAL;
1360 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001361 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001362 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001363 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001364 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001365 }
1366
Christopher Tatee0a22b32013-07-11 14:43:13 -07001367 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1368 throw new IllegalArgumentException("Invalid alarm type " + type);
1369 }
1370
Christopher Tate5f221e82013-07-30 17:13:15 -07001371 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001372 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001373 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001374 + " pid=" + what);
1375 triggerAtTime = 0;
1376 }
1377
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001378 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001379 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1380 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001381 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001382 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1383
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001384 final long maxElapsed;
1385 if (windowLength == AlarmManager.WINDOW_EXACT) {
1386 maxElapsed = triggerElapsed;
1387 } else if (windowLength < 0) {
1388 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001389 // Fix this window in place, so that as time approaches we don't collapse it.
1390 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001391 } else {
1392 maxElapsed = triggerElapsed + windowLength;
1393 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001394
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001396 if (DEBUG_BATCH) {
1397 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001398 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001399 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001400 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001402 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001403 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1404 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 }
1406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407
Christopher Tate3e04b472013-10-21 17:51:31 -07001408 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001409 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1410 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1411 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001412 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001413 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1414 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001415 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001416 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001417 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1418 + " -- package not allowed to start");
1419 return;
1420 }
1421 } catch (RemoteException e) {
1422 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001423 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001424 setImplLocked(a, false, doValidate);
1425 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001426
Suprabh Shukla75edab12018-01-29 14:09:06 -08001427 private long getMinDelayForBucketLocked(int bucket) {
1428 // Return the minimum time that should elapse before an app in the specified bucket
1429 // can receive alarms again
1430 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
1431 return mConstants.APP_STANDBY_MIN_DELAYS[4];
1432 }
1433 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) {
1434 return mConstants.APP_STANDBY_MIN_DELAYS[3];
1435 }
1436 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1437 return mConstants.APP_STANDBY_MIN_DELAYS[2];
1438 }
1439 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1440 return mConstants.APP_STANDBY_MIN_DELAYS[1];
1441 }
1442 else return mConstants.APP_STANDBY_MIN_DELAYS[0];
1443 }
1444
1445 private void adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
1446 if (alarm.alarmClock != null || UserHandle.isCore(alarm.creatorUid)) {
1447 return;
1448 }
1449 if (mAppStandbyParole) {
1450 if (alarm.whenElapsed > alarm.requestedWhenElapsed) {
1451 // We did throttle this alarm earlier, restore original requirements
1452 alarm.whenElapsed = alarm.requestedWhenElapsed;
1453 alarm.maxWhenElapsed = alarm.requestedMaxWhenElapsed;
1454 }
1455 return;
1456 }
1457 final String sourcePackage = alarm.sourcePackage;
1458 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1459 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1460 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1461
1462 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1463 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1464 if (lastElapsed > 0) {
1465 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
1466 if (alarm.requestedWhenElapsed < minElapsed) {
1467 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
1468 }
1469 }
1470 }
1471
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001472 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1473 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001474 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001475 // The caller has given the time they want this to happen at, however we need
1476 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001477 // bring us out of idle at an earlier time.
1478 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001479 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001480 }
1481 // Add fuzz to make the alarm go off some time before the actual desired time.
1482 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001483 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001484 if (fuzz > 0) {
1485 if (mRandom == null) {
1486 mRandom = new Random();
1487 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001488 final int delta = mRandom.nextInt(fuzz);
1489 a.whenElapsed -= delta;
1490 if (false) {
1491 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1492 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1493 Slog.d(TAG, "Applied fuzz: " + fuzz);
1494 Slog.d(TAG, "Final delta: " + delta);
1495 Slog.d(TAG, "Final when: " + a.whenElapsed);
1496 }
1497 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001498 }
1499
1500 } else if (mPendingIdleUntil != null) {
1501 // We currently have an idle until alarm scheduled; if the new alarm has
1502 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001503 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1504 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1505 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001506 == 0) {
1507 mPendingWhileIdleAlarms.add(a);
1508 return;
1509 }
1510 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001511 if (RECORD_DEVICE_IDLE_ALARMS) {
1512 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1513 IdleDispatchEntry ent = new IdleDispatchEntry();
1514 ent.uid = a.uid;
1515 ent.pkg = a.operation.getCreatorPackage();
1516 ent.tag = a.operation.getTag("");
1517 ent.op = "SET";
1518 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1519 ent.argRealtime = a.whenElapsed;
1520 mAllowWhileIdleDispatches.add(ent);
1521 }
1522 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001523 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001524
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001525 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1526 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001527 if (whichBatch < 0) {
1528 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001529 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001531 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001532 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001533 // The start time of this batch advanced, so batch ordering may
1534 // have just been broken. Move it to where it now belongs.
1535 mAlarmBatches.remove(whichBatch);
1536 addBatchLocked(mAlarmBatches, batch);
1537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
1539
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001540 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001541 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001542 }
1543
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001544 boolean needRebatch = false;
1545
1546 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001547 if (RECORD_DEVICE_IDLE_ALARMS) {
1548 if (mPendingIdleUntil == null) {
1549 IdleDispatchEntry ent = new IdleDispatchEntry();
1550 ent.uid = 0;
1551 ent.pkg = "START IDLE";
1552 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1553 mAllowWhileIdleDispatches.add(ent);
1554 }
1555 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001556 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1557 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1558 + " to " + a);
1559 }
1560
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001561 mPendingIdleUntil = a;
1562 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001563 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1564 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1565 mNextWakeFromIdle = a;
1566 // If this wake from idle is earlier than whatever was previously scheduled,
1567 // and we are currently idling, then we need to rebatch alarms in case the idle
1568 // until time needs to be updated.
1569 if (mPendingIdleUntil != null) {
1570 needRebatch = true;
1571 }
1572 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001573 }
1574
1575 if (!rebatching) {
1576 if (DEBUG_VALIDATE) {
1577 if (doValidate && !validateConsistencyLocked()) {
1578 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1579 + " when(hex)=" + Long.toHexString(a.when)
1580 + " whenElapsed=" + a.whenElapsed
1581 + " maxWhenElapsed=" + a.maxWhenElapsed
1582 + " interval=" + a.repeatInterval + " op=" + a.operation
1583 + " flags=0x" + Integer.toHexString(a.flags));
1584 rebatchAllAlarmsLocked(false);
1585 needRebatch = false;
1586 }
1587 }
1588
1589 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001590 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001591 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001592
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001593 rescheduleKernelAlarmsLocked();
1594 updateNextAlarmClockLocked();
1595 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001596 }
1597
Christopher Tate1d99c392017-12-07 16:54:04 -08001598 /**
1599 * System-process internal API
1600 */
1601 private final class LocalService implements AlarmManagerInternal {
1602 @Override
1603 public void removeAlarmsForUid(int uid) {
1604 synchronized (mLock) {
1605 removeLocked(uid);
1606 }
1607 }
1608 }
1609
1610 /**
1611 * Public-facing binder interface
1612 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001613 private final IBinder mService = new IAlarmManager.Stub() {
1614 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001615 public void set(String callingPackage,
1616 int type, long triggerAtTime, long windowLength, long interval, int flags,
1617 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1618 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001619 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001620
1621 // make sure the caller is not lying about which package should be blamed for
1622 // wakelock time spent in alarm delivery
1623 mAppOps.checkPackage(callingUid, callingPackage);
1624
1625 // Repeating alarms must use PendingIntent, not direct listener
1626 if (interval != 0) {
1627 if (directReceiver != null) {
1628 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1629 }
1630 }
1631
Adam Lesinski182f73f2013-12-05 16:48:06 -08001632 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001633 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001634 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001635 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001636 }
1637
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001638 // No incoming callers can request either WAKE_FROM_IDLE or
1639 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1640 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1641 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1642
1643 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1644 // manager when to come out of idle mode, which is only for DeviceIdleController.
1645 if (callingUid != Process.SYSTEM_UID) {
1646 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1647 }
1648
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001649 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001650 if (windowLength == AlarmManager.WINDOW_EXACT) {
1651 flags |= AlarmManager.FLAG_STANDALONE;
1652 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001653
1654 // If this alarm is for an alarm clock, then it must be standalone and we will
1655 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001656 if (alarmClock != null) {
1657 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001658
1659 // If the caller is a core system component or on the user's whitelist, and not calling
1660 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1661 // This means we will allow these alarms to go off as normal even while idle, with no
1662 // timing restrictions.
1663 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001664 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001665 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001666 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1667 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001668 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001669
Christopher Tate14a7bb02015-10-01 10:24:31 -07001670 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1671 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001672 }
Christopher Tate89779822012-08-31 14:40:03 -07001673
Adam Lesinski182f73f2013-12-05 16:48:06 -08001674 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001675 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001676 getContext().enforceCallingOrSelfPermission(
1677 "android.permission.SET_TIME",
1678 "setTime");
1679
Greg Hackmann0cab8962014-02-21 16:35:52 -08001680 if (mNativeData == 0) {
1681 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1682 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001683 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001684
1685 synchronized (mLock) {
1686 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001689
1690 @Override
1691 public void setTimeZone(String tz) {
1692 getContext().enforceCallingOrSelfPermission(
1693 "android.permission.SET_TIME_ZONE",
1694 "setTimeZone");
1695
1696 final long oldId = Binder.clearCallingIdentity();
1697 try {
1698 setTimeZoneImpl(tz);
1699 } finally {
1700 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
1702 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001703
Adam Lesinski182f73f2013-12-05 16:48:06 -08001704 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001705 public void remove(PendingIntent operation, IAlarmListener listener) {
1706 if (operation == null && listener == null) {
1707 Slog.w(TAG, "remove() with no intent or listener");
1708 return;
1709 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001710
Christopher Tate14a7bb02015-10-01 10:24:31 -07001711 synchronized (mLock) {
1712 removeLocked(operation, listener);
1713 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001715
Adam Lesinski182f73f2013-12-05 16:48:06 -08001716 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001717 public long getNextWakeFromIdleTime() {
1718 return getNextWakeFromIdleTimeImpl();
1719 }
1720
1721 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001722 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001723 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1724 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1725 "getNextAlarmClock", null);
1726
1727 return getNextAlarmClockImpl(userId);
1728 }
1729
1730 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001731 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001732 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001733
1734 if (args.length > 0 && "--proto".equals(args[0])) {
1735 dumpProto(fd);
1736 } else {
1737 dumpImpl(pw);
1738 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001739 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001740 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001741
Adam Lesinski182f73f2013-12-05 16:48:06 -08001742 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 synchronized (mLock) {
1744 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001745 mConstants.dump(pw);
1746 pw.println();
1747
Makoto Onuki2206af32017-11-21 16:25:35 -08001748 mForceAppStandbyTracker.dump(pw, " ");
Christopher Tate12cf0b62018-01-05 18:40:14 -08001749 pw.println();
Makoto Onuki2206af32017-11-21 16:25:35 -08001750
Suprabh Shukla75edab12018-01-29 14:09:06 -08001751 pw.println(" App Standby Parole: " + mAppStandbyParole);
1752 pw.println();
1753
Christopher Tatee0a22b32013-07-11 14:43:13 -07001754 final long nowRTC = System.currentTimeMillis();
1755 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001756 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001757
Dianne Hackborna750a632015-06-16 17:18:23 -07001758 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001759 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001760 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001761 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001762 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001763 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001764 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1765 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001766 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001767 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1768 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001769 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1770 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001771 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001772 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001773 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001774 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1775 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001776 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001777 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1778 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001779 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001780 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1781 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001782 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001783 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1784 pw.println();
1785 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001786
1787 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1788 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001789 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001790 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001791 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001792 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001793 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001794 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1795 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1796 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001797 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001798
John Spurlock604a5ee2015-06-01 12:27:22 -04001799 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001800 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001801 final TreeSet<Integer> users = new TreeSet<>();
1802 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1803 users.add(mNextAlarmClockForUser.keyAt(i));
1804 }
1805 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1806 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1807 }
1808 for (int user : users) {
1809 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1810 final long time = next != null ? next.getTriggerTime() : 0;
1811 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001812 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001813 pw.print(" pendingSend:"); pw.print(pendingSend);
1814 pw.print(" time:"); pw.print(time);
1815 if (time > 0) {
1816 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1817 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1818 }
1819 pw.println();
1820 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001821 if (mAlarmBatches.size() > 0) {
1822 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001823 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001824 pw.println(mAlarmBatches.size());
1825 for (Batch b : mAlarmBatches) {
1826 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001827 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001830 pw.println();
1831 pw.println(" Pending user blocked background alarms: ");
1832 boolean blocked = false;
1833 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1834 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1835 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1836 blocked = true;
1837 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1838 }
1839 }
1840 if (!blocked) {
1841 pw.println(" none");
1842 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001843
Suprabh Shukla75edab12018-01-29 14:09:06 -08001844 pw.println(" mLastAlarmDeliveredForPackage:");
1845 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1846 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1847 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1848 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1849 pw.println();
1850 }
1851 pw.println();
1852
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001853 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001854 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001855 pw.println(" Idle mode state:");
1856 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001857 if (mPendingIdleUntil != null) {
1858 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001859 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001860 } else {
1861 pw.println("null");
1862 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001863 pw.println(" Pending alarms:");
1864 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001865 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001866 if (mNextWakeFromIdle != null) {
1867 pw.println();
1868 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001869 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001870 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001871
1872 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001873 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001874 if (mPendingNonWakeupAlarms.size() > 0) {
1875 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001876 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001877 } else {
1878 pw.println("(none)");
1879 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001880 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001881 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1882 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001883 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001884 pw.print(", max non-interactive time: ");
1885 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1886 pw.println();
1887
1888 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001889 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001890 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1891 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1892 pw.print(" Listener send count: "); pw.println(mListenerCount);
1893 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001894 pw.println();
1895
Christopher Tate7f2a0352015-12-08 10:24:33 -08001896 if (mInFlight.size() > 0) {
1897 pw.println("Outstanding deliveries:");
1898 for (int i = 0; i < mInFlight.size(); i++) {
1899 pw.print(" #"); pw.print(i); pw.print(": ");
1900 pw.println(mInFlight.get(i));
1901 }
1902 pw.println();
1903 }
1904
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001905 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001906 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001907 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08001908 pw.print(" UID ");
1909 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
1910 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001911 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08001912 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
1913 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
1914
1915 final long minInterval = getWhileIdleMinIntervalLocked(uid);
1916 pw.print(" Next allowed:");
1917 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
1918 pw.print(" (");
1919 TimeUtils.formatDuration(minInterval, 0, pw);
1920 pw.print(")");
1921
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001922 pw.println();
1923 }
1924 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08001925
1926 pw.print(" mUseAllowWhileIdleShortTime: [");
1927 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
1928 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
1929 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
1930 pw.print(" ");
1931 }
1932 }
1933 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001934 pw.println();
1935
Dianne Hackborn81038902012-11-26 17:04:09 -08001936 if (mLog.dump(pw, " Recent problems", " ")) {
1937 pw.println();
1938 }
1939
1940 final FilterStats[] topFilters = new FilterStats[10];
1941 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1942 @Override
1943 public int compare(FilterStats lhs, FilterStats rhs) {
1944 if (lhs.aggregateTime < rhs.aggregateTime) {
1945 return 1;
1946 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1947 return -1;
1948 }
1949 return 0;
1950 }
1951 };
1952 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001953 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001954 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1955 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1956 for (int ip=0; ip<uidStats.size(); ip++) {
1957 BroadcastStats bs = uidStats.valueAt(ip);
1958 for (int is=0; is<bs.filterStats.size(); is++) {
1959 FilterStats fs = bs.filterStats.valueAt(is);
1960 int pos = len > 0
1961 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1962 if (pos < 0) {
1963 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001964 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001965 if (pos < topFilters.length) {
1966 int copylen = topFilters.length - pos - 1;
1967 if (copylen > 0) {
1968 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1969 }
1970 topFilters[pos] = fs;
1971 if (len < topFilters.length) {
1972 len++;
1973 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001974 }
1975 }
1976 }
1977 }
1978 if (len > 0) {
1979 pw.println(" Top Alarms:");
1980 for (int i=0; i<len; i++) {
1981 FilterStats fs = topFilters[i];
1982 pw.print(" ");
1983 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1984 TimeUtils.formatDuration(fs.aggregateTime, pw);
1985 pw.print(" running, "); pw.print(fs.numWakeup);
1986 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001987 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1988 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001989 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001990 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001991 pw.println();
1992 }
1993 }
1994
1995 pw.println(" ");
1996 pw.println(" Alarm Stats:");
1997 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001998 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1999 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2000 for (int ip=0; ip<uidStats.size(); ip++) {
2001 BroadcastStats bs = uidStats.valueAt(ip);
2002 pw.print(" ");
2003 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2004 UserHandle.formatUid(pw, bs.mUid);
2005 pw.print(":");
2006 pw.print(bs.mPackageName);
2007 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2008 pw.print(" running, "); pw.print(bs.numWakeup);
2009 pw.println(" wakeups:");
2010 tmpFilters.clear();
2011 for (int is=0; is<bs.filterStats.size(); is++) {
2012 tmpFilters.add(bs.filterStats.valueAt(is));
2013 }
2014 Collections.sort(tmpFilters, comparator);
2015 for (int i=0; i<tmpFilters.size(); i++) {
2016 FilterStats fs = tmpFilters.get(i);
2017 pw.print(" ");
2018 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2019 TimeUtils.formatDuration(fs.aggregateTime, pw);
2020 pw.print(" "); pw.print(fs.numWakeup);
2021 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002022 pw.print(" alarms, last ");
2023 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2024 pw.println(":");
2025 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002026 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002027 pw.println();
2028 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002029 }
2030 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002031 pw.println();
2032 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002033
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002034 if (RECORD_DEVICE_IDLE_ALARMS) {
2035 pw.println();
2036 pw.println(" Allow while idle dispatches:");
2037 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2038 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2039 pw.print(" ");
2040 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2041 pw.print(": ");
2042 UserHandle.formatUid(pw, ent.uid);
2043 pw.print(":");
2044 pw.println(ent.pkg);
2045 if (ent.op != null) {
2046 pw.print(" ");
2047 pw.print(ent.op);
2048 pw.print(" / ");
2049 pw.print(ent.tag);
2050 if (ent.argRealtime != 0) {
2051 pw.print(" (");
2052 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2053 pw.print(")");
2054 }
2055 pw.println();
2056 }
2057 }
2058 }
2059
Christopher Tate18a75f12013-07-01 18:18:59 -07002060 if (WAKEUP_STATS) {
2061 pw.println();
2062 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002063 long last = -1;
2064 for (WakeupEvent event : mRecentWakeups) {
2065 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2066 pw.print('|');
2067 if (last < 0) {
2068 pw.print('0');
2069 } else {
2070 pw.print(event.when - last);
2071 }
2072 last = event.when;
2073 pw.print('|'); pw.print(event.uid);
2074 pw.print('|'); pw.print(event.action);
2075 pw.println();
2076 }
2077 pw.println();
2078 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002079 }
2080 }
2081
Kweku Adams61e03292017-10-19 14:27:12 -07002082 void dumpProto(FileDescriptor fd) {
2083 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2084
2085 synchronized (mLock) {
2086 final long nowRTC = System.currentTimeMillis();
2087 final long nowElapsed = SystemClock.elapsedRealtime();
2088 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
2089 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
2090 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
2091 mLastTimeChangeClockTime);
2092 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2093 mLastTimeChangeRealtime);
2094
2095 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2096
Makoto Onuki2206af32017-11-21 16:25:35 -08002097 mForceAppStandbyTracker.dumpProto(proto,
2098 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07002099
2100 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2101 if (!mInteractive) {
2102 // Durations
2103 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2104 nowElapsed - mNonInteractiveStartTime);
2105 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2106 currentNonWakeupFuzzLocked(nowElapsed));
2107 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2108 nowElapsed - mLastAlarmDeliveryTime);
2109 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2110 nowElapsed - mNextNonWakeupDeliveryTime);
2111 }
2112
2113 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2114 mNextNonWakeup - nowElapsed);
2115 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2116 mNextWakeup - nowElapsed);
2117 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2118 nowElapsed - mLastWakeup);
2119 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2120 nowElapsed - mLastWakeupSet);
2121 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002122
2123 final TreeSet<Integer> users = new TreeSet<>();
2124 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2125 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2126 users.add(mNextAlarmClockForUser.keyAt(i));
2127 }
2128 final int pendingSendNextAlarmClockChangedForUserSize =
2129 mPendingSendNextAlarmClockChangedForUser.size();
2130 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2131 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2132 }
2133 for (int user : users) {
2134 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2135 final long time = next != null ? next.getTriggerTime() : 0;
2136 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2137 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2138 proto.write(AlarmClockMetadataProto.USER, user);
2139 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2140 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2141 proto.end(aToken);
2142 }
2143 for (Batch b : mAlarmBatches) {
2144 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2145 nowElapsed, nowRTC);
2146 }
2147 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2148 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2149 if (blockedAlarms != null) {
2150 for (Alarm a : blockedAlarms) {
2151 a.writeToProto(proto,
2152 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2153 nowElapsed, nowRTC);
2154 }
2155 }
2156 }
2157 if (mPendingIdleUntil != null) {
2158 mPendingIdleUntil.writeToProto(
2159 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2160 }
2161 for (Alarm a : mPendingWhileIdleAlarms) {
2162 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2163 nowElapsed, nowRTC);
2164 }
2165 if (mNextWakeFromIdle != null) {
2166 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2167 nowElapsed, nowRTC);
2168 }
2169
2170 for (Alarm a : mPendingNonWakeupAlarms) {
2171 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2172 nowElapsed, nowRTC);
2173 }
2174
2175 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2176 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2177 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2178 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2179 mNonInteractiveTime);
2180
2181 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2182 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2183 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2184 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2185 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2186
2187 for (InFlight f : mInFlight) {
2188 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2189 }
2190
Kweku Adams61e03292017-10-19 14:27:12 -07002191 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2192 final long token = proto.start(
2193 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002194 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2195 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2196
2197 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID, uid);
2198 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2199 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
2200 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002201 proto.end(token);
2202 }
2203
Makoto Onukiadb50d82018-01-29 16:20:30 -08002204 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2205 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2206 proto.write(AlarmManagerServiceProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
2207 mUseAllowWhileIdleShortTime.keyAt(i));
2208 }
2209 }
2210
Kweku Adams61e03292017-10-19 14:27:12 -07002211 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2212
2213 final FilterStats[] topFilters = new FilterStats[10];
2214 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2215 @Override
2216 public int compare(FilterStats lhs, FilterStats rhs) {
2217 if (lhs.aggregateTime < rhs.aggregateTime) {
2218 return 1;
2219 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2220 return -1;
2221 }
2222 return 0;
2223 }
2224 };
2225 int len = 0;
2226 // Get the top 10 FilterStats, ordered by aggregateTime.
2227 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2228 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2229 for (int ip = 0; ip < uidStats.size(); ++ip) {
2230 BroadcastStats bs = uidStats.valueAt(ip);
2231 for (int is = 0; is < bs.filterStats.size(); ++is) {
2232 FilterStats fs = bs.filterStats.valueAt(is);
2233 int pos = len > 0
2234 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2235 if (pos < 0) {
2236 pos = -pos - 1;
2237 }
2238 if (pos < topFilters.length) {
2239 int copylen = topFilters.length - pos - 1;
2240 if (copylen > 0) {
2241 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2242 }
2243 topFilters[pos] = fs;
2244 if (len < topFilters.length) {
2245 len++;
2246 }
2247 }
2248 }
2249 }
2250 }
2251 for (int i = 0; i < len; ++i) {
2252 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2253 FilterStats fs = topFilters[i];
2254
2255 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2256 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2257 fs.mBroadcastStats.mPackageName);
2258 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2259
2260 proto.end(token);
2261 }
2262
2263 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2264 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2265 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2266 for (int ip = 0; ip < uidStats.size(); ++ip) {
2267 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2268
2269 BroadcastStats bs = uidStats.valueAt(ip);
2270 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2271
2272 // uidStats is an ArrayMap, which we can't sort.
2273 tmpFilters.clear();
2274 for (int is = 0; is < bs.filterStats.size(); ++is) {
2275 tmpFilters.add(bs.filterStats.valueAt(is));
2276 }
2277 Collections.sort(tmpFilters, comparator);
2278 for (FilterStats fs : tmpFilters) {
2279 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2280 }
2281
2282 proto.end(token);
2283 }
2284 }
2285
2286 if (RECORD_DEVICE_IDLE_ALARMS) {
2287 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2288 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2289 final long token = proto.start(
2290 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2291
2292 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2293 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2294 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2295 proto.write(IdleDispatchEntryProto.OP, ent.op);
2296 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2297 ent.elapsedRealtime);
2298 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2299
2300 proto.end(token);
2301 }
2302 }
2303
2304 if (WAKEUP_STATS) {
2305 for (WakeupEvent event : mRecentWakeups) {
2306 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2307 proto.write(WakeupEventProto.UID, event.uid);
2308 proto.write(WakeupEventProto.ACTION, event.action);
2309 proto.write(WakeupEventProto.WHEN, event.when);
2310 proto.end(token);
2311 }
2312 }
2313 }
2314
2315 proto.flush();
2316 }
2317
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002318 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002319 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2320 PrintWriter pw = new PrintWriter(bs);
2321 final long nowRTC = System.currentTimeMillis();
2322 final long nowELAPSED = SystemClock.elapsedRealtime();
2323 final int NZ = mAlarmBatches.size();
2324 for (int iz = 0; iz < NZ; iz++) {
2325 Batch bz = mAlarmBatches.get(iz);
2326 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002327 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002328 pw.flush();
2329 Slog.v(TAG, bs.toString());
2330 bs.reset();
2331 }
2332 }
2333
2334 private boolean validateConsistencyLocked() {
2335 if (DEBUG_VALIDATE) {
2336 long lastTime = Long.MIN_VALUE;
2337 final int N = mAlarmBatches.size();
2338 for (int i = 0; i < N; i++) {
2339 Batch b = mAlarmBatches.get(i);
2340 if (b.start >= lastTime) {
2341 // duplicate start times are okay because of standalone batches
2342 lastTime = b.start;
2343 } else {
2344 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002345 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2346 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002347 return false;
2348 }
2349 }
2350 }
2351 return true;
2352 }
2353
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002354 private Batch findFirstWakeupBatchLocked() {
2355 final int N = mAlarmBatches.size();
2356 for (int i = 0; i < N; i++) {
2357 Batch b = mAlarmBatches.get(i);
2358 if (b.hasWakeups()) {
2359 return b;
2360 }
2361 }
2362 return null;
2363 }
2364
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002365 long getNextWakeFromIdleTimeImpl() {
2366 synchronized (mLock) {
2367 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2368 }
2369 }
2370
2371 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002372 synchronized (mLock) {
2373 return mNextAlarmClockForUser.get(userId);
2374 }
2375 }
2376
2377 /**
2378 * Recomputes the next alarm clock for all users.
2379 */
2380 private void updateNextAlarmClockLocked() {
2381 if (!mNextAlarmClockMayChange) {
2382 return;
2383 }
2384 mNextAlarmClockMayChange = false;
2385
Jose Lima235510e2014-08-13 12:50:01 -07002386 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002387 nextForUser.clear();
2388
2389 final int N = mAlarmBatches.size();
2390 for (int i = 0; i < N; i++) {
2391 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2392 final int M = alarms.size();
2393
2394 for (int j = 0; j < M; j++) {
2395 Alarm a = alarms.get(j);
2396 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002397 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002398 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002399
2400 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002401 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002402 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002403 " for user " + userId);
2404 }
2405
2406 // Alarms and batches are sorted by time, no need to compare times here.
2407 if (nextForUser.get(userId) == null) {
2408 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002409 } else if (a.alarmClock.equals(current)
2410 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2411 // same/earlier time and it's the one we cited before, so stick with it
2412 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002413 }
2414 }
2415 }
2416 }
2417
2418 // Update mNextAlarmForUser with new values.
2419 final int NN = nextForUser.size();
2420 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002421 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002422 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002423 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002424 if (!newAlarm.equals(currentAlarm)) {
2425 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2426 }
2427 }
2428
2429 // Remove users without any alarm clocks scheduled.
2430 final int NNN = mNextAlarmClockForUser.size();
2431 for (int i = NNN - 1; i >= 0; i--) {
2432 int userId = mNextAlarmClockForUser.keyAt(i);
2433 if (nextForUser.get(userId) == null) {
2434 updateNextAlarmInfoForUserLocked(userId, null);
2435 }
2436 }
2437 }
2438
Jose Lima235510e2014-08-13 12:50:01 -07002439 private void updateNextAlarmInfoForUserLocked(int userId,
2440 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002441 if (alarmClock != null) {
2442 if (DEBUG_ALARM_CLOCK) {
2443 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002444 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002445 }
2446 mNextAlarmClockForUser.put(userId, alarmClock);
2447 } else {
2448 if (DEBUG_ALARM_CLOCK) {
2449 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2450 }
2451 mNextAlarmClockForUser.remove(userId);
2452 }
2453
2454 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2455 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2456 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2457 }
2458
2459 /**
2460 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2461 * for which alarm clocks have changed since the last call to this.
2462 *
2463 * Do not call with a lock held. Only call from mHandler's thread.
2464 *
2465 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2466 */
2467 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002468 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002469 pendingUsers.clear();
2470
2471 synchronized (mLock) {
2472 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2473 for (int i = 0; i < N; i++) {
2474 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2475 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2476 }
2477 mPendingSendNextAlarmClockChangedForUser.clear();
2478 }
2479
2480 final int N = pendingUsers.size();
2481 for (int i = 0; i < N; i++) {
2482 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002483 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002484 Settings.System.putStringForUser(getContext().getContentResolver(),
2485 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002486 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002487 userId);
2488
2489 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2490 new UserHandle(userId));
2491 }
2492 }
2493
2494 /**
2495 * Formats an alarm like platform/packages/apps/DeskClock used to.
2496 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002497 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2498 int userId) {
2499 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002500 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2501 return (info == null) ? "" :
2502 DateFormat.format(pattern, info.getTriggerTime()).toString();
2503 }
2504
Adam Lesinski182f73f2013-12-05 16:48:06 -08002505 void rescheduleKernelAlarmsLocked() {
2506 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2507 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002508 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002509 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002510 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002511 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002512 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002513 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002514 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002515 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002516 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002517 if (firstBatch != firstWakeup) {
2518 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002519 }
2520 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002521 if (mPendingNonWakeupAlarms.size() > 0) {
2522 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2523 nextNonWakeup = mNextNonWakeupDeliveryTime;
2524 }
2525 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002526 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002527 mNextNonWakeup = nextNonWakeup;
2528 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2529 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002530 }
2531
Christopher Tate14a7bb02015-10-01 10:24:31 -07002532 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002533 if (operation == null && directReceiver == null) {
2534 if (localLOGV) {
2535 Slog.w(TAG, "requested remove() of null operation",
2536 new RuntimeException("here"));
2537 }
2538 return;
2539 }
2540
Adam Lesinski182f73f2013-12-05 16:48:06 -08002541 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002542 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002543 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2544 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002545 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002546 if (b.size() == 0) {
2547 mAlarmBatches.remove(i);
2548 }
2549 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002550 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002551 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002552 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2553 mPendingWhileIdleAlarms.remove(i);
2554 }
2555 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002556 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2557 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2558 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2559 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2560 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2561 alarmsForUid.remove(j);
2562 }
2563 }
2564 if (alarmsForUid.size() == 0) {
2565 mPendingBackgroundAlarms.removeAt(i);
2566 }
2567 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002568 if (didRemove) {
2569 if (DEBUG_BATCH) {
2570 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2571 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002572 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002573 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002574 mPendingIdleUntil = null;
2575 restorePending = true;
2576 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002577 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002578 mNextWakeFromIdle = null;
2579 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002580 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002581 if (restorePending) {
2582 restorePendingWhileIdleAlarmsLocked();
2583 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002584 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002585 }
2586 }
2587
Christopher Tate1d99c392017-12-07 16:54:04 -08002588 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002589 if (uid == Process.SYSTEM_UID) {
2590 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2591 return;
2592 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002593 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002594 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002595 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2596 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002597 didRemove |= b.remove(whichAlarms);
2598 if (b.size() == 0) {
2599 mAlarmBatches.remove(i);
2600 }
2601 }
2602 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2603 final Alarm a = mPendingWhileIdleAlarms.get(i);
2604 if (a.uid == uid) {
2605 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2606 mPendingWhileIdleAlarms.remove(i);
2607 }
2608 }
2609 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2610 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2611 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2612 if (alarmsForUid.get(j).uid == uid) {
2613 alarmsForUid.remove(j);
2614 }
2615 }
2616 if (alarmsForUid.size() == 0) {
2617 mPendingBackgroundAlarms.removeAt(i);
2618 }
2619 }
2620 if (didRemove) {
2621 if (DEBUG_BATCH) {
2622 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2623 }
2624 rebatchAllAlarmsLocked(true);
2625 rescheduleKernelAlarmsLocked();
2626 updateNextAlarmClockLocked();
2627 }
2628 }
2629
2630 void removeLocked(final String packageName) {
2631 if (packageName == null) {
2632 if (localLOGV) {
2633 Slog.w(TAG, "requested remove() of null packageName",
2634 new RuntimeException("here"));
2635 }
2636 return;
2637 }
2638
2639 boolean didRemove = false;
2640 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002641 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002642 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2643 Batch b = mAlarmBatches.get(i);
2644 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002645 if (b.size() == 0) {
2646 mAlarmBatches.remove(i);
2647 }
2648 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002649 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2650 if (oldHasTick != newHasTick) {
2651 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2652 }
2653
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002654 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002655 final Alarm a = mPendingWhileIdleAlarms.get(i);
2656 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002657 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2658 mPendingWhileIdleAlarms.remove(i);
2659 }
2660 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002661 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2662 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2663 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2664 if (alarmsForUid.get(j).matches(packageName)) {
2665 alarmsForUid.remove(j);
2666 }
2667 }
2668 if (alarmsForUid.size() == 0) {
2669 mPendingBackgroundAlarms.removeAt(i);
2670 }
2671 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002672 if (didRemove) {
2673 if (DEBUG_BATCH) {
2674 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2675 }
2676 rebatchAllAlarmsLocked(true);
2677 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002678 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002679 }
2680 }
2681
Christopher Tate1d99c392017-12-07 16:54:04 -08002682 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002683 if (uid == Process.SYSTEM_UID) {
2684 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2685 return;
2686 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002687 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002688 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2689 try {
2690 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2691 uid, a.packageName)) {
2692 return true;
2693 }
2694 } catch (RemoteException e) { /* fall through */}
2695 return false;
2696 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002697 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2698 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002699 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002700 if (b.size() == 0) {
2701 mAlarmBatches.remove(i);
2702 }
2703 }
2704 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2705 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002706 if (a.uid == uid) {
2707 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2708 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002709 }
2710 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002711 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2712 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2713 mPendingBackgroundAlarms.removeAt(i);
2714 }
2715 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002716 if (didRemove) {
2717 if (DEBUG_BATCH) {
2718 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2719 }
2720 rebatchAllAlarmsLocked(true);
2721 rescheduleKernelAlarmsLocked();
2722 updateNextAlarmClockLocked();
2723 }
2724 }
2725
Adam Lesinski182f73f2013-12-05 16:48:06 -08002726 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002727 if (userHandle == UserHandle.USER_SYSTEM) {
2728 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2729 return;
2730 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002731 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002732 final Predicate<Alarm> whichAlarms =
2733 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002734 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2735 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002736 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002737 if (b.size() == 0) {
2738 mAlarmBatches.remove(i);
2739 }
2740 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002741 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002742 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002743 == userHandle) {
2744 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2745 mPendingWhileIdleAlarms.remove(i);
2746 }
2747 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002748 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2749 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2750 mPendingBackgroundAlarms.removeAt(i);
2751 }
2752 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002753 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2754 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2755 mLastAllowWhileIdleDispatch.removeAt(i);
2756 }
2757 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002758
2759 if (didRemove) {
2760 if (DEBUG_BATCH) {
2761 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2762 }
2763 rebatchAllAlarmsLocked(true);
2764 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002765 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002766 }
2767 }
2768
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002769 void interactiveStateChangedLocked(boolean interactive) {
2770 if (mInteractive != interactive) {
2771 mInteractive = interactive;
2772 final long nowELAPSED = SystemClock.elapsedRealtime();
2773 if (interactive) {
2774 if (mPendingNonWakeupAlarms.size() > 0) {
2775 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2776 mTotalDelayTime += thisDelayTime;
2777 if (mMaxDelayTime < thisDelayTime) {
2778 mMaxDelayTime = thisDelayTime;
2779 }
2780 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2781 mPendingNonWakeupAlarms.clear();
2782 }
2783 if (mNonInteractiveStartTime > 0) {
2784 long dur = nowELAPSED - mNonInteractiveStartTime;
2785 if (dur > mNonInteractiveTime) {
2786 mNonInteractiveTime = dur;
2787 }
2788 }
2789 } else {
2790 mNonInteractiveStartTime = nowELAPSED;
2791 }
2792 }
2793 }
2794
Adam Lesinski182f73f2013-12-05 16:48:06 -08002795 boolean lookForPackageLocked(String packageName) {
2796 for (int i = 0; i < mAlarmBatches.size(); i++) {
2797 Batch b = mAlarmBatches.get(i);
2798 if (b.hasPackage(packageName)) {
2799 return true;
2800 }
2801 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002802 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002803 final Alarm a = mPendingWhileIdleAlarms.get(i);
2804 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002805 return true;
2806 }
2807 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002808 return false;
2809 }
2810
2811 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002812 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002813 // The kernel never triggers alarms with negative wakeup times
2814 // so we ensure they are positive.
2815 long alarmSeconds, alarmNanoseconds;
2816 if (when < 0) {
2817 alarmSeconds = 0;
2818 alarmNanoseconds = 0;
2819 } else {
2820 alarmSeconds = when / 1000;
2821 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2822 }
Kweku Adams61e03292017-10-19 14:27:12 -07002823
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002824 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002825 } else {
2826 Message msg = Message.obtain();
2827 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002828
Adam Lesinski182f73f2013-12-05 16:48:06 -08002829 mHandler.removeMessages(ALARM_EVENT);
2830 mHandler.sendMessageAtTime(msg, when);
2831 }
2832 }
2833
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002834 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002835 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 for (int i=list.size()-1; i>=0; i--) {
2837 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002838 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2839 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002840 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 }
2842 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002843
2844 private static final String labelForType(int type) {
2845 switch (type) {
2846 case RTC: return "RTC";
2847 case RTC_WAKEUP : return "RTC_WAKEUP";
2848 case ELAPSED_REALTIME : return "ELAPSED";
2849 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002850 }
2851 return "--unknown--";
2852 }
2853
2854 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002855 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002856 for (int i=list.size()-1; i>=0; i--) {
2857 Alarm a = list.get(i);
2858 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002859 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2860 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002861 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002862 }
2863 }
2864
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002865 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002866 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002867 if (alarm.alarmClock != null) {
2868 // Don't block alarm clocks
2869 return false;
2870 }
2871 if (alarm.operation != null
2872 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2873 // Don't block starting foreground components
2874 return false;
2875 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002876 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002877 final int sourceUid = alarm.creatorUid;
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002878 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage,
2879 allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002880 }
2881
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002882 private native long init();
2883 private native void close(long nativeData);
2884 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2885 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002886 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002887 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888
Makoto Onukiadb50d82018-01-29 16:20:30 -08002889 private long getWhileIdleMinIntervalLocked(int uid) {
2890 final boolean dozing = mPendingIdleUntil != null;
2891 final boolean ebs = mForceAppStandbyTracker.isForceAllAppsStandbyEnabled();
2892 if (!dozing && !ebs) {
2893 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2894 }
2895 if (dozing) {
2896 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2897 }
2898 if (mUseAllowWhileIdleShortTime.get(uid)) {
2899 // if the last allow-while-idle went off while uid was fg, or the uid
2900 // recently came into fg, don't block the alarm for long.
2901 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2902 }
2903 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2904 }
2905
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002906 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002907 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002908 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002909 // batches are temporally sorted, so we need only pull from the
2910 // start of the list until we either empty it or hit a batch
2911 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002912 while (mAlarmBatches.size() > 0) {
2913 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002914 if (batch.start > nowELAPSED) {
2915 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002916 break;
2917 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002918
Christopher Tatee0a22b32013-07-11 14:43:13 -07002919 // We will (re)schedule some alarms now; don't let that interfere
2920 // with delivery of this current batch
2921 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002922
Christopher Tatee0a22b32013-07-11 14:43:13 -07002923 final int N = batch.size();
2924 for (int i = 0; i < N; i++) {
2925 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002926
2927 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2928 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2929 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002930 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002931 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002932 if (nowELAPSED < minTime) {
2933 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2934 // alarm went off for this app. Reschedule the alarm to be in the
2935 // correct time period.
2936 alarm.whenElapsed = minTime;
2937 if (alarm.maxWhenElapsed < minTime) {
2938 alarm.maxWhenElapsed = minTime;
2939 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002940 if (RECORD_DEVICE_IDLE_ALARMS) {
2941 IdleDispatchEntry ent = new IdleDispatchEntry();
2942 ent.uid = alarm.uid;
2943 ent.pkg = alarm.operation.getCreatorPackage();
2944 ent.tag = alarm.operation.getTag("");
2945 ent.op = "RESCHEDULE";
2946 ent.elapsedRealtime = nowELAPSED;
2947 ent.argRealtime = lastTime;
2948 mAllowWhileIdleDispatches.add(ent);
2949 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002950 setImplLocked(alarm, true, false);
2951 continue;
2952 }
2953 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002954 if (isBackgroundRestricted(alarm)) {
2955 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2956 if (DEBUG_BG_LIMIT) {
2957 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2958 }
2959 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2960 if (alarmsForUid == null) {
2961 alarmsForUid = new ArrayList<>();
2962 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2963 }
2964 alarmsForUid.add(alarm);
2965 continue;
2966 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002967
Christopher Tatee0a22b32013-07-11 14:43:13 -07002968 alarm.count = 1;
2969 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002970 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2971 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002972 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002973 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002974 if (mPendingIdleUntil == alarm) {
2975 mPendingIdleUntil = null;
2976 rebatchAllAlarmsLocked(false);
2977 restorePendingWhileIdleAlarmsLocked();
2978 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002979 if (mNextWakeFromIdle == alarm) {
2980 mNextWakeFromIdle = null;
2981 rebatchAllAlarmsLocked(false);
2982 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002983
2984 // Recurring alarms may have passed several alarm intervals while the
2985 // phone was asleep or off, so pass a trigger count when sending them.
2986 if (alarm.repeatInterval > 0) {
2987 // this adjustment will be zero if we're late by
2988 // less than one full repeat interval
Suprabh Shukla75edab12018-01-29 14:09:06 -08002989 alarm.count += (nowELAPSED - alarm.requestedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002990
2991 // Also schedule its next recurrence
2992 final long delta = alarm.count * alarm.repeatInterval;
2993 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002994 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002995 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002996 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2997 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002998 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002999
Christopher Tate864d42e2014-12-02 11:48:53 -08003000 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003001 hasWakeup = true;
3002 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003003
3004 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3005 if (alarm.alarmClock != null) {
3006 mNextAlarmClockMayChange = true;
3007 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003010
Christopher Tate1590f1e2014-10-02 17:27:57 -07003011 // This is a new alarm delivery set; bump the sequence number to indicate that
3012 // all apps' alarm delivery classes should be recalculated.
3013 mCurrentSeq++;
3014 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003015 Collections.sort(triggerList, mAlarmDispatchComparator);
3016
3017 if (localLOGV) {
3018 for (int i=0; i<triggerList.size(); i++) {
3019 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3020 }
3021 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003022
3023 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003024 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003025
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003026 /**
3027 * This Comparator sorts Alarms into increasing time order.
3028 */
3029 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3030 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003031 long when1 = a1.whenElapsed;
3032 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003033 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034 return 1;
3035 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003036 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037 return -1;
3038 }
3039 return 0;
3040 }
3041 }
Kweku Adams61e03292017-10-19 14:27:12 -07003042
Makoto Onuki2206af32017-11-21 16:25:35 -08003043 @VisibleForTesting
3044 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003045 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003046 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003047 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003048 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003049 public final IAlarmListener listener;
3050 public final String listenerTag;
3051 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003052 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003053 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003054 public final AlarmManager.AlarmClockInfo alarmClock;
3055 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003056 public final int creatorUid;
3057 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003058 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059 public int count;
3060 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003061 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003062 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003063 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shukla75edab12018-01-29 14:09:06 -08003064 public final long requestedWhenElapsed; // original expiry time requested by the app
3065 public final long requestedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003067 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003068
Christopher Tate3e04b472013-10-21 17:51:31 -07003069 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003070 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3071 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3072 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003073 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003074 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003075 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3076 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003077 when = _when;
3078 whenElapsed = _whenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003079 requestedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003080 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003081 maxWhenElapsed = _maxWhen;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003082 requestedMaxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003083 repeatInterval = _interval;
3084 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003085 listener = _rec;
3086 listenerTag = _listenerTag;
3087 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003088 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003089 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003090 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003091 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003092 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003093 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003094 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003095 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003096
Christopher Tate14a7bb02015-10-01 10:24:31 -07003097 public static String makeTag(PendingIntent pi, String tag, int type) {
3098 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3099 ? "*walarm*:" : "*alarm*:";
3100 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3101 }
3102
3103 public WakeupEvent makeWakeupEvent(long nowRTC) {
3104 return new WakeupEvent(nowRTC, creatorUid,
3105 (operation != null)
3106 ? operation.getIntent().getAction()
3107 : ("<listener>:" + listenerTag));
3108 }
3109
3110 // Returns true if either matches
3111 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3112 return (operation != null)
3113 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003114 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003115 }
3116
3117 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003118 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003119 }
3120
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003121 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003122 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003123 StringBuilder sb = new StringBuilder(128);
3124 sb.append("Alarm{");
3125 sb.append(Integer.toHexString(System.identityHashCode(this)));
3126 sb.append(" type ");
3127 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003128 sb.append(" when ");
3129 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003130 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003131 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003132 sb.append('}');
3133 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003134 }
3135
Kweku Adams61e03292017-10-19 14:27:12 -07003136 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003137 SimpleDateFormat sdf) {
3138 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003139 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003140 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003141 pw.print(" requestedWhenELapsed="); TimeUtils.formatDuration(
3142 requestedWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003143 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3144 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003145 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003146 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003147 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003148 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003149 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003150 }
3151 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003152 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003153 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003154 pw.print(" count="); pw.print(count);
3155 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003156 if (alarmClock != null) {
3157 pw.print(prefix); pw.println("Alarm clock:");
3158 pw.print(prefix); pw.print(" triggerTime=");
3159 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3160 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3161 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003162 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003163 if (listener != null) {
3164 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3165 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003166 }
Kweku Adams61e03292017-10-19 14:27:12 -07003167
3168 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3169 long nowRTC) {
3170 final long token = proto.start(fieldId);
3171
3172 proto.write(AlarmProto.TAG, statsTag);
3173 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003174 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003175 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3176 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3177 proto.write(AlarmProto.COUNT, count);
3178 proto.write(AlarmProto.FLAGS, flags);
3179 if (alarmClock != null) {
3180 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3181 }
3182 if (operation != null) {
3183 operation.writeToProto(proto, AlarmProto.OPERATION);
3184 }
3185 if (listener != null) {
3186 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3187 }
3188
3189 proto.end(token);
3190 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003191 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003192
Christopher Tatee0a22b32013-07-11 14:43:13 -07003193 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3194 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003195 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3196 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003197 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003198 break;
3199 }
3200
Christopher Tatee0a22b32013-07-11 14:43:13 -07003201 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003202 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3203 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003204 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003205 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003206 }
3207 }
3208
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003209 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3210 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3211 if (timeSinceOn < 5*60*1000) {
3212 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3213 return 2*60*1000;
3214 } else if (timeSinceOn < 30*60*1000) {
3215 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3216 return 15*60*1000;
3217 } else {
3218 // Otherwise, we will delay by at most an hour.
3219 return 60*60*1000;
3220 }
3221 }
3222
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003223 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003224 if (duration < 15*60*1000) {
3225 // If the duration until the time is less than 15 minutes, the maximum fuzz
3226 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003227 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003228 } else if (duration < 90*60*1000) {
3229 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3230 return 15*60*1000;
3231 } else {
3232 // Otherwise, we will fuzz by at most half an hour.
3233 return 30*60*1000;
3234 }
3235 }
3236
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003237 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3238 if (mInteractive) {
3239 return false;
3240 }
3241 if (mLastAlarmDeliveryTime <= 0) {
3242 return false;
3243 }
minho.choo649acab2014-12-12 16:13:55 +09003244 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003245 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3246 // and the next delivery time is in the past, then just deliver them all. This
3247 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3248 return false;
3249 }
3250 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3251 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3252 }
3253
3254 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3255 mLastAlarmDeliveryTime = nowELAPSED;
3256 for (int i=0; i<triggerList.size(); i++) {
3257 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003258 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003259 if (alarm.wakeup) {
3260 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3261 } else {
3262 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3263 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003264 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003265 if (localLOGV) {
3266 Slog.v(TAG, "sending alarm " + alarm);
3267 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003268 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003269 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3270 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003271 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003272 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003273 } catch (RuntimeException e) {
3274 Slog.w(TAG, "Failure sending alarm.", e);
3275 }
Tim Murray175c0f92017-11-28 15:01:04 -08003276 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003277 }
3278 }
3279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003280 private class AlarmThread extends Thread
3281 {
3282 public AlarmThread()
3283 {
3284 super("AlarmManager");
3285 }
Kweku Adams61e03292017-10-19 14:27:12 -07003286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 public void run()
3288 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003289 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 while (true)
3292 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003293 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003294 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003295
3296 triggerList.clear();
3297
Dianne Hackbornc3527222015-05-13 14:03:20 -07003298 final long nowRTC = System.currentTimeMillis();
3299 final long nowELAPSED = SystemClock.elapsedRealtime();
3300
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003302 // The kernel can give us spurious time change notifications due to
3303 // small adjustments it makes internally; we want to filter those out.
3304 final long lastTimeChangeClockTime;
3305 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003306 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003307 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3308 expectedClockTime = lastTimeChangeClockTime
3309 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003310 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003311 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3312 || nowRTC > (expectedClockTime+1000)) {
3313 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003314 // let's do it!
3315 if (DEBUG_BATCH) {
3316 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3317 }
3318 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003319 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003320 rebatchAllAlarms();
3321 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003322 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003323 synchronized (mLock) {
3324 mNumTimeChanged++;
3325 mLastTimeChangeClockTime = nowRTC;
3326 mLastTimeChangeRealtime = nowELAPSED;
3327 }
3328 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3329 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003330 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003331 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3332 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003333 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3334
3335 // The world has changed on us, so we need to re-evaluate alarms
3336 // regardless of whether the kernel has told us one went off.
3337 result |= IS_WAKEUP_MASK;
3338 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003339 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003340
Dianne Hackbornc3527222015-05-13 14:03:20 -07003341 if (result != TIME_CHANGED_MASK) {
3342 // If this was anything besides just a time change, then figure what if
3343 // anything to do about alarms.
3344 synchronized (mLock) {
3345 if (localLOGV) Slog.v(
3346 TAG, "Checking for alarms... rtc=" + nowRTC
3347 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003348
Dianne Hackbornc3527222015-05-13 14:03:20 -07003349 if (WAKEUP_STATS) {
3350 if ((result & IS_WAKEUP_MASK) != 0) {
3351 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3352 int n = 0;
3353 for (WakeupEvent event : mRecentWakeups) {
3354 if (event.when > newEarliest) break;
3355 n++; // number of now-stale entries at the list head
3356 }
3357 for (int i = 0; i < n; i++) {
3358 mRecentWakeups.remove();
3359 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003360
Dianne Hackbornc3527222015-05-13 14:03:20 -07003361 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003362 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003363 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003364
3365 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3366 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3367 // if there are no wakeup alarms and the screen is off, we can
3368 // delay what we have so far until the future.
3369 if (mPendingNonWakeupAlarms.size() == 0) {
3370 mStartCurrentDelayTime = nowELAPSED;
3371 mNextNonWakeupDeliveryTime = nowELAPSED
3372 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3373 }
3374 mPendingNonWakeupAlarms.addAll(triggerList);
3375 mNumDelayedAlarms += triggerList.size();
3376 rescheduleKernelAlarmsLocked();
3377 updateNextAlarmClockLocked();
3378 } else {
3379 // now deliver the alarm intents; if there are pending non-wakeup
3380 // alarms, we need to merge them in to the list. note we don't
3381 // just deliver them first because we generally want non-wakeup
3382 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003383 if (mPendingNonWakeupAlarms.size() > 0) {
3384 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3385 triggerList.addAll(mPendingNonWakeupAlarms);
3386 Collections.sort(triggerList, mAlarmDispatchComparator);
3387 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3388 mTotalDelayTime += thisDelayTime;
3389 if (mMaxDelayTime < thisDelayTime) {
3390 mMaxDelayTime = thisDelayTime;
3391 }
3392 mPendingNonWakeupAlarms.clear();
3393 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003394 boolean needRebatch = false;
3395 final HashSet<String> triggerPackages = new HashSet<>();
3396 for (int i = triggerList.size() - 1; i >= 0; i--) {
3397 triggerPackages.add(triggerList.get(i).sourcePackage);
3398 }
3399 outer:
3400 for (int i = 0; i < mAlarmBatches.size(); i++) {
3401 final Batch batch = mAlarmBatches.get(i);
3402 for (int j = 0; j < batch.size(); j++) {
3403 if (triggerPackages.contains(batch.get(j))) {
3404 needRebatch = true;
3405 break outer;
3406 }
3407 }
3408 }
3409 if (needRebatch) {
3410 rebatchAllAlarmsLocked(false);
3411 } else {
3412 rescheduleKernelAlarmsLocked();
3413 updateNextAlarmClockLocked();
3414 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003415 deliverAlarmsLocked(triggerList, nowELAPSED);
3416 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003418
3419 } else {
3420 // Just in case -- even though no wakeup flag was set, make sure
3421 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003422 synchronized (mLock) {
3423 rescheduleKernelAlarmsLocked();
3424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 }
3426 }
3427 }
3428 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003429
David Christieebe51fc2013-07-26 13:23:29 -07003430 /**
3431 * Attribute blame for a WakeLock.
3432 * @param pi PendingIntent to attribute blame to if ws is null.
3433 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003434 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003435 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003436 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003437 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003438 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003439 final boolean unimportant = pi == mTimeTickSender;
3440 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003441 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003442 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003443 } else {
3444 mWakeLock.setHistoryTag(null);
3445 }
3446 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003447 if (ws != null) {
3448 mWakeLock.setWorkSource(ws);
3449 return;
3450 }
3451
Christopher Tate14a7bb02015-10-01 10:24:31 -07003452 final int uid = (knownUid >= 0)
3453 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003454 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003455 if (uid >= 0) {
3456 mWakeLock.setWorkSource(new WorkSource(uid));
3457 return;
3458 }
3459 } catch (Exception e) {
3460 }
3461
3462 // Something went wrong; fall back to attributing the lock to the OS
3463 mWakeLock.setWorkSource(null);
3464 }
3465
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003466 private class AlarmHandler extends Handler {
3467 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003468 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3469 public static final int LISTENER_TIMEOUT = 3;
3470 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003471 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3472 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003473 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003474
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 public AlarmHandler() {
3476 }
Kweku Adams61e03292017-10-19 14:27:12 -07003477
Makoto Onuki4d298b52018-02-05 10:54:58 -08003478 public void postRemoveForStopped(int uid) {
3479 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3480 }
3481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003483 switch (msg.what) {
3484 case ALARM_EVENT: {
3485 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3486 synchronized (mLock) {
3487 final long nowRTC = System.currentTimeMillis();
3488 final long nowELAPSED = SystemClock.elapsedRealtime();
3489 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3490 updateNextAlarmClockLocked();
3491 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003492
Christopher Tate14a7bb02015-10-01 10:24:31 -07003493 // now trigger the alarms without the lock held
3494 for (int i=0; i<triggerList.size(); i++) {
3495 Alarm alarm = triggerList.get(i);
3496 try {
3497 alarm.operation.send();
3498 } catch (PendingIntent.CanceledException e) {
3499 if (alarm.repeatInterval > 0) {
3500 // This IntentSender is no longer valid, but this
3501 // is a repeating alarm, so toss the hoser.
3502 removeImpl(alarm.operation);
3503 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003504 }
3505 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003506 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003508
3509 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3510 sendNextAlarmClockChanged();
3511 break;
3512
3513 case LISTENER_TIMEOUT:
3514 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3515 break;
3516
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003517 case REPORT_ALARMS_ACTIVE:
3518 if (mLocalDeviceIdleController != null) {
3519 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3520 }
3521 break;
3522
Suprabh Shukla75edab12018-01-29 14:09:06 -08003523 case APP_STANDBY_PAROLE_CHANGED:
3524 synchronized (mLock) {
3525 mAppStandbyParole = (Boolean) msg.obj;
3526 rebatchAllAlarmsLocked(false);
3527 }
3528 break;
3529
3530 case APP_STANDBY_BUCKET_CHANGED:
3531 synchronized (mLock) {
3532 rebatchAllAlarmsLocked(false);
3533 }
3534 break;
3535
Makoto Onuki4d298b52018-02-05 10:54:58 -08003536 case REMOVE_FOR_STOPPED:
3537 synchronized (mLock) {
3538 removeForStoppedLocked(msg.arg1);
3539 }
3540 break;
3541
Christopher Tate14a7bb02015-10-01 10:24:31 -07003542 default:
3543 // nope, just ignore it
3544 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
3546 }
3547 }
Kweku Adams61e03292017-10-19 14:27:12 -07003548
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003549 class ClockReceiver extends BroadcastReceiver {
3550 public ClockReceiver() {
3551 IntentFilter filter = new IntentFilter();
3552 filter.addAction(Intent.ACTION_TIME_TICK);
3553 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003554 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003555 }
Kweku Adams61e03292017-10-19 14:27:12 -07003556
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 @Override
3558 public void onReceive(Context context, Intent intent) {
3559 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003560 if (DEBUG_BATCH) {
3561 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3562 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003563 synchronized (mLock) {
3564 mLastTickReceived = System.currentTimeMillis();
3565 }
Christopher Tate385e4982013-07-23 18:22:29 -07003566 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3568 // Since the kernel does not keep track of DST, we need to
3569 // reset the TZ information at the beginning of each day
3570 // based off of the current Zone gmt offset + userspace tracked
3571 // daylight savings information.
3572 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003573 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003574 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003575 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 }
3577 }
Kweku Adams61e03292017-10-19 14:27:12 -07003578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003580 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003581 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003582
3583 // Schedule this event for the amount of time that it would take to get to
3584 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003585 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003586
David Christieebe51fc2013-07-26 13:23:29 -07003587 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003588 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003589 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3590 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003591
3592 // Finally, remember when we set the tick alarm
3593 synchronized (mLock) {
3594 mLastTickSet = currentTime;
3595 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 }
Christopher Tate385e4982013-07-23 18:22:29 -07003597
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003598 public void scheduleDateChangedEvent() {
3599 Calendar calendar = Calendar.getInstance();
3600 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003601 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 calendar.set(Calendar.MINUTE, 0);
3603 calendar.set(Calendar.SECOND, 0);
3604 calendar.set(Calendar.MILLISECOND, 0);
3605 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003606
3607 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003608 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3609 AlarmManager.FLAG_STANDALONE, workSource, null,
3610 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003611 }
3612 }
Kweku Adams61e03292017-10-19 14:27:12 -07003613
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003614 class InteractiveStateReceiver extends BroadcastReceiver {
3615 public InteractiveStateReceiver() {
3616 IntentFilter filter = new IntentFilter();
3617 filter.addAction(Intent.ACTION_SCREEN_OFF);
3618 filter.addAction(Intent.ACTION_SCREEN_ON);
3619 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3620 getContext().registerReceiver(this, filter);
3621 }
3622
3623 @Override
3624 public void onReceive(Context context, Intent intent) {
3625 synchronized (mLock) {
3626 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3627 }
3628 }
3629 }
3630
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003631 class UninstallReceiver extends BroadcastReceiver {
3632 public UninstallReceiver() {
3633 IntentFilter filter = new IntentFilter();
3634 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3635 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003636 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003637 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003638 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003639 // Register for events related to sdcard installation.
3640 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003641 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003642 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003643 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003644 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003645 }
Kweku Adams61e03292017-10-19 14:27:12 -07003646
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 @Override
3648 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003649 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003650 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003651 String action = intent.getAction();
3652 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003653 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3654 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3655 for (String packageName : pkgList) {
3656 if (lookForPackageLocked(packageName)) {
3657 setResultCode(Activity.RESULT_OK);
3658 return;
3659 }
3660 }
3661 return;
3662 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003663 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003664 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3665 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3666 if (userHandle >= 0) {
3667 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003668 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3669 final Pair<String, Integer> packageUser =
3670 mLastAlarmDeliveredForPackage.keyAt(i);
3671 if (packageUser.second == userHandle) {
3672 mLastAlarmDeliveredForPackage.removeAt(i);
3673 }
3674 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003675 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003676 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003677 if (uid >= 0) {
3678 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003679 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003680 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003681 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003682 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3683 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3684 // This package is being updated; don't kill its alarms.
3685 return;
3686 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003687 Uri data = intent.getData();
3688 if (data != null) {
3689 String pkg = data.getSchemeSpecificPart();
3690 if (pkg != null) {
3691 pkgList = new String[]{pkg};
3692 }
3693 }
3694 }
3695 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003696 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3697 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3698 if (ArrayUtils.contains(pkgList, packageUser.first)
3699 && packageUser.second == UserHandle.getUserId(uid)) {
3700 mLastAlarmDeliveredForPackage.removeAt(i);
3701 }
3702 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003703 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003704 if (uid >= 0) {
3705 // package-removed case
3706 removeLocked(uid);
3707 } else {
3708 // external-applications-unavailable etc case
3709 removeLocked(pkg);
3710 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003711 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003712 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3713 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3714 if (uidStats.remove(pkg) != null) {
3715 if (uidStats.size() <= 0) {
3716 mBroadcastStats.removeAt(i);
3717 }
3718 }
3719 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 }
3722 }
3723 }
3724 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003725
3726 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003727 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003728 }
3729
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003730 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003731 if (disabled) {
3732 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003733 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003734 }
3735
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003736 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003737 }
3738
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003739 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003740 if (disabled) {
3741 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003742 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003743 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003744
3745 @Override public void onUidCachedChanged(int uid, boolean cached) {
3746 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003747 };
3748
Suprabh Shukla75edab12018-01-29 14:09:06 -08003749 /**
3750 * Tracking of app assignments to standby buckets
3751 */
3752 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3753 @Override
3754 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
3755 boolean idle, int bucket) {
3756 if (DEBUG_STANDBY) {
3757 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3758 bucket);
3759 }
3760 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3761 mHandler.sendEmptyMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3762 }
3763
3764 @Override
3765 public void onParoleStateChanged(boolean isParoleOn) {
3766 if (DEBUG_STANDBY) {
3767 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3768 }
3769 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3770 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3771 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3772 Boolean.valueOf(isParoleOn)).sendToTarget();
3773 }
3774 };
3775
Makoto Onuki2206af32017-11-21 16:25:35 -08003776 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003777 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003778 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003779 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003780 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003781 }
3782 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003783
3784 @Override
3785 public void unblockAlarmsForUid(int uid) {
3786 synchronized (mLock) {
3787 sendPendingBackgroundAlarmsLocked(uid, null);
3788 }
3789 }
3790
3791 @Override
3792 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3793 synchronized (mLock) {
3794 sendPendingBackgroundAlarmsLocked(uid, packageName);
3795 }
3796 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003797
3798 @Override
3799 public void onUidForeground(int uid, boolean foreground) {
3800 synchronized (mLock) {
3801 if (foreground) {
3802 mUseAllowWhileIdleShortTime.put(uid, true);
3803
3804 // Note we don't have to drain the pending while-idle alarms here, because
3805 // this event should coincide with unblockAlarmsForUid().
3806 }
3807 }
3808 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003809 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003810
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003812 String pkg = pi.getCreatorPackage();
3813 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003814 return getStatsLocked(uid, pkg);
3815 }
3816
3817 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003818 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3819 if (uidStats == null) {
3820 uidStats = new ArrayMap<String, BroadcastStats>();
3821 mBroadcastStats.put(uid, uidStats);
3822 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003823 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003824 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003825 bs = new BroadcastStats(uid, pkgName);
3826 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 }
3828 return bs;
3829 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003830
Christopher Tate21e9f192017-08-08 13:49:11 -07003831 /**
3832 * Canonical count of (operation.send() - onSendFinished()) and
3833 * listener send/complete/timeout invocations.
3834 * Guarded by the usual lock.
3835 */
3836 @GuardedBy("mLock")
3837 private int mSendCount = 0;
3838 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003839 private int mSendFinishCount = 0;
3840 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003841 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003842 @GuardedBy("mLock")
3843 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003844
Christopher Tate14a7bb02015-10-01 10:24:31 -07003845 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003846
Christopher Tate14a7bb02015-10-01 10:24:31 -07003847 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3848 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003849 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003850 return mInFlight.remove(i);
3851 }
3852 }
3853 mLog.w("No in-flight alarm for " + pi + " " + intent);
3854 return null;
3855 }
3856
3857 private InFlight removeLocked(IBinder listener) {
3858 for (int i = 0; i < mInFlight.size(); i++) {
3859 if (mInFlight.get(i).mListener == listener) {
3860 return mInFlight.remove(i);
3861 }
3862 }
3863 mLog.w("No in-flight alarm for listener " + listener);
3864 return null;
3865 }
3866
3867 private void updateStatsLocked(InFlight inflight) {
3868 final long nowELAPSED = SystemClock.elapsedRealtime();
3869 BroadcastStats bs = inflight.mBroadcastStats;
3870 bs.nesting--;
3871 if (bs.nesting <= 0) {
3872 bs.nesting = 0;
3873 bs.aggregateTime += nowELAPSED - bs.startTime;
3874 }
3875 FilterStats fs = inflight.mFilterStats;
3876 fs.nesting--;
3877 if (fs.nesting <= 0) {
3878 fs.nesting = 0;
3879 fs.aggregateTime += nowELAPSED - fs.startTime;
3880 }
3881 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003882 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3883 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003884 }
3885 }
3886
3887 private void updateTrackingLocked(InFlight inflight) {
3888 if (inflight != null) {
3889 updateStatsLocked(inflight);
3890 }
3891 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003892 if (DEBUG_WAKELOCK) {
3893 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3894 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003895 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003896 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003897 mWakeLock.release();
3898 if (mInFlight.size() > 0) {
3899 mLog.w("Finished all dispatches with " + mInFlight.size()
3900 + " remaining inflights");
3901 for (int i=0; i<mInFlight.size(); i++) {
3902 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3903 }
3904 mInFlight.clear();
3905 }
3906 } else {
3907 // the next of our alarms is now in flight. reattribute the wakelock.
3908 if (mInFlight.size() > 0) {
3909 InFlight inFlight = mInFlight.get(0);
3910 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3911 inFlight.mAlarmType, inFlight.mTag, -1, false);
3912 } else {
3913 // should never happen
3914 mLog.w("Alarm wakelock still held but sent queue empty");
3915 mWakeLock.setWorkSource(null);
3916 }
3917 }
3918 }
3919
3920 /**
3921 * Callback that arrives when a direct-call alarm reports that delivery has finished
3922 */
3923 @Override
3924 public void alarmComplete(IBinder who) {
3925 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003926 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003927 + " pid=" + Binder.getCallingPid());
3928 return;
3929 }
3930
3931 final long ident = Binder.clearCallingIdentity();
3932 try {
3933 synchronized (mLock) {
3934 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3935 InFlight inflight = removeLocked(who);
3936 if (inflight != null) {
3937 if (DEBUG_LISTENER_CALLBACK) {
3938 Slog.i(TAG, "alarmComplete() from " + who);
3939 }
3940 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003941 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003942 } else {
3943 // Delivery timed out, and the timeout handling already took care of
3944 // updating our tracking here, so we needn't do anything further.
3945 if (DEBUG_LISTENER_CALLBACK) {
3946 Slog.i(TAG, "Late alarmComplete() from " + who);
3947 }
3948 }
3949 }
3950 } finally {
3951 Binder.restoreCallingIdentity(ident);
3952 }
3953 }
3954
3955 /**
3956 * Callback that arrives when a PendingIntent alarm has finished delivery
3957 */
3958 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003959 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3960 String resultData, Bundle resultExtras) {
3961 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003962 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003963 updateTrackingLocked(removeLocked(pi, intent));
3964 }
3965 }
3966
3967 /**
3968 * Timeout of a direct-call alarm delivery
3969 */
3970 public void alarmTimedOut(IBinder who) {
3971 synchronized (mLock) {
3972 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003973 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003974 // TODO: implement ANR policy for the target
3975 if (DEBUG_LISTENER_CALLBACK) {
3976 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003978 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003979 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003980 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003981 if (DEBUG_LISTENER_CALLBACK) {
3982 Slog.i(TAG, "Spurious timeout of listener " + who);
3983 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003984 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003985 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003986 }
3987 }
3988
3989 /**
3990 * Deliver an alarm and set up the post-delivery handling appropriately
3991 */
3992 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3993 if (alarm.operation != null) {
3994 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003995 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08003996
3997 if (alarm.priorityClass.priority == PRIO_TICK) {
3998 mLastTickIssued = nowELAPSED;
3999 }
4000
Christopher Tate14a7bb02015-10-01 10:24:31 -07004001 try {
4002 alarm.operation.send(getContext(), 0,
4003 mBackgroundIntent.putExtra(
4004 Intent.EXTRA_ALARM_COUNT, alarm.count),
4005 mDeliveryTracker, mHandler, null,
4006 allowWhileIdle ? mIdleOptions : null);
4007 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004008 if (alarm.operation == mTimeTickSender) {
4009 Slog.wtf(TAG, "mTimeTickSender canceled");
4010 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004011 if (alarm.repeatInterval > 0) {
4012 // This IntentSender is no longer valid, but this
4013 // is a repeating alarm, so toss it
4014 removeImpl(alarm.operation);
4015 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004016 // No actual delivery was possible, so the delivery tracker's
4017 // 'finished' callback won't be invoked. We also don't need
4018 // to do any wakelock or stats tracking, so we have nothing
4019 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004020 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004021 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004022 }
4023 } else {
4024 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004025 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004026 try {
4027 if (DEBUG_LISTENER_CALLBACK) {
4028 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4029 + " listener=" + alarm.listener.asBinder());
4030 }
4031 alarm.listener.doAlarm(this);
4032 mHandler.sendMessageDelayed(
4033 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4034 alarm.listener.asBinder()),
4035 mConstants.LISTENER_TIMEOUT);
4036 } catch (Exception e) {
4037 if (DEBUG_LISTENER_CALLBACK) {
4038 Slog.i(TAG, "Alarm undeliverable to listener "
4039 + alarm.listener.asBinder(), e);
4040 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004041 // As in the PendingIntent.CanceledException case, delivery of the
4042 // alarm was not possible, so we have no wakelock or timeout or
4043 // stats management to do. It threw before we posted the delayed
4044 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004045 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004046 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004047 }
4048 }
4049
4050 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004051 if (DEBUG_WAKELOCK) {
4052 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4053 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004054 if (mBroadcastRefCount == 0) {
4055 setWakelockWorkSource(alarm.operation, alarm.workSource,
4056 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4057 true);
4058 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004059 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004060 }
4061 final InFlight inflight = new InFlight(AlarmManagerService.this,
4062 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4063 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4064 mInFlight.add(inflight);
4065 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004066 if (allowWhileIdle) {
4067 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004068 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukiadb50d82018-01-29 16:20:30 -08004069 if (mForceAppStandbyTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004070 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4071 } else {
4072 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4073 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004074 if (RECORD_DEVICE_IDLE_ALARMS) {
4075 IdleDispatchEntry ent = new IdleDispatchEntry();
4076 ent.uid = alarm.uid;
4077 ent.pkg = alarm.packageName;
4078 ent.tag = alarm.statsTag;
4079 ent.op = "DELIVER";
4080 ent.elapsedRealtime = nowELAPSED;
4081 mAllowWhileIdleDispatches.add(ent);
4082 }
4083 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004084 if (!UserHandle.isCore(alarm.creatorUid)) {
4085 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4086 UserHandle.getUserId(alarm.creatorUid));
4087 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4088 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004089
4090 final BroadcastStats bs = inflight.mBroadcastStats;
4091 bs.count++;
4092 if (bs.nesting == 0) {
4093 bs.nesting = 1;
4094 bs.startTime = nowELAPSED;
4095 } else {
4096 bs.nesting++;
4097 }
4098 final FilterStats fs = inflight.mFilterStats;
4099 fs.count++;
4100 if (fs.nesting == 0) {
4101 fs.nesting = 1;
4102 fs.startTime = nowELAPSED;
4103 } else {
4104 fs.nesting++;
4105 }
4106 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4107 || alarm.type == RTC_WAKEUP) {
4108 bs.numWakeup++;
4109 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004110 ActivityManager.noteWakeupAlarm(
4111 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4112 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004113 }
4114 }
4115 }
4116}