blob: 30dfee86403fa92e5d7cb2c3cce1113a19ca66be [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 pw.print(" mUseAllowWhileIdleShortTime: [");
1844 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
1845 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
1846 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
1847 pw.print(" ");
1848 }
1849 }
1850 pw.println("]");
1851
Suprabh Shukla75edab12018-01-29 14:09:06 -08001852 pw.println(" mLastAlarmDeliveredForPackage:");
1853 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1854 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1855 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1856 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1857 pw.println();
1858 }
1859 pw.println();
1860
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001861 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001862 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001863 pw.println(" Idle mode state:");
1864 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001865 if (mPendingIdleUntil != null) {
1866 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001867 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001868 } else {
1869 pw.println("null");
1870 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001871 pw.println(" Pending alarms:");
1872 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001873 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001874 if (mNextWakeFromIdle != null) {
1875 pw.println();
1876 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001877 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001878 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001879
1880 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001881 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001882 if (mPendingNonWakeupAlarms.size() > 0) {
1883 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001884 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001885 } else {
1886 pw.println("(none)");
1887 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001888 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001889 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1890 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001891 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001892 pw.print(", max non-interactive time: ");
1893 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1894 pw.println();
1895
1896 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001897 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001898 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1899 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1900 pw.print(" Listener send count: "); pw.println(mListenerCount);
1901 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001902 pw.println();
1903
Christopher Tate7f2a0352015-12-08 10:24:33 -08001904 if (mInFlight.size() > 0) {
1905 pw.println("Outstanding deliveries:");
1906 for (int i = 0; i < mInFlight.size(); i++) {
1907 pw.print(" #"); pw.print(i); pw.print(": ");
1908 pw.println(mInFlight.get(i));
1909 }
1910 pw.println();
1911 }
1912
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001913 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001914 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001915 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1916 pw.print(" UID ");
1917 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1918 pw.print(": ");
1919 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1920 nowELAPSED, pw);
1921 pw.println();
1922 }
1923 }
1924 pw.println();
1925
Dianne Hackborn81038902012-11-26 17:04:09 -08001926 if (mLog.dump(pw, " Recent problems", " ")) {
1927 pw.println();
1928 }
1929
1930 final FilterStats[] topFilters = new FilterStats[10];
1931 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1932 @Override
1933 public int compare(FilterStats lhs, FilterStats rhs) {
1934 if (lhs.aggregateTime < rhs.aggregateTime) {
1935 return 1;
1936 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1937 return -1;
1938 }
1939 return 0;
1940 }
1941 };
1942 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001943 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001944 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1945 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1946 for (int ip=0; ip<uidStats.size(); ip++) {
1947 BroadcastStats bs = uidStats.valueAt(ip);
1948 for (int is=0; is<bs.filterStats.size(); is++) {
1949 FilterStats fs = bs.filterStats.valueAt(is);
1950 int pos = len > 0
1951 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1952 if (pos < 0) {
1953 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001954 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001955 if (pos < topFilters.length) {
1956 int copylen = topFilters.length - pos - 1;
1957 if (copylen > 0) {
1958 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1959 }
1960 topFilters[pos] = fs;
1961 if (len < topFilters.length) {
1962 len++;
1963 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001964 }
1965 }
1966 }
1967 }
1968 if (len > 0) {
1969 pw.println(" Top Alarms:");
1970 for (int i=0; i<len; i++) {
1971 FilterStats fs = topFilters[i];
1972 pw.print(" ");
1973 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1974 TimeUtils.formatDuration(fs.aggregateTime, pw);
1975 pw.print(" running, "); pw.print(fs.numWakeup);
1976 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001977 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1978 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001979 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001980 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001981 pw.println();
1982 }
1983 }
1984
1985 pw.println(" ");
1986 pw.println(" Alarm Stats:");
1987 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001988 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1989 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1990 for (int ip=0; ip<uidStats.size(); ip++) {
1991 BroadcastStats bs = uidStats.valueAt(ip);
1992 pw.print(" ");
1993 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1994 UserHandle.formatUid(pw, bs.mUid);
1995 pw.print(":");
1996 pw.print(bs.mPackageName);
1997 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1998 pw.print(" running, "); pw.print(bs.numWakeup);
1999 pw.println(" wakeups:");
2000 tmpFilters.clear();
2001 for (int is=0; is<bs.filterStats.size(); is++) {
2002 tmpFilters.add(bs.filterStats.valueAt(is));
2003 }
2004 Collections.sort(tmpFilters, comparator);
2005 for (int i=0; i<tmpFilters.size(); i++) {
2006 FilterStats fs = tmpFilters.get(i);
2007 pw.print(" ");
2008 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2009 TimeUtils.formatDuration(fs.aggregateTime, pw);
2010 pw.print(" "); pw.print(fs.numWakeup);
2011 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002012 pw.print(" alarms, last ");
2013 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2014 pw.println(":");
2015 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002016 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002017 pw.println();
2018 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002019 }
2020 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002021 pw.println();
2022 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002023
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002024 if (RECORD_DEVICE_IDLE_ALARMS) {
2025 pw.println();
2026 pw.println(" Allow while idle dispatches:");
2027 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2028 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2029 pw.print(" ");
2030 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2031 pw.print(": ");
2032 UserHandle.formatUid(pw, ent.uid);
2033 pw.print(":");
2034 pw.println(ent.pkg);
2035 if (ent.op != null) {
2036 pw.print(" ");
2037 pw.print(ent.op);
2038 pw.print(" / ");
2039 pw.print(ent.tag);
2040 if (ent.argRealtime != 0) {
2041 pw.print(" (");
2042 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2043 pw.print(")");
2044 }
2045 pw.println();
2046 }
2047 }
2048 }
2049
Christopher Tate18a75f12013-07-01 18:18:59 -07002050 if (WAKEUP_STATS) {
2051 pw.println();
2052 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002053 long last = -1;
2054 for (WakeupEvent event : mRecentWakeups) {
2055 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2056 pw.print('|');
2057 if (last < 0) {
2058 pw.print('0');
2059 } else {
2060 pw.print(event.when - last);
2061 }
2062 last = event.when;
2063 pw.print('|'); pw.print(event.uid);
2064 pw.print('|'); pw.print(event.action);
2065 pw.println();
2066 }
2067 pw.println();
2068 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002069 }
2070 }
2071
Kweku Adams61e03292017-10-19 14:27:12 -07002072 void dumpProto(FileDescriptor fd) {
2073 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2074
2075 synchronized (mLock) {
2076 final long nowRTC = System.currentTimeMillis();
2077 final long nowElapsed = SystemClock.elapsedRealtime();
2078 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
2079 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
2080 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
2081 mLastTimeChangeClockTime);
2082 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
2083 mLastTimeChangeRealtime);
2084
2085 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
2086
Makoto Onuki2206af32017-11-21 16:25:35 -08002087 mForceAppStandbyTracker.dumpProto(proto,
2088 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07002089
2090 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2091 if (!mInteractive) {
2092 // Durations
2093 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2094 nowElapsed - mNonInteractiveStartTime);
2095 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2096 currentNonWakeupFuzzLocked(nowElapsed));
2097 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2098 nowElapsed - mLastAlarmDeliveryTime);
2099 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2100 nowElapsed - mNextNonWakeupDeliveryTime);
2101 }
2102
2103 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2104 mNextNonWakeup - nowElapsed);
2105 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2106 mNextWakeup - nowElapsed);
2107 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2108 nowElapsed - mLastWakeup);
2109 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2110 nowElapsed - mLastWakeupSet);
2111 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002112
2113 final TreeSet<Integer> users = new TreeSet<>();
2114 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2115 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2116 users.add(mNextAlarmClockForUser.keyAt(i));
2117 }
2118 final int pendingSendNextAlarmClockChangedForUserSize =
2119 mPendingSendNextAlarmClockChangedForUser.size();
2120 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2121 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2122 }
2123 for (int user : users) {
2124 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2125 final long time = next != null ? next.getTriggerTime() : 0;
2126 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2127 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2128 proto.write(AlarmClockMetadataProto.USER, user);
2129 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2130 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2131 proto.end(aToken);
2132 }
2133 for (Batch b : mAlarmBatches) {
2134 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2135 nowElapsed, nowRTC);
2136 }
2137 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2138 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2139 if (blockedAlarms != null) {
2140 for (Alarm a : blockedAlarms) {
2141 a.writeToProto(proto,
2142 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2143 nowElapsed, nowRTC);
2144 }
2145 }
2146 }
2147 if (mPendingIdleUntil != null) {
2148 mPendingIdleUntil.writeToProto(
2149 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2150 }
2151 for (Alarm a : mPendingWhileIdleAlarms) {
2152 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2153 nowElapsed, nowRTC);
2154 }
2155 if (mNextWakeFromIdle != null) {
2156 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2157 nowElapsed, nowRTC);
2158 }
2159
2160 for (Alarm a : mPendingNonWakeupAlarms) {
2161 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2162 nowElapsed, nowRTC);
2163 }
2164
2165 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2166 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2167 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2168 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2169 mNonInteractiveTime);
2170
2171 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2172 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2173 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2174 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2175 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2176
2177 for (InFlight f : mInFlight) {
2178 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2179 }
2180
Kweku Adams61e03292017-10-19 14:27:12 -07002181 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2182 final long token = proto.start(
2183 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2184 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2185 mLastAllowWhileIdleDispatch.keyAt(i));
2186 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2187 mLastAllowWhileIdleDispatch.valueAt(i));
2188 proto.end(token);
2189 }
2190
2191 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2192
2193 final FilterStats[] topFilters = new FilterStats[10];
2194 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2195 @Override
2196 public int compare(FilterStats lhs, FilterStats rhs) {
2197 if (lhs.aggregateTime < rhs.aggregateTime) {
2198 return 1;
2199 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2200 return -1;
2201 }
2202 return 0;
2203 }
2204 };
2205 int len = 0;
2206 // Get the top 10 FilterStats, ordered by aggregateTime.
2207 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2208 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2209 for (int ip = 0; ip < uidStats.size(); ++ip) {
2210 BroadcastStats bs = uidStats.valueAt(ip);
2211 for (int is = 0; is < bs.filterStats.size(); ++is) {
2212 FilterStats fs = bs.filterStats.valueAt(is);
2213 int pos = len > 0
2214 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2215 if (pos < 0) {
2216 pos = -pos - 1;
2217 }
2218 if (pos < topFilters.length) {
2219 int copylen = topFilters.length - pos - 1;
2220 if (copylen > 0) {
2221 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2222 }
2223 topFilters[pos] = fs;
2224 if (len < topFilters.length) {
2225 len++;
2226 }
2227 }
2228 }
2229 }
2230 }
2231 for (int i = 0; i < len; ++i) {
2232 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2233 FilterStats fs = topFilters[i];
2234
2235 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2236 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2237 fs.mBroadcastStats.mPackageName);
2238 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2239
2240 proto.end(token);
2241 }
2242
2243 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2244 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2245 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2246 for (int ip = 0; ip < uidStats.size(); ++ip) {
2247 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2248
2249 BroadcastStats bs = uidStats.valueAt(ip);
2250 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2251
2252 // uidStats is an ArrayMap, which we can't sort.
2253 tmpFilters.clear();
2254 for (int is = 0; is < bs.filterStats.size(); ++is) {
2255 tmpFilters.add(bs.filterStats.valueAt(is));
2256 }
2257 Collections.sort(tmpFilters, comparator);
2258 for (FilterStats fs : tmpFilters) {
2259 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2260 }
2261
2262 proto.end(token);
2263 }
2264 }
2265
2266 if (RECORD_DEVICE_IDLE_ALARMS) {
2267 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2268 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2269 final long token = proto.start(
2270 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2271
2272 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2273 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2274 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2275 proto.write(IdleDispatchEntryProto.OP, ent.op);
2276 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2277 ent.elapsedRealtime);
2278 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2279
2280 proto.end(token);
2281 }
2282 }
2283
2284 if (WAKEUP_STATS) {
2285 for (WakeupEvent event : mRecentWakeups) {
2286 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2287 proto.write(WakeupEventProto.UID, event.uid);
2288 proto.write(WakeupEventProto.ACTION, event.action);
2289 proto.write(WakeupEventProto.WHEN, event.when);
2290 proto.end(token);
2291 }
2292 }
2293 }
2294
2295 proto.flush();
2296 }
2297
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002298 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002299 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2300 PrintWriter pw = new PrintWriter(bs);
2301 final long nowRTC = System.currentTimeMillis();
2302 final long nowELAPSED = SystemClock.elapsedRealtime();
2303 final int NZ = mAlarmBatches.size();
2304 for (int iz = 0; iz < NZ; iz++) {
2305 Batch bz = mAlarmBatches.get(iz);
2306 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002307 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002308 pw.flush();
2309 Slog.v(TAG, bs.toString());
2310 bs.reset();
2311 }
2312 }
2313
2314 private boolean validateConsistencyLocked() {
2315 if (DEBUG_VALIDATE) {
2316 long lastTime = Long.MIN_VALUE;
2317 final int N = mAlarmBatches.size();
2318 for (int i = 0; i < N; i++) {
2319 Batch b = mAlarmBatches.get(i);
2320 if (b.start >= lastTime) {
2321 // duplicate start times are okay because of standalone batches
2322 lastTime = b.start;
2323 } else {
2324 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002325 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2326 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002327 return false;
2328 }
2329 }
2330 }
2331 return true;
2332 }
2333
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002334 private Batch findFirstWakeupBatchLocked() {
2335 final int N = mAlarmBatches.size();
2336 for (int i = 0; i < N; i++) {
2337 Batch b = mAlarmBatches.get(i);
2338 if (b.hasWakeups()) {
2339 return b;
2340 }
2341 }
2342 return null;
2343 }
2344
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002345 long getNextWakeFromIdleTimeImpl() {
2346 synchronized (mLock) {
2347 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2348 }
2349 }
2350
2351 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002352 synchronized (mLock) {
2353 return mNextAlarmClockForUser.get(userId);
2354 }
2355 }
2356
2357 /**
2358 * Recomputes the next alarm clock for all users.
2359 */
2360 private void updateNextAlarmClockLocked() {
2361 if (!mNextAlarmClockMayChange) {
2362 return;
2363 }
2364 mNextAlarmClockMayChange = false;
2365
Jose Lima235510e2014-08-13 12:50:01 -07002366 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002367 nextForUser.clear();
2368
2369 final int N = mAlarmBatches.size();
2370 for (int i = 0; i < N; i++) {
2371 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2372 final int M = alarms.size();
2373
2374 for (int j = 0; j < M; j++) {
2375 Alarm a = alarms.get(j);
2376 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002377 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002378 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002379
2380 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002381 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002382 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002383 " for user " + userId);
2384 }
2385
2386 // Alarms and batches are sorted by time, no need to compare times here.
2387 if (nextForUser.get(userId) == null) {
2388 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002389 } else if (a.alarmClock.equals(current)
2390 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2391 // same/earlier time and it's the one we cited before, so stick with it
2392 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002393 }
2394 }
2395 }
2396 }
2397
2398 // Update mNextAlarmForUser with new values.
2399 final int NN = nextForUser.size();
2400 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002401 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002402 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002403 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002404 if (!newAlarm.equals(currentAlarm)) {
2405 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2406 }
2407 }
2408
2409 // Remove users without any alarm clocks scheduled.
2410 final int NNN = mNextAlarmClockForUser.size();
2411 for (int i = NNN - 1; i >= 0; i--) {
2412 int userId = mNextAlarmClockForUser.keyAt(i);
2413 if (nextForUser.get(userId) == null) {
2414 updateNextAlarmInfoForUserLocked(userId, null);
2415 }
2416 }
2417 }
2418
Jose Lima235510e2014-08-13 12:50:01 -07002419 private void updateNextAlarmInfoForUserLocked(int userId,
2420 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002421 if (alarmClock != null) {
2422 if (DEBUG_ALARM_CLOCK) {
2423 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002424 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002425 }
2426 mNextAlarmClockForUser.put(userId, alarmClock);
2427 } else {
2428 if (DEBUG_ALARM_CLOCK) {
2429 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2430 }
2431 mNextAlarmClockForUser.remove(userId);
2432 }
2433
2434 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2435 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2436 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2437 }
2438
2439 /**
2440 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2441 * for which alarm clocks have changed since the last call to this.
2442 *
2443 * Do not call with a lock held. Only call from mHandler's thread.
2444 *
2445 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2446 */
2447 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002448 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002449 pendingUsers.clear();
2450
2451 synchronized (mLock) {
2452 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2453 for (int i = 0; i < N; i++) {
2454 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2455 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2456 }
2457 mPendingSendNextAlarmClockChangedForUser.clear();
2458 }
2459
2460 final int N = pendingUsers.size();
2461 for (int i = 0; i < N; i++) {
2462 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002463 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002464 Settings.System.putStringForUser(getContext().getContentResolver(),
2465 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002466 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002467 userId);
2468
2469 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2470 new UserHandle(userId));
2471 }
2472 }
2473
2474 /**
2475 * Formats an alarm like platform/packages/apps/DeskClock used to.
2476 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002477 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2478 int userId) {
2479 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002480 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2481 return (info == null) ? "" :
2482 DateFormat.format(pattern, info.getTriggerTime()).toString();
2483 }
2484
Adam Lesinski182f73f2013-12-05 16:48:06 -08002485 void rescheduleKernelAlarmsLocked() {
2486 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2487 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002488 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002489 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002490 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002491 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002492 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002493 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002494 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002495 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002496 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002497 if (firstBatch != firstWakeup) {
2498 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002499 }
2500 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002501 if (mPendingNonWakeupAlarms.size() > 0) {
2502 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2503 nextNonWakeup = mNextNonWakeupDeliveryTime;
2504 }
2505 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002506 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002507 mNextNonWakeup = nextNonWakeup;
2508 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2509 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002510 }
2511
Christopher Tate14a7bb02015-10-01 10:24:31 -07002512 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002513 if (operation == null && directReceiver == null) {
2514 if (localLOGV) {
2515 Slog.w(TAG, "requested remove() of null operation",
2516 new RuntimeException("here"));
2517 }
2518 return;
2519 }
2520
Adam Lesinski182f73f2013-12-05 16:48:06 -08002521 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002522 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002523 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2524 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002525 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002526 if (b.size() == 0) {
2527 mAlarmBatches.remove(i);
2528 }
2529 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002530 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002531 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002532 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2533 mPendingWhileIdleAlarms.remove(i);
2534 }
2535 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002536 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2537 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2538 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2539 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2540 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2541 alarmsForUid.remove(j);
2542 }
2543 }
2544 if (alarmsForUid.size() == 0) {
2545 mPendingBackgroundAlarms.removeAt(i);
2546 }
2547 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002548 if (didRemove) {
2549 if (DEBUG_BATCH) {
2550 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2551 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002552 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002553 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002554 mPendingIdleUntil = null;
2555 restorePending = true;
2556 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002557 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002558 mNextWakeFromIdle = null;
2559 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002560 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002561 if (restorePending) {
2562 restorePendingWhileIdleAlarmsLocked();
2563 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002564 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002565 }
2566 }
2567
Christopher Tate1d99c392017-12-07 16:54:04 -08002568 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002569 if (uid == Process.SYSTEM_UID) {
2570 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2571 return;
2572 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002573 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002574 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002575 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2576 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002577 didRemove |= b.remove(whichAlarms);
2578 if (b.size() == 0) {
2579 mAlarmBatches.remove(i);
2580 }
2581 }
2582 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2583 final Alarm a = mPendingWhileIdleAlarms.get(i);
2584 if (a.uid == uid) {
2585 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2586 mPendingWhileIdleAlarms.remove(i);
2587 }
2588 }
2589 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2590 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2591 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2592 if (alarmsForUid.get(j).uid == uid) {
2593 alarmsForUid.remove(j);
2594 }
2595 }
2596 if (alarmsForUid.size() == 0) {
2597 mPendingBackgroundAlarms.removeAt(i);
2598 }
2599 }
2600 if (didRemove) {
2601 if (DEBUG_BATCH) {
2602 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2603 }
2604 rebatchAllAlarmsLocked(true);
2605 rescheduleKernelAlarmsLocked();
2606 updateNextAlarmClockLocked();
2607 }
2608 }
2609
2610 void removeLocked(final String packageName) {
2611 if (packageName == null) {
2612 if (localLOGV) {
2613 Slog.w(TAG, "requested remove() of null packageName",
2614 new RuntimeException("here"));
2615 }
2616 return;
2617 }
2618
2619 boolean didRemove = false;
2620 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002621 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002622 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2623 Batch b = mAlarmBatches.get(i);
2624 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002625 if (b.size() == 0) {
2626 mAlarmBatches.remove(i);
2627 }
2628 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002629 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2630 if (oldHasTick != newHasTick) {
2631 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2632 }
2633
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002634 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002635 final Alarm a = mPendingWhileIdleAlarms.get(i);
2636 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002637 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2638 mPendingWhileIdleAlarms.remove(i);
2639 }
2640 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002641 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2642 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2643 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2644 if (alarmsForUid.get(j).matches(packageName)) {
2645 alarmsForUid.remove(j);
2646 }
2647 }
2648 if (alarmsForUid.size() == 0) {
2649 mPendingBackgroundAlarms.removeAt(i);
2650 }
2651 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002652 if (didRemove) {
2653 if (DEBUG_BATCH) {
2654 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2655 }
2656 rebatchAllAlarmsLocked(true);
2657 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002658 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002659 }
2660 }
2661
Christopher Tate1d99c392017-12-07 16:54:04 -08002662 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002663 if (uid == Process.SYSTEM_UID) {
2664 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2665 return;
2666 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002667 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002668 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2669 try {
2670 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2671 uid, a.packageName)) {
2672 return true;
2673 }
2674 } catch (RemoteException e) { /* fall through */}
2675 return false;
2676 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002677 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2678 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002679 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002680 if (b.size() == 0) {
2681 mAlarmBatches.remove(i);
2682 }
2683 }
2684 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2685 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002686 if (a.uid == uid) {
2687 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2688 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002689 }
2690 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002691 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2692 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2693 mPendingBackgroundAlarms.removeAt(i);
2694 }
2695 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002696 if (didRemove) {
2697 if (DEBUG_BATCH) {
2698 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2699 }
2700 rebatchAllAlarmsLocked(true);
2701 rescheduleKernelAlarmsLocked();
2702 updateNextAlarmClockLocked();
2703 }
2704 }
2705
Adam Lesinski182f73f2013-12-05 16:48:06 -08002706 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002707 if (userHandle == UserHandle.USER_SYSTEM) {
2708 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2709 return;
2710 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002711 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002712 final Predicate<Alarm> whichAlarms =
2713 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002714 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2715 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002716 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002717 if (b.size() == 0) {
2718 mAlarmBatches.remove(i);
2719 }
2720 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002721 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002722 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002723 == userHandle) {
2724 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2725 mPendingWhileIdleAlarms.remove(i);
2726 }
2727 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002728 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2729 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2730 mPendingBackgroundAlarms.removeAt(i);
2731 }
2732 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002733 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2734 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2735 mLastAllowWhileIdleDispatch.removeAt(i);
2736 }
2737 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002738
2739 if (didRemove) {
2740 if (DEBUG_BATCH) {
2741 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2742 }
2743 rebatchAllAlarmsLocked(true);
2744 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002745 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002746 }
2747 }
2748
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002749 void interactiveStateChangedLocked(boolean interactive) {
2750 if (mInteractive != interactive) {
2751 mInteractive = interactive;
2752 final long nowELAPSED = SystemClock.elapsedRealtime();
2753 if (interactive) {
2754 if (mPendingNonWakeupAlarms.size() > 0) {
2755 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2756 mTotalDelayTime += thisDelayTime;
2757 if (mMaxDelayTime < thisDelayTime) {
2758 mMaxDelayTime = thisDelayTime;
2759 }
2760 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2761 mPendingNonWakeupAlarms.clear();
2762 }
2763 if (mNonInteractiveStartTime > 0) {
2764 long dur = nowELAPSED - mNonInteractiveStartTime;
2765 if (dur > mNonInteractiveTime) {
2766 mNonInteractiveTime = dur;
2767 }
2768 }
2769 } else {
2770 mNonInteractiveStartTime = nowELAPSED;
2771 }
2772 }
2773 }
2774
Adam Lesinski182f73f2013-12-05 16:48:06 -08002775 boolean lookForPackageLocked(String packageName) {
2776 for (int i = 0; i < mAlarmBatches.size(); i++) {
2777 Batch b = mAlarmBatches.get(i);
2778 if (b.hasPackage(packageName)) {
2779 return true;
2780 }
2781 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002782 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002783 final Alarm a = mPendingWhileIdleAlarms.get(i);
2784 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002785 return true;
2786 }
2787 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002788 return false;
2789 }
2790
2791 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002792 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002793 // The kernel never triggers alarms with negative wakeup times
2794 // so we ensure they are positive.
2795 long alarmSeconds, alarmNanoseconds;
2796 if (when < 0) {
2797 alarmSeconds = 0;
2798 alarmNanoseconds = 0;
2799 } else {
2800 alarmSeconds = when / 1000;
2801 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2802 }
Kweku Adams61e03292017-10-19 14:27:12 -07002803
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002804 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002805 } else {
2806 Message msg = Message.obtain();
2807 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002808
Adam Lesinski182f73f2013-12-05 16:48:06 -08002809 mHandler.removeMessages(ALARM_EVENT);
2810 mHandler.sendMessageAtTime(msg, when);
2811 }
2812 }
2813
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002814 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002815 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002816 for (int i=list.size()-1; i>=0; i--) {
2817 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002818 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2819 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002820 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002821 }
2822 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002823
2824 private static final String labelForType(int type) {
2825 switch (type) {
2826 case RTC: return "RTC";
2827 case RTC_WAKEUP : return "RTC_WAKEUP";
2828 case ELAPSED_REALTIME : return "ELAPSED";
2829 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002830 }
2831 return "--unknown--";
2832 }
2833
2834 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002835 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002836 for (int i=list.size()-1; i>=0; i--) {
2837 Alarm a = list.get(i);
2838 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002839 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2840 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002841 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002842 }
2843 }
2844
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002845 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002846 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002847 if (alarm.alarmClock != null) {
2848 // Don't block alarm clocks
2849 return false;
2850 }
2851 if (alarm.operation != null
2852 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2853 // Don't block starting foreground components
2854 return false;
2855 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002856 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002857 final int sourceUid = alarm.creatorUid;
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002858 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage,
2859 allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002860 }
2861
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002862 private native long init();
2863 private native void close(long nativeData);
2864 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2865 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002866 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002867 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002869 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002870 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002871 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002872 // batches are temporally sorted, so we need only pull from the
2873 // start of the list until we either empty it or hit a batch
2874 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002875 while (mAlarmBatches.size() > 0) {
2876 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002877 if (batch.start > nowELAPSED) {
2878 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002879 break;
2880 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881
Christopher Tatee0a22b32013-07-11 14:43:13 -07002882 // We will (re)schedule some alarms now; don't let that interfere
2883 // with delivery of this current batch
2884 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002885
Christopher Tatee0a22b32013-07-11 14:43:13 -07002886 final int N = batch.size();
2887 for (int i = 0; i < N; i++) {
2888 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002889
2890 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2891 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2892 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002893 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
2894 final boolean dozing = mPendingIdleUntil != null;
2895 final boolean ebs = mForceAppStandbyTracker.isForceAllAppsStandbyEnabled();
2896 final long minTime;
2897 if (!dozing && !ebs) {
2898 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2899 } else if (dozing) {
2900 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2901 } else if (mUseAllowWhileIdleShortTime.get(alarm.creatorUid)) {
2902 // if the last allow-while-idle went off while uid was fg, or the uid
2903 // recently came into fg, don't block the alarm for long.
2904 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
2905 } else {
2906 minTime = lastTime + mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
2907 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002908 if (nowELAPSED < minTime) {
2909 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2910 // alarm went off for this app. Reschedule the alarm to be in the
2911 // correct time period.
2912 alarm.whenElapsed = minTime;
2913 if (alarm.maxWhenElapsed < minTime) {
2914 alarm.maxWhenElapsed = minTime;
2915 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002916 if (RECORD_DEVICE_IDLE_ALARMS) {
2917 IdleDispatchEntry ent = new IdleDispatchEntry();
2918 ent.uid = alarm.uid;
2919 ent.pkg = alarm.operation.getCreatorPackage();
2920 ent.tag = alarm.operation.getTag("");
2921 ent.op = "RESCHEDULE";
2922 ent.elapsedRealtime = nowELAPSED;
2923 ent.argRealtime = lastTime;
2924 mAllowWhileIdleDispatches.add(ent);
2925 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002926 setImplLocked(alarm, true, false);
2927 continue;
2928 }
2929 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002930 if (isBackgroundRestricted(alarm)) {
2931 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2932 if (DEBUG_BG_LIMIT) {
2933 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2934 }
2935 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2936 if (alarmsForUid == null) {
2937 alarmsForUid = new ArrayList<>();
2938 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2939 }
2940 alarmsForUid.add(alarm);
2941 continue;
2942 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002943
Christopher Tatee0a22b32013-07-11 14:43:13 -07002944 alarm.count = 1;
2945 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002946 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2947 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002948 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002949 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002950 if (mPendingIdleUntil == alarm) {
2951 mPendingIdleUntil = null;
2952 rebatchAllAlarmsLocked(false);
2953 restorePendingWhileIdleAlarmsLocked();
2954 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002955 if (mNextWakeFromIdle == alarm) {
2956 mNextWakeFromIdle = null;
2957 rebatchAllAlarmsLocked(false);
2958 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002959
2960 // Recurring alarms may have passed several alarm intervals while the
2961 // phone was asleep or off, so pass a trigger count when sending them.
2962 if (alarm.repeatInterval > 0) {
2963 // this adjustment will be zero if we're late by
2964 // less than one full repeat interval
Suprabh Shukla75edab12018-01-29 14:09:06 -08002965 alarm.count += (nowELAPSED - alarm.requestedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002966
2967 // Also schedule its next recurrence
2968 final long delta = alarm.count * alarm.repeatInterval;
2969 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002970 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002971 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002972 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2973 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002975
Christopher Tate864d42e2014-12-02 11:48:53 -08002976 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002977 hasWakeup = true;
2978 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002979
2980 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2981 if (alarm.alarmClock != null) {
2982 mNextAlarmClockMayChange = true;
2983 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002986
Christopher Tate1590f1e2014-10-02 17:27:57 -07002987 // This is a new alarm delivery set; bump the sequence number to indicate that
2988 // all apps' alarm delivery classes should be recalculated.
2989 mCurrentSeq++;
2990 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002991 Collections.sort(triggerList, mAlarmDispatchComparator);
2992
2993 if (localLOGV) {
2994 for (int i=0; i<triggerList.size(); i++) {
2995 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2996 }
2997 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002998
2999 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003000 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003001
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003002 /**
3003 * This Comparator sorts Alarms into increasing time order.
3004 */
3005 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3006 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003007 long when1 = a1.whenElapsed;
3008 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003009 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003010 return 1;
3011 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003012 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003013 return -1;
3014 }
3015 return 0;
3016 }
3017 }
Kweku Adams61e03292017-10-19 14:27:12 -07003018
Makoto Onuki2206af32017-11-21 16:25:35 -08003019 @VisibleForTesting
3020 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003021 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003022 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003023 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003024 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003025 public final IAlarmListener listener;
3026 public final String listenerTag;
3027 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003028 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003029 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003030 public final AlarmManager.AlarmClockInfo alarmClock;
3031 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003032 public final int creatorUid;
3033 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003034 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003035 public int count;
3036 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003037 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003038 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003039 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shukla75edab12018-01-29 14:09:06 -08003040 public final long requestedWhenElapsed; // original expiry time requested by the app
3041 public final long requestedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003042 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003043 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003044
Christopher Tate3e04b472013-10-21 17:51:31 -07003045 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003046 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3047 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3048 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003049 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003050 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003051 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3052 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003053 when = _when;
3054 whenElapsed = _whenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003055 requestedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003056 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003057 maxWhenElapsed = _maxWhen;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003058 requestedMaxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003059 repeatInterval = _interval;
3060 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003061 listener = _rec;
3062 listenerTag = _listenerTag;
3063 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003064 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003065 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003066 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003067 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003068 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003069 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003070 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003071 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003072
Christopher Tate14a7bb02015-10-01 10:24:31 -07003073 public static String makeTag(PendingIntent pi, String tag, int type) {
3074 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3075 ? "*walarm*:" : "*alarm*:";
3076 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3077 }
3078
3079 public WakeupEvent makeWakeupEvent(long nowRTC) {
3080 return new WakeupEvent(nowRTC, creatorUid,
3081 (operation != null)
3082 ? operation.getIntent().getAction()
3083 : ("<listener>:" + listenerTag));
3084 }
3085
3086 // Returns true if either matches
3087 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3088 return (operation != null)
3089 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003090 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003091 }
3092
3093 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003094 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003095 }
3096
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003098 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003099 StringBuilder sb = new StringBuilder(128);
3100 sb.append("Alarm{");
3101 sb.append(Integer.toHexString(System.identityHashCode(this)));
3102 sb.append(" type ");
3103 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003104 sb.append(" when ");
3105 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003106 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003107 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003108 sb.append('}');
3109 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003110 }
3111
Kweku Adams61e03292017-10-19 14:27:12 -07003112 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003113 SimpleDateFormat sdf) {
3114 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003115 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003116 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003117 pw.print(" requestedWhenELapsed="); TimeUtils.formatDuration(
3118 requestedWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003119 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3120 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003121 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003122 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003123 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003124 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003125 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003126 }
3127 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003128 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003129 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003130 pw.print(" count="); pw.print(count);
3131 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003132 if (alarmClock != null) {
3133 pw.print(prefix); pw.println("Alarm clock:");
3134 pw.print(prefix); pw.print(" triggerTime=");
3135 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3136 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3137 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003138 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003139 if (listener != null) {
3140 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3141 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003142 }
Kweku Adams61e03292017-10-19 14:27:12 -07003143
3144 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3145 long nowRTC) {
3146 final long token = proto.start(fieldId);
3147
3148 proto.write(AlarmProto.TAG, statsTag);
3149 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003150 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003151 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3152 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3153 proto.write(AlarmProto.COUNT, count);
3154 proto.write(AlarmProto.FLAGS, flags);
3155 if (alarmClock != null) {
3156 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3157 }
3158 if (operation != null) {
3159 operation.writeToProto(proto, AlarmProto.OPERATION);
3160 }
3161 if (listener != null) {
3162 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3163 }
3164
3165 proto.end(token);
3166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003168
Christopher Tatee0a22b32013-07-11 14:43:13 -07003169 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3170 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003171 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3172 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003173 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003174 break;
3175 }
3176
Christopher Tatee0a22b32013-07-11 14:43:13 -07003177 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003178 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3179 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003180 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003181 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003182 }
3183 }
3184
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003185 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3186 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3187 if (timeSinceOn < 5*60*1000) {
3188 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3189 return 2*60*1000;
3190 } else if (timeSinceOn < 30*60*1000) {
3191 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3192 return 15*60*1000;
3193 } else {
3194 // Otherwise, we will delay by at most an hour.
3195 return 60*60*1000;
3196 }
3197 }
3198
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003199 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003200 if (duration < 15*60*1000) {
3201 // If the duration until the time is less than 15 minutes, the maximum fuzz
3202 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003203 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003204 } else if (duration < 90*60*1000) {
3205 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3206 return 15*60*1000;
3207 } else {
3208 // Otherwise, we will fuzz by at most half an hour.
3209 return 30*60*1000;
3210 }
3211 }
3212
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003213 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3214 if (mInteractive) {
3215 return false;
3216 }
3217 if (mLastAlarmDeliveryTime <= 0) {
3218 return false;
3219 }
minho.choo649acab2014-12-12 16:13:55 +09003220 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003221 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3222 // and the next delivery time is in the past, then just deliver them all. This
3223 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3224 return false;
3225 }
3226 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3227 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3228 }
3229
3230 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3231 mLastAlarmDeliveryTime = nowELAPSED;
3232 for (int i=0; i<triggerList.size(); i++) {
3233 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003234 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003235 if (alarm.wakeup) {
3236 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3237 } else {
3238 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3239 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003240 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003241 if (localLOGV) {
3242 Slog.v(TAG, "sending alarm " + alarm);
3243 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003244 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003245 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3246 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003247 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003248 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003249 } catch (RuntimeException e) {
3250 Slog.w(TAG, "Failure sending alarm.", e);
3251 }
Tim Murray175c0f92017-11-28 15:01:04 -08003252 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003253 }
3254 }
3255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 private class AlarmThread extends Thread
3257 {
3258 public AlarmThread()
3259 {
3260 super("AlarmManager");
3261 }
Kweku Adams61e03292017-10-19 14:27:12 -07003262
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003263 public void run()
3264 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003265 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3266
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 while (true)
3268 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003269 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003270 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003271
3272 triggerList.clear();
3273
Dianne Hackbornc3527222015-05-13 14:03:20 -07003274 final long nowRTC = System.currentTimeMillis();
3275 final long nowELAPSED = SystemClock.elapsedRealtime();
3276
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003278 // The kernel can give us spurious time change notifications due to
3279 // small adjustments it makes internally; we want to filter those out.
3280 final long lastTimeChangeClockTime;
3281 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003282 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003283 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3284 expectedClockTime = lastTimeChangeClockTime
3285 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003286 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003287 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3288 || nowRTC > (expectedClockTime+1000)) {
3289 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003290 // let's do it!
3291 if (DEBUG_BATCH) {
3292 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3293 }
3294 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003295 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003296 rebatchAllAlarms();
3297 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003298 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003299 synchronized (mLock) {
3300 mNumTimeChanged++;
3301 mLastTimeChangeClockTime = nowRTC;
3302 mLastTimeChangeRealtime = nowELAPSED;
3303 }
3304 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3305 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003306 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003307 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3308 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003309 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3310
3311 // The world has changed on us, so we need to re-evaluate alarms
3312 // regardless of whether the kernel has told us one went off.
3313 result |= IS_WAKEUP_MASK;
3314 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003315 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003316
Dianne Hackbornc3527222015-05-13 14:03:20 -07003317 if (result != TIME_CHANGED_MASK) {
3318 // If this was anything besides just a time change, then figure what if
3319 // anything to do about alarms.
3320 synchronized (mLock) {
3321 if (localLOGV) Slog.v(
3322 TAG, "Checking for alarms... rtc=" + nowRTC
3323 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003324
Dianne Hackbornc3527222015-05-13 14:03:20 -07003325 if (WAKEUP_STATS) {
3326 if ((result & IS_WAKEUP_MASK) != 0) {
3327 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3328 int n = 0;
3329 for (WakeupEvent event : mRecentWakeups) {
3330 if (event.when > newEarliest) break;
3331 n++; // number of now-stale entries at the list head
3332 }
3333 for (int i = 0; i < n; i++) {
3334 mRecentWakeups.remove();
3335 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003336
Dianne Hackbornc3527222015-05-13 14:03:20 -07003337 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003338 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003339 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003340
3341 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3342 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3343 // if there are no wakeup alarms and the screen is off, we can
3344 // delay what we have so far until the future.
3345 if (mPendingNonWakeupAlarms.size() == 0) {
3346 mStartCurrentDelayTime = nowELAPSED;
3347 mNextNonWakeupDeliveryTime = nowELAPSED
3348 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3349 }
3350 mPendingNonWakeupAlarms.addAll(triggerList);
3351 mNumDelayedAlarms += triggerList.size();
3352 rescheduleKernelAlarmsLocked();
3353 updateNextAlarmClockLocked();
3354 } else {
3355 // now deliver the alarm intents; if there are pending non-wakeup
3356 // alarms, we need to merge them in to the list. note we don't
3357 // just deliver them first because we generally want non-wakeup
3358 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003359 if (mPendingNonWakeupAlarms.size() > 0) {
3360 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3361 triggerList.addAll(mPendingNonWakeupAlarms);
3362 Collections.sort(triggerList, mAlarmDispatchComparator);
3363 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3364 mTotalDelayTime += thisDelayTime;
3365 if (mMaxDelayTime < thisDelayTime) {
3366 mMaxDelayTime = thisDelayTime;
3367 }
3368 mPendingNonWakeupAlarms.clear();
3369 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003370 boolean needRebatch = false;
3371 final HashSet<String> triggerPackages = new HashSet<>();
3372 for (int i = triggerList.size() - 1; i >= 0; i--) {
3373 triggerPackages.add(triggerList.get(i).sourcePackage);
3374 }
3375 outer:
3376 for (int i = 0; i < mAlarmBatches.size(); i++) {
3377 final Batch batch = mAlarmBatches.get(i);
3378 for (int j = 0; j < batch.size(); j++) {
3379 if (triggerPackages.contains(batch.get(j))) {
3380 needRebatch = true;
3381 break outer;
3382 }
3383 }
3384 }
3385 if (needRebatch) {
3386 rebatchAllAlarmsLocked(false);
3387 } else {
3388 rescheduleKernelAlarmsLocked();
3389 updateNextAlarmClockLocked();
3390 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003391 deliverAlarmsLocked(triggerList, nowELAPSED);
3392 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003393 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003394
3395 } else {
3396 // Just in case -- even though no wakeup flag was set, make sure
3397 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003398 synchronized (mLock) {
3399 rescheduleKernelAlarmsLocked();
3400 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003401 }
3402 }
3403 }
3404 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003405
David Christieebe51fc2013-07-26 13:23:29 -07003406 /**
3407 * Attribute blame for a WakeLock.
3408 * @param pi PendingIntent to attribute blame to if ws is null.
3409 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003410 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003411 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003412 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003413 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003414 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003415 final boolean unimportant = pi == mTimeTickSender;
3416 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003417 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003418 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003419 } else {
3420 mWakeLock.setHistoryTag(null);
3421 }
3422 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003423 if (ws != null) {
3424 mWakeLock.setWorkSource(ws);
3425 return;
3426 }
3427
Christopher Tate14a7bb02015-10-01 10:24:31 -07003428 final int uid = (knownUid >= 0)
3429 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003430 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003431 if (uid >= 0) {
3432 mWakeLock.setWorkSource(new WorkSource(uid));
3433 return;
3434 }
3435 } catch (Exception e) {
3436 }
3437
3438 // Something went wrong; fall back to attributing the lock to the OS
3439 mWakeLock.setWorkSource(null);
3440 }
3441
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003442 private class AlarmHandler extends Handler {
3443 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003444 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3445 public static final int LISTENER_TIMEOUT = 3;
3446 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003447 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3448 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Kweku Adams61e03292017-10-19 14:27:12 -07003449
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003450 public AlarmHandler() {
3451 }
Kweku Adams61e03292017-10-19 14:27:12 -07003452
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003453 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003454 switch (msg.what) {
3455 case ALARM_EVENT: {
3456 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3457 synchronized (mLock) {
3458 final long nowRTC = System.currentTimeMillis();
3459 final long nowELAPSED = SystemClock.elapsedRealtime();
3460 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3461 updateNextAlarmClockLocked();
3462 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003463
Christopher Tate14a7bb02015-10-01 10:24:31 -07003464 // now trigger the alarms without the lock held
3465 for (int i=0; i<triggerList.size(); i++) {
3466 Alarm alarm = triggerList.get(i);
3467 try {
3468 alarm.operation.send();
3469 } catch (PendingIntent.CanceledException e) {
3470 if (alarm.repeatInterval > 0) {
3471 // This IntentSender is no longer valid, but this
3472 // is a repeating alarm, so toss the hoser.
3473 removeImpl(alarm.operation);
3474 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003475 }
3476 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003477 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003479
3480 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3481 sendNextAlarmClockChanged();
3482 break;
3483
3484 case LISTENER_TIMEOUT:
3485 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3486 break;
3487
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003488 case REPORT_ALARMS_ACTIVE:
3489 if (mLocalDeviceIdleController != null) {
3490 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3491 }
3492 break;
3493
Suprabh Shukla75edab12018-01-29 14:09:06 -08003494 case APP_STANDBY_PAROLE_CHANGED:
3495 synchronized (mLock) {
3496 mAppStandbyParole = (Boolean) msg.obj;
3497 rebatchAllAlarmsLocked(false);
3498 }
3499 break;
3500
3501 case APP_STANDBY_BUCKET_CHANGED:
3502 synchronized (mLock) {
3503 rebatchAllAlarmsLocked(false);
3504 }
3505 break;
3506
Christopher Tate14a7bb02015-10-01 10:24:31 -07003507 default:
3508 // nope, just ignore it
3509 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 }
3511 }
3512 }
Kweku Adams61e03292017-10-19 14:27:12 -07003513
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003514 class ClockReceiver extends BroadcastReceiver {
3515 public ClockReceiver() {
3516 IntentFilter filter = new IntentFilter();
3517 filter.addAction(Intent.ACTION_TIME_TICK);
3518 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003519 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003520 }
Kweku Adams61e03292017-10-19 14:27:12 -07003521
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003522 @Override
3523 public void onReceive(Context context, Intent intent) {
3524 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003525 if (DEBUG_BATCH) {
3526 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3527 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003528 synchronized (mLock) {
3529 mLastTickReceived = System.currentTimeMillis();
3530 }
Christopher Tate385e4982013-07-23 18:22:29 -07003531 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003532 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3533 // Since the kernel does not keep track of DST, we need to
3534 // reset the TZ information at the beginning of each day
3535 // based off of the current Zone gmt offset + userspace tracked
3536 // daylight savings information.
3537 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003538 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003539 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003540 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003541 }
3542 }
Kweku Adams61e03292017-10-19 14:27:12 -07003543
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003544 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003545 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003546 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003547
3548 // Schedule this event for the amount of time that it would take to get to
3549 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003550 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003551
David Christieebe51fc2013-07-26 13:23:29 -07003552 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003553 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003554 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3555 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003556
3557 // Finally, remember when we set the tick alarm
3558 synchronized (mLock) {
3559 mLastTickSet = currentTime;
3560 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003561 }
Christopher Tate385e4982013-07-23 18:22:29 -07003562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003563 public void scheduleDateChangedEvent() {
3564 Calendar calendar = Calendar.getInstance();
3565 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003566 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003567 calendar.set(Calendar.MINUTE, 0);
3568 calendar.set(Calendar.SECOND, 0);
3569 calendar.set(Calendar.MILLISECOND, 0);
3570 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003571
3572 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003573 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3574 AlarmManager.FLAG_STANDALONE, workSource, null,
3575 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003576 }
3577 }
Kweku Adams61e03292017-10-19 14:27:12 -07003578
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003579 class InteractiveStateReceiver extends BroadcastReceiver {
3580 public InteractiveStateReceiver() {
3581 IntentFilter filter = new IntentFilter();
3582 filter.addAction(Intent.ACTION_SCREEN_OFF);
3583 filter.addAction(Intent.ACTION_SCREEN_ON);
3584 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3585 getContext().registerReceiver(this, filter);
3586 }
3587
3588 @Override
3589 public void onReceive(Context context, Intent intent) {
3590 synchronized (mLock) {
3591 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3592 }
3593 }
3594 }
3595
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003596 class UninstallReceiver extends BroadcastReceiver {
3597 public UninstallReceiver() {
3598 IntentFilter filter = new IntentFilter();
3599 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3600 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003601 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003603 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003604 // Register for events related to sdcard installation.
3605 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003606 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003607 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003608 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003609 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003610 }
Kweku Adams61e03292017-10-19 14:27:12 -07003611
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003612 @Override
3613 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003614 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003616 String action = intent.getAction();
3617 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003618 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3619 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3620 for (String packageName : pkgList) {
3621 if (lookForPackageLocked(packageName)) {
3622 setResultCode(Activity.RESULT_OK);
3623 return;
3624 }
3625 }
3626 return;
3627 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003628 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003629 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3630 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3631 if (userHandle >= 0) {
3632 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003633 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3634 final Pair<String, Integer> packageUser =
3635 mLastAlarmDeliveredForPackage.keyAt(i);
3636 if (packageUser.second == userHandle) {
3637 mLastAlarmDeliveredForPackage.removeAt(i);
3638 }
3639 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003640 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003641 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003642 if (uid >= 0) {
3643 mLastAllowWhileIdleDispatch.delete(uid);
3644 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003645 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003646 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3647 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3648 // This package is being updated; don't kill its alarms.
3649 return;
3650 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003651 Uri data = intent.getData();
3652 if (data != null) {
3653 String pkg = data.getSchemeSpecificPart();
3654 if (pkg != null) {
3655 pkgList = new String[]{pkg};
3656 }
3657 }
3658 }
3659 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003660 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3661 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3662 if (ArrayUtils.contains(pkgList, packageUser.first)
3663 && packageUser.second == UserHandle.getUserId(uid)) {
3664 mLastAlarmDeliveredForPackage.removeAt(i);
3665 }
3666 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003667 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003668 if (uid >= 0) {
3669 // package-removed case
3670 removeLocked(uid);
3671 } else {
3672 // external-applications-unavailable etc case
3673 removeLocked(pkg);
3674 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003675 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003676 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3677 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3678 if (uidStats.remove(pkg) != null) {
3679 if (uidStats.size() <= 0) {
3680 mBroadcastStats.removeAt(i);
3681 }
3682 }
3683 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 }
3686 }
3687 }
3688 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003689
3690 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003691 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003692 }
3693
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003694 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003695 synchronized (mLock) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003696 mUseAllowWhileIdleShortTime.delete(uid);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003697 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003698 removeForStoppedLocked(uid);
3699 }
3700 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003701 }
3702
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003703 @Override public void onUidActive(int uid) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003704 synchronized (mLock) {
3705 mUseAllowWhileIdleShortTime.put(uid, true);
3706 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003707 }
3708
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003709 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003710 synchronized (mLock) {
3711 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003712 removeForStoppedLocked(uid);
3713 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003714 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003715 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003716
3717 @Override public void onUidCachedChanged(int uid, boolean cached) {
3718 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003719 };
3720
Suprabh Shukla75edab12018-01-29 14:09:06 -08003721 /**
3722 * Tracking of app assignments to standby buckets
3723 */
3724 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3725 @Override
3726 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
3727 boolean idle, int bucket) {
3728 if (DEBUG_STANDBY) {
3729 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3730 bucket);
3731 }
3732 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3733 mHandler.sendEmptyMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3734 }
3735
3736 @Override
3737 public void onParoleStateChanged(boolean isParoleOn) {
3738 if (DEBUG_STANDBY) {
3739 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3740 }
3741 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3742 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3743 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3744 Boolean.valueOf(isParoleOn)).sendToTarget();
3745 }
3746 };
3747
Makoto Onuki2206af32017-11-21 16:25:35 -08003748 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003749 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003750 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003751 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003752 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003753 }
3754 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003755
3756 @Override
3757 public void unblockAlarmsForUid(int uid) {
3758 synchronized (mLock) {
3759 sendPendingBackgroundAlarmsLocked(uid, null);
3760 }
3761 }
3762
3763 @Override
3764 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3765 synchronized (mLock) {
3766 sendPendingBackgroundAlarmsLocked(uid, packageName);
3767 }
3768 }
3769 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003770
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003771 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003772 String pkg = pi.getCreatorPackage();
3773 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003774 return getStatsLocked(uid, pkg);
3775 }
3776
3777 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003778 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3779 if (uidStats == null) {
3780 uidStats = new ArrayMap<String, BroadcastStats>();
3781 mBroadcastStats.put(uid, uidStats);
3782 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003783 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003785 bs = new BroadcastStats(uid, pkgName);
3786 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 }
3788 return bs;
3789 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003790
Christopher Tate21e9f192017-08-08 13:49:11 -07003791 /**
3792 * Canonical count of (operation.send() - onSendFinished()) and
3793 * listener send/complete/timeout invocations.
3794 * Guarded by the usual lock.
3795 */
3796 @GuardedBy("mLock")
3797 private int mSendCount = 0;
3798 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003799 private int mSendFinishCount = 0;
3800 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003801 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003802 @GuardedBy("mLock")
3803 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003804
Christopher Tate14a7bb02015-10-01 10:24:31 -07003805 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003806
Christopher Tate14a7bb02015-10-01 10:24:31 -07003807 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3808 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003809 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003810 return mInFlight.remove(i);
3811 }
3812 }
3813 mLog.w("No in-flight alarm for " + pi + " " + intent);
3814 return null;
3815 }
3816
3817 private InFlight removeLocked(IBinder listener) {
3818 for (int i = 0; i < mInFlight.size(); i++) {
3819 if (mInFlight.get(i).mListener == listener) {
3820 return mInFlight.remove(i);
3821 }
3822 }
3823 mLog.w("No in-flight alarm for listener " + listener);
3824 return null;
3825 }
3826
3827 private void updateStatsLocked(InFlight inflight) {
3828 final long nowELAPSED = SystemClock.elapsedRealtime();
3829 BroadcastStats bs = inflight.mBroadcastStats;
3830 bs.nesting--;
3831 if (bs.nesting <= 0) {
3832 bs.nesting = 0;
3833 bs.aggregateTime += nowELAPSED - bs.startTime;
3834 }
3835 FilterStats fs = inflight.mFilterStats;
3836 fs.nesting--;
3837 if (fs.nesting <= 0) {
3838 fs.nesting = 0;
3839 fs.aggregateTime += nowELAPSED - fs.startTime;
3840 }
3841 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003842 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3843 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003844 }
3845 }
3846
3847 private void updateTrackingLocked(InFlight inflight) {
3848 if (inflight != null) {
3849 updateStatsLocked(inflight);
3850 }
3851 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003852 if (DEBUG_WAKELOCK) {
3853 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3854 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003855 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003856 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003857 mWakeLock.release();
3858 if (mInFlight.size() > 0) {
3859 mLog.w("Finished all dispatches with " + mInFlight.size()
3860 + " remaining inflights");
3861 for (int i=0; i<mInFlight.size(); i++) {
3862 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3863 }
3864 mInFlight.clear();
3865 }
3866 } else {
3867 // the next of our alarms is now in flight. reattribute the wakelock.
3868 if (mInFlight.size() > 0) {
3869 InFlight inFlight = mInFlight.get(0);
3870 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3871 inFlight.mAlarmType, inFlight.mTag, -1, false);
3872 } else {
3873 // should never happen
3874 mLog.w("Alarm wakelock still held but sent queue empty");
3875 mWakeLock.setWorkSource(null);
3876 }
3877 }
3878 }
3879
3880 /**
3881 * Callback that arrives when a direct-call alarm reports that delivery has finished
3882 */
3883 @Override
3884 public void alarmComplete(IBinder who) {
3885 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003886 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003887 + " pid=" + Binder.getCallingPid());
3888 return;
3889 }
3890
3891 final long ident = Binder.clearCallingIdentity();
3892 try {
3893 synchronized (mLock) {
3894 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3895 InFlight inflight = removeLocked(who);
3896 if (inflight != null) {
3897 if (DEBUG_LISTENER_CALLBACK) {
3898 Slog.i(TAG, "alarmComplete() from " + who);
3899 }
3900 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003901 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003902 } else {
3903 // Delivery timed out, and the timeout handling already took care of
3904 // updating our tracking here, so we needn't do anything further.
3905 if (DEBUG_LISTENER_CALLBACK) {
3906 Slog.i(TAG, "Late alarmComplete() from " + who);
3907 }
3908 }
3909 }
3910 } finally {
3911 Binder.restoreCallingIdentity(ident);
3912 }
3913 }
3914
3915 /**
3916 * Callback that arrives when a PendingIntent alarm has finished delivery
3917 */
3918 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003919 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3920 String resultData, Bundle resultExtras) {
3921 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003922 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003923 updateTrackingLocked(removeLocked(pi, intent));
3924 }
3925 }
3926
3927 /**
3928 * Timeout of a direct-call alarm delivery
3929 */
3930 public void alarmTimedOut(IBinder who) {
3931 synchronized (mLock) {
3932 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003933 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003934 // TODO: implement ANR policy for the target
3935 if (DEBUG_LISTENER_CALLBACK) {
3936 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003937 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003938 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003939 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003940 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003941 if (DEBUG_LISTENER_CALLBACK) {
3942 Slog.i(TAG, "Spurious timeout of listener " + who);
3943 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003944 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003946 }
3947 }
3948
3949 /**
3950 * Deliver an alarm and set up the post-delivery handling appropriately
3951 */
3952 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3953 if (alarm.operation != null) {
3954 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003955 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08003956
3957 if (alarm.priorityClass.priority == PRIO_TICK) {
3958 mLastTickIssued = nowELAPSED;
3959 }
3960
Christopher Tate14a7bb02015-10-01 10:24:31 -07003961 try {
3962 alarm.operation.send(getContext(), 0,
3963 mBackgroundIntent.putExtra(
3964 Intent.EXTRA_ALARM_COUNT, alarm.count),
3965 mDeliveryTracker, mHandler, null,
3966 allowWhileIdle ? mIdleOptions : null);
3967 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08003968 if (alarm.operation == mTimeTickSender) {
3969 Slog.wtf(TAG, "mTimeTickSender canceled");
3970 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003971 if (alarm.repeatInterval > 0) {
3972 // This IntentSender is no longer valid, but this
3973 // is a repeating alarm, so toss it
3974 removeImpl(alarm.operation);
3975 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003976 // No actual delivery was possible, so the delivery tracker's
3977 // 'finished' callback won't be invoked. We also don't need
3978 // to do any wakelock or stats tracking, so we have nothing
3979 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003980 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003981 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003982 }
3983 } else {
3984 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003985 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003986 try {
3987 if (DEBUG_LISTENER_CALLBACK) {
3988 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3989 + " listener=" + alarm.listener.asBinder());
3990 }
3991 alarm.listener.doAlarm(this);
3992 mHandler.sendMessageDelayed(
3993 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3994 alarm.listener.asBinder()),
3995 mConstants.LISTENER_TIMEOUT);
3996 } catch (Exception e) {
3997 if (DEBUG_LISTENER_CALLBACK) {
3998 Slog.i(TAG, "Alarm undeliverable to listener "
3999 + alarm.listener.asBinder(), e);
4000 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004001 // As in the PendingIntent.CanceledException case, delivery of the
4002 // alarm was not possible, so we have no wakelock or timeout or
4003 // stats management to do. It threw before we posted the delayed
4004 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004005 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004006 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004007 }
4008 }
4009
4010 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004011 if (DEBUG_WAKELOCK) {
4012 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4013 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004014 if (mBroadcastRefCount == 0) {
4015 setWakelockWorkSource(alarm.operation, alarm.workSource,
4016 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4017 true);
4018 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004019 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004020 }
4021 final InFlight inflight = new InFlight(AlarmManagerService.this,
4022 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4023 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4024 mInFlight.add(inflight);
4025 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004026 if (allowWhileIdle) {
4027 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004028 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
4029 if (mForceAppStandbyTracker.isInForeground(alarm.creatorUid)) {
4030 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4031 } else {
4032 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4033 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004034 if (RECORD_DEVICE_IDLE_ALARMS) {
4035 IdleDispatchEntry ent = new IdleDispatchEntry();
4036 ent.uid = alarm.uid;
4037 ent.pkg = alarm.packageName;
4038 ent.tag = alarm.statsTag;
4039 ent.op = "DELIVER";
4040 ent.elapsedRealtime = nowELAPSED;
4041 mAllowWhileIdleDispatches.add(ent);
4042 }
4043 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08004044 if (!UserHandle.isCore(alarm.creatorUid)) {
4045 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4046 UserHandle.getUserId(alarm.creatorUid));
4047 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4048 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004049
4050 final BroadcastStats bs = inflight.mBroadcastStats;
4051 bs.count++;
4052 if (bs.nesting == 0) {
4053 bs.nesting = 1;
4054 bs.startTime = nowELAPSED;
4055 } else {
4056 bs.nesting++;
4057 }
4058 final FilterStats fs = inflight.mFilterStats;
4059 fs.count++;
4060 if (fs.nesting == 0) {
4061 fs.nesting = 1;
4062 fs.startTime = nowELAPSED;
4063 } else {
4064 fs.nesting++;
4065 }
4066 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4067 || alarm.type == RTC_WAKEUP) {
4068 bs.numWakeup++;
4069 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004070 ActivityManager.noteWakeupAlarm(
4071 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4072 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004073 }
4074 }
4075 }
4076}