blob: d17ca7f9e77a7803c45a4605e7ec62287b5d3d5f [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey9911a282018-02-14 22:29:11 -070019import static android.app.AlarmManager.ELAPSED_REALTIME;
20import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
21import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
22import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
23import static android.app.AlarmManager.RTC;
24import static android.app.AlarmManager.RTC_WAKEUP;
25
Suprabh Shukla75edab12018-01-29 14:09:06 -080026import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080027import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020028import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070029import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070030import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070031import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070032import android.app.IAlarmCompleteListener;
33import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070035import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080037import android.app.usage.UsageStatsManager;
38import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070040import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070044import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070046import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
50import android.os.Binder;
51import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070052import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080054import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070056import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070058import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070059import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.SystemClock;
61import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080062import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070063import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070064import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020065import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080066import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020068import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080069import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080070import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080071import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070072import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020073import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070074import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080075import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080076import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080077import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020078import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070079import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070080import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070081import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Jeff Sharkey9911a282018-02-14 22:29:11 -070083import com.android.internal.annotations.GuardedBy;
84import com.android.internal.annotations.VisibleForTesting;
85import com.android.internal.util.ArrayUtils;
86import com.android.internal.util.DumpUtils;
87import com.android.internal.util.LocalLog;
88import com.android.server.AppStateTracker.Listener;
89
Christopher Tate4cb338d2013-07-26 13:11:31 -070090import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.io.FileDescriptor;
92import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070093import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -070094import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080096import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.util.Calendar;
98import java.util.Collections;
99import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500100import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700101import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700102import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200103import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700104import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400106import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800107import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Makoto Onuki2206af32017-11-21 16:25:35 -0800109/**
110 * Alarm manager implementaion.
111 *
112 * Unit test:
113 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
114 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700116 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
117 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700119 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 static final int TIME_CHANGED_MASK = 1 << 16;
121 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800122
Christopher Tatee0a22b32013-07-11 14:43:13 -0700123 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800125
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 static final boolean localLOGV = false;
128 static final boolean DEBUG_BATCH = localLOGV || false;
129 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200130 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700131 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800132 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700133 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800134 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700135 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700136 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 static final int ALARM_EVENT = 1;
138 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200139
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700143
Adam Lesinski182f73f2013-12-05 16:48:06 -0800144 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700145
Christopher Tate24cd46f2016-02-02 14:28:01 -0800146 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
147 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700148 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
149 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200150
Adam Lesinski182f73f2013-12-05 16:48:06 -0800151 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800152
Christopher Tate14a7bb02015-10-01 10:24:31 -0700153 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800154 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800155 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700156
Adam Lesinski182f73f2013-12-05 16:48:06 -0800157 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800158
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700159 // List of alarms per uid deferred due to user applied background restrictions on the source app
160 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800161 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800162 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700163 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700164 private long mLastWakeupSet;
165 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800166 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800167 private long mLastTickSet;
168 private long mLastTickIssued; // elapsed
169 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800170 private long mLastTickAdded;
171 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 int mBroadcastRefCount = 0;
173 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700174 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700175 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
176 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800177 final AlarmHandler mHandler = new AlarmHandler();
178 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700179 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700181 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800182 PendingIntent mTimeTickSender;
183 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700184 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700185 boolean mInteractive = true;
186 long mNonInteractiveStartTime;
187 long mNonInteractiveTime;
188 long mLastAlarmDeliveryTime;
189 long mStartCurrentDelayTime;
190 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700191 long mLastTimeChangeClockTime;
192 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700193 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800194
Christopher Tatebb9cce52017-04-18 14:19:43 -0700195 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
196
197 /**
198 * This permission must be defined by the canonical System UI package,
199 * with protection level "signature".
200 */
201 private static final String SYSTEM_UI_SELF_PERMISSION =
202 "android.permission.systemui.IDENTITY";
203
204 /**
205 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
206 */
207 int mSystemUiUid;
208
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700209 /**
210 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700211 * used to determine the earliest we can dispatch the next such alarm. Times are in the
212 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700213 */
214 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
215
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800216 /**
217 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
218 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
219 */
220 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
221
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700222 final static class IdleDispatchEntry {
223 int uid;
224 String pkg;
225 String tag;
226 String op;
227 long elapsedRealtime;
228 long argRealtime;
229 }
230 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
231
Suprabh Shukla75edab12018-01-29 14:09:06 -0800232 interface Stats {
233 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800234 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800235 }
236
237 private final StatLogger mStatLogger = new StatLogger(new String[] {
238 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800239 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800240 });
241
Dianne Hackborna750a632015-06-16 17:18:23 -0700242 /**
243 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
244 */
245 Bundle mIdleOptions;
246
Jose Lima235510e2014-08-13 12:50:01 -0700247 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
248 new SparseArray<>();
249 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
250 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200251 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
252 new SparseBooleanArray();
253 private boolean mNextAlarmClockMayChange;
254
255 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700256 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
257 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200258
Makoto Onukie4918212018-02-06 11:30:15 -0800259 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800260 private boolean mAppStandbyParole;
261 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800262
Dianne Hackborna750a632015-06-16 17:18:23 -0700263 /**
264 * All times are in milliseconds. These constants are kept synchronized with the system
265 * global Settings. Any access to this class or its fields should be done while
266 * holding the AlarmManagerService.mLock lock.
267 */
268 private final class Constants extends ContentObserver {
269 // Key names stored in the settings value.
270 private static final String KEY_MIN_FUTURITY = "min_futurity";
271 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800272 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700273 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
274 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
275 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
276 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700277 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700278
Suprabh Shukla75edab12018-01-29 14:09:06 -0800279 // Keys for specifying throttling delay based on app standby bucketing
280 private final String[] KEYS_APP_STANDBY_DELAY = {
281 "standby_active_delay",
282 "standby_working_delay",
283 "standby_frequent_delay",
284 "standby_rare_delay",
285 "standby_never_delay",
286 };
287
Dianne Hackborna750a632015-06-16 17:18:23 -0700288 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
289 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800290 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700291 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700292 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700293 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700294 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800295 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
296 0, // Active
297 6 * 60_000, // Working
298 30 * 60_000, // Frequent
299 2 * 60 * 60_000, // Rare
300 10 * 24 * 60 * 60_000 // Never
301 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700302
Dianne Hackborna750a632015-06-16 17:18:23 -0700303 // Minimum futurity of a new alarm
304 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
305
306 // Minimum alarm recurrence interval
307 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
308
Christopher Tate22e919d2018-02-16 16:16:50 -0800309 // Maximum alarm recurrence interval
310 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
311
Dianne Hackborna750a632015-06-16 17:18:23 -0700312 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
313 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
314
315 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
316 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
317
318 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
319 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
320 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
321
Christopher Tate14a7bb02015-10-01 10:24:31 -0700322 // Direct alarm listener callback timeout
323 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
324
Suprabh Shukla75edab12018-01-29 14:09:06 -0800325 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
326
Dianne Hackborna750a632015-06-16 17:18:23 -0700327 private ContentResolver mResolver;
328 private final KeyValueListParser mParser = new KeyValueListParser(',');
329 private long mLastAllowWhileIdleWhitelistDuration = -1;
330
331 public Constants(Handler handler) {
332 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700333 updateAllowWhileIdleWhitelistDurationLocked();
334 }
335
336 public void start(ContentResolver resolver) {
337 mResolver = resolver;
338 mResolver.registerContentObserver(Settings.Global.getUriFor(
339 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
340 updateConstants();
341 }
342
Dianne Hackborna750a632015-06-16 17:18:23 -0700343 public void updateAllowWhileIdleWhitelistDurationLocked() {
344 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
345 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
346 BroadcastOptions opts = BroadcastOptions.makeBasic();
347 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
348 mIdleOptions = opts.toBundle();
349 }
350 }
351
352 @Override
353 public void onChange(boolean selfChange, Uri uri) {
354 updateConstants();
355 }
356
357 private void updateConstants() {
358 synchronized (mLock) {
359 try {
360 mParser.setString(Settings.Global.getString(mResolver,
361 Settings.Global.ALARM_MANAGER_CONSTANTS));
362 } catch (IllegalArgumentException e) {
363 // Failed to parse the settings string, log this and move on
364 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800365 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700366 }
367
368 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
369 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800370 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700371 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
372 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
373 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
374 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
375 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
376 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
377 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700378 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
379 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800380 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
381 DEFAULT_APP_STANDBY_DELAYS[0]);
382 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
383 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
384 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
385 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700386 updateAllowWhileIdleWhitelistDurationLocked();
387 }
388 }
389
390 void dump(PrintWriter pw) {
391 pw.println(" Settings:");
392
393 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
394 TimeUtils.formatDuration(MIN_FUTURITY, pw);
395 pw.println();
396
397 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
398 TimeUtils.formatDuration(MIN_INTERVAL, pw);
399 pw.println();
400
Christopher Tate22e919d2018-02-16 16:16:50 -0800401 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
402 TimeUtils.formatDuration(MAX_INTERVAL, pw);
403 pw.println();
404
Christopher Tate14a7bb02015-10-01 10:24:31 -0700405 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
406 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
407 pw.println();
408
Dianne Hackborna750a632015-06-16 17:18:23 -0700409 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
410 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
411 pw.println();
412
413 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
414 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
415 pw.println();
416
417 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
418 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
419 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800420
421 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
422 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
423 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
424 pw.println();
425 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700426 }
Kweku Adams61e03292017-10-19 14:27:12 -0700427
428 void dumpProto(ProtoOutputStream proto, long fieldId) {
429 final long token = proto.start(fieldId);
430
431 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
432 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800433 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700434 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
435 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
436 ALLOW_WHILE_IDLE_SHORT_TIME);
437 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
438 ALLOW_WHILE_IDLE_LONG_TIME);
439 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
440 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
441
442 proto.end(token);
443 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700444 }
445
446 final Constants mConstants;
447
Christopher Tate1590f1e2014-10-02 17:27:57 -0700448 // Alarm delivery ordering bookkeeping
449 static final int PRIO_TICK = 0;
450 static final int PRIO_WAKEUP = 1;
451 static final int PRIO_NORMAL = 2;
452
Dianne Hackborna750a632015-06-16 17:18:23 -0700453 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700454 int seq;
455 int priority;
456
457 PriorityClass() {
458 seq = mCurrentSeq - 1;
459 priority = PRIO_NORMAL;
460 }
461 }
462
Dianne Hackborna750a632015-06-16 17:18:23 -0700463 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700464 int mCurrentSeq = 0;
465
Dianne Hackborna750a632015-06-16 17:18:23 -0700466 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700467 public long when;
468 public int uid;
469 public String action;
470
471 public WakeupEvent(long theTime, int theUid, String theAction) {
472 when = theTime;
473 uid = theUid;
474 action = theAction;
475 }
476 }
477
Adam Lesinski182f73f2013-12-05 16:48:06 -0800478 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
479 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700480
Adrian Roosc42a1e12014-07-07 23:35:53 +0200481 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 long start; // These endpoints are always in ELAPSED
483 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700484 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485
486 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
487
488 Batch() {
489 start = 0;
490 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700491 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700492 }
493
494 Batch(Alarm seed) {
495 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800496 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700497 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800499 if (seed.operation == mTimeTickSender) {
500 mLastTickAdded = System.currentTimeMillis();
501 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700502 }
503
504 int size() {
505 return alarms.size();
506 }
507
508 Alarm get(int index) {
509 return alarms.get(index);
510 }
511
512 boolean canHold(long whenElapsed, long maxWhen) {
513 return (end >= whenElapsed) && (start <= maxWhen);
514 }
515
516 boolean add(Alarm alarm) {
517 boolean newStart = false;
518 // narrows the batch if necessary; presumes that canHold(alarm) is true
519 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
520 if (index < 0) {
521 index = 0 - index - 1;
522 }
523 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800524 if (alarm.operation == mTimeTickSender) {
525 mLastTickAdded = System.currentTimeMillis();
526 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700527 if (DEBUG_BATCH) {
528 Slog.v(TAG, "Adding " + alarm + " to " + this);
529 }
530 if (alarm.whenElapsed > start) {
531 start = alarm.whenElapsed;
532 newStart = true;
533 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700534 if (alarm.maxWhenElapsed < end) {
535 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700536 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700537 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700538
539 if (DEBUG_BATCH) {
540 Slog.v(TAG, " => now " + this);
541 }
542 return newStart;
543 }
544
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800545 boolean remove(Alarm alarm) {
546 return remove(a -> (a == alarm));
547 }
548
Christopher Tate1d99c392017-12-07 16:54:04 -0800549 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 boolean didRemove = false;
551 long newStart = 0; // recalculate endpoints as we go
552 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700553 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700554 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800556 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557 alarms.remove(i);
558 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200559 if (alarm.alarmClock != null) {
560 mNextAlarmClockMayChange = true;
561 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800562 if (alarm.operation == mTimeTickSender) {
563 mLastTickRemoved = System.currentTimeMillis();
564 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 } else {
566 if (alarm.whenElapsed > newStart) {
567 newStart = alarm.whenElapsed;
568 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700569 if (alarm.maxWhenElapsed < newEnd) {
570 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700571 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700572 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 i++;
574 }
575 }
576 if (didRemove) {
577 // commit the new batch bounds
578 start = newStart;
579 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700580 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700581 }
582 return didRemove;
583 }
584
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 boolean hasPackage(final String packageName) {
586 final int N = alarms.size();
587 for (int i = 0; i < N; i++) {
588 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700589 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700590 return true;
591 }
592 }
593 return false;
594 }
595
596 boolean hasWakeups() {
597 final int N = alarms.size();
598 for (int i = 0; i < N; i++) {
599 Alarm a = alarms.get(i);
600 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
601 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
602 return true;
603 }
604 }
605 return false;
606 }
607
608 @Override
609 public String toString() {
610 StringBuilder b = new StringBuilder(40);
611 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
612 b.append(" num="); b.append(size());
613 b.append(" start="); b.append(start);
614 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700615 if (flags != 0) {
616 b.append(" flgs=0x");
617 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700618 }
619 b.append('}');
620 return b.toString();
621 }
Kweku Adams61e03292017-10-19 14:27:12 -0700622
623 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
624 long nowRTC) {
625 final long token = proto.start(fieldId);
626
627 proto.write(BatchProto.START_REALTIME, start);
628 proto.write(BatchProto.END_REALTIME, end);
629 proto.write(BatchProto.FLAGS, flags);
630 for (Alarm a : alarms) {
631 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
632 }
633
634 proto.end(token);
635 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700636 }
637
638 static class BatchTimeOrder implements Comparator<Batch> {
639 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800640 long when1 = b1.start;
641 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800642 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700643 return 1;
644 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800645 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700646 return -1;
647 }
648 return 0;
649 }
650 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800651
652 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
653 @Override
654 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700655 // priority class trumps everything. TICK < WAKEUP < NORMAL
656 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
657 return -1;
658 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
659 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800660 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700661
662 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800663 if (lhs.whenElapsed < rhs.whenElapsed) {
664 return -1;
665 } else if (lhs.whenElapsed > rhs.whenElapsed) {
666 return 1;
667 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700668
669 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800670 return 0;
671 }
672 };
673
Christopher Tate1590f1e2014-10-02 17:27:57 -0700674 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
675 final int N = alarms.size();
676 for (int i = 0; i < N; i++) {
677 Alarm a = alarms.get(i);
678
679 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700680 if (a.operation != null
681 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700682 alarmPrio = PRIO_TICK;
683 } else if (a.wakeup) {
684 alarmPrio = PRIO_WAKEUP;
685 } else {
686 alarmPrio = PRIO_NORMAL;
687 }
688
689 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800690 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700691 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700692 if (packagePrio == null) {
693 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700694 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700695 }
696 a.priorityClass = packagePrio;
697
698 if (packagePrio.seq != mCurrentSeq) {
699 // first alarm we've seen in the current delivery generation from this package
700 packagePrio.priority = alarmPrio;
701 packagePrio.seq = mCurrentSeq;
702 } else {
703 // Multiple alarms from this package being delivered in this generation;
704 // bump the package's delivery class if it's warranted.
705 // TICK < WAKEUP < NORMAL
706 if (alarmPrio < packagePrio.priority) {
707 packagePrio.priority = alarmPrio;
708 }
709 }
710 }
711 }
712
Christopher Tatee0a22b32013-07-11 14:43:13 -0700713 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800714 static final long MIN_FUZZABLE_INTERVAL = 10000;
715 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700716 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
717
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700718 // 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 -0700719 // to run during this time are placed in mPendingWhileIdleAlarms
720 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700721 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700722 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700723
Jeff Brownb880d882014-02-10 19:47:07 -0800724 public AlarmManagerService(Context context) {
725 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700726 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800727
Christopher Tate1d99c392017-12-07 16:54:04 -0800728 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800729 }
730
Christopher Tatee0a22b32013-07-11 14:43:13 -0700731 static long convertToElapsed(long when, int type) {
732 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
733 if (isRtc) {
734 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
735 }
736 return when;
737 }
738
739 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
740 // calculate the end of our nominal delivery window for the alarm.
741 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
742 // Current heuristic: batchable window is 75% of either the recurrence interval
743 // [for a periodic alarm] or of the time from now to the desired delivery time,
744 // with a minimum delay/interval of 10 seconds, under which we will simply not
745 // defer the alarm.
746 long futurity = (interval == 0)
747 ? (triggerAtTime - now)
748 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700749 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700750 futurity = 0;
751 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800752 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700753 }
754
755 // returns true if the batch was added at the head
756 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
757 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
758 if (index < 0) {
759 index = 0 - index - 1;
760 }
761 list.add(index, newBatch);
762 return (index == 0);
763 }
764
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800765 private void insertAndBatchAlarmLocked(Alarm alarm) {
766 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
767 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
768
769 if (whichBatch < 0) {
770 addBatchLocked(mAlarmBatches, new Batch(alarm));
771 } else {
772 final Batch batch = mAlarmBatches.get(whichBatch);
773 if (batch.add(alarm)) {
774 // The start time of this batch advanced, so batch ordering may
775 // have just been broken. Move it to where it now belongs.
776 mAlarmBatches.remove(whichBatch);
777 addBatchLocked(mAlarmBatches, batch);
778 }
779 }
780 }
781
Christopher Tate385e4982013-07-23 18:22:29 -0700782 // Return the index of the matching batch, or -1 if none found.
783 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700784 final int N = mAlarmBatches.size();
785 for (int i = 0; i < N; i++) {
786 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700787 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700788 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700789 }
790 }
Christopher Tate385e4982013-07-23 18:22:29 -0700791 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700792 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800793 /** @return total count of the alarms in a set of alarm batches. */
794 static int getAlarmCount(ArrayList<Batch> batches) {
795 int ret = 0;
796
797 final int size = batches.size();
798 for (int i = 0; i < size; i++) {
799 ret += batches.get(i).size();
800 }
801 return ret;
802 }
803
804 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
805 if (alarms.size() == 0) {
806 return false;
807 }
808 final int batchSize = alarms.size();
809 for (int j = 0; j < batchSize; j++) {
810 if (alarms.get(j).operation == mTimeTickSender) {
811 return true;
812 }
813 }
814 return false;
815 }
816
817 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
818 final int numBatches = batches.size();
819 for (int i = 0; i < numBatches; i++) {
820 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
821 return true;
822 }
823 }
824 return false;
825 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700826
827 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
828 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700829 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700830 rebatchAllAlarmsLocked(true);
831 }
832 }
833
834 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800835 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800836 final int oldCount =
837 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
838 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
839 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
840
Christopher Tate4cb338d2013-07-26 13:11:31 -0700841 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
842 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700843 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700844 final long nowElapsed = SystemClock.elapsedRealtime();
845 final int oldBatches = oldSet.size();
846 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
847 Batch batch = oldSet.get(batchNum);
848 final int N = batch.size();
849 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700850 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700851 }
852 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700853 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
854 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
855 + " to " + mPendingIdleUntil);
856 if (mPendingIdleUntil == null) {
857 // Somehow we lost this... we need to restore all of the pending alarms.
858 restorePendingWhileIdleAlarmsLocked();
859 }
860 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800861 final int newCount =
862 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
863 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
864 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
865
866 if (oldCount != newCount) {
867 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
868 }
869 if (oldHasTick != newHasTick) {
870 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
871 }
872
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700873 rescheduleKernelAlarmsLocked();
874 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800875 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700876 }
877
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800878 /**
879 * Re-orders the alarm batches based on newly evaluated send times based on the current
880 * app-standby buckets
881 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
882 * null indicates all
883 * @return True if there was any reordering done to the current list.
884 */
885 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
886 final long start = mStatLogger.getTime();
887 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
888
889 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
890 final Batch batch = mAlarmBatches.get(batchIndex);
891 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
892 final Alarm alarm = batch.get(alarmIndex);
893 final Pair<String, Integer> packageUser =
894 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
895 if (targetPackages != null && !targetPackages.contains(packageUser)) {
896 continue;
897 }
898 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
899 batch.remove(alarm);
900 rescheduledAlarms.add(alarm);
901 }
902 }
903 if (batch.size() == 0) {
904 mAlarmBatches.remove(batchIndex);
905 }
906 }
907 for (int i = 0; i < rescheduledAlarms.size(); i++) {
908 final Alarm a = rescheduledAlarms.get(i);
909 insertAndBatchAlarmLocked(a);
910 }
911
912 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
913 return rescheduledAlarms.size() > 0;
914 }
915
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700916 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
917 a.when = a.origWhen;
918 long whenElapsed = convertToElapsed(a.when, a.type);
919 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700920 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700921 // Exact
922 maxElapsed = whenElapsed;
923 } else {
924 // Not exact. Preserve any explicit window, otherwise recalculate
925 // the window based on the alarm's new futurity. Note that this
926 // reflects a policy of preferring timely to deferred delivery.
927 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800928 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700929 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
930 }
931 a.whenElapsed = whenElapsed;
932 a.maxWhenElapsed = maxElapsed;
933 setImplLocked(a, true, doValidate);
934 }
935
Christopher Tate22e919d2018-02-16 16:16:50 -0800936 static long clampPositive(long val) {
937 return (val >= 0) ? val : Long.MAX_VALUE;
938 }
939
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700940 /**
941 * Sends alarms that were blocked due to user applied background restrictions - either because
942 * the user lifted those or the uid came to foreground.
943 *
944 * @param uid uid to filter on
945 * @param packageName package to filter on, or null for all packages in uid
946 */
947 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
948 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
949 if (alarmsForUid == null || alarmsForUid.size() == 0) {
950 return;
951 }
952 final ArrayList<Alarm> alarmsToDeliver;
953 if (packageName != null) {
954 if (DEBUG_BG_LIMIT) {
955 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
956 }
957 alarmsToDeliver = new ArrayList<>();
958 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
959 final Alarm a = alarmsForUid.get(i);
960 if (a.matches(packageName)) {
961 alarmsToDeliver.add(alarmsForUid.remove(i));
962 }
963 }
964 if (alarmsForUid.size() == 0) {
965 mPendingBackgroundAlarms.remove(uid);
966 }
967 } else {
968 if (DEBUG_BG_LIMIT) {
969 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
970 }
971 alarmsToDeliver = alarmsForUid;
972 mPendingBackgroundAlarms.remove(uid);
973 }
974 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
975 }
976
Makoto Onuki2206af32017-11-21 16:25:35 -0800977 /**
978 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
979 * restricted.
980 *
981 * This is only called when the global "force all apps-standby" flag changes or when the
982 * power save whitelist changes, so it's okay to be slow.
983 */
984 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700985 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800986
987 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
988 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
989
990 if (alarmsToDeliver.size() > 0) {
991 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
992 }
993 }
994
995 @VisibleForTesting
996 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
997 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
998 Predicate<Alarm> isBackgroundRestricted) {
999
1000 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1001 final int uid = pendingAlarms.keyAt(uidIndex);
1002 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1003
1004 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1005 final Alarm alarm = alarmsForUid.get(alarmIndex);
1006
1007 if (isBackgroundRestricted.test(alarm)) {
1008 continue;
1009 }
1010
1011 unrestrictedAlarms.add(alarm);
1012 alarmsForUid.remove(alarmIndex);
1013 }
1014
1015 if (alarmsForUid.size() == 0) {
1016 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001017 }
1018 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001019 }
1020
1021 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1022 final int N = alarms.size();
1023 boolean hasWakeup = false;
1024 for (int i = 0; i < N; i++) {
1025 final Alarm alarm = alarms.get(i);
1026 if (alarm.wakeup) {
1027 hasWakeup = true;
1028 }
1029 alarm.count = 1;
1030 // Recurring alarms may have passed several alarm intervals while the
1031 // alarm was kept pending. Send the appropriate trigger count.
1032 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001033 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001034 // Also schedule its next recurrence
1035 final long delta = alarm.count * alarm.repeatInterval;
1036 final long nextElapsed = alarm.whenElapsed + delta;
1037 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1038 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1039 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1040 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1041 // Kernel alarms will be rescheduled as needed in setImplLocked
1042 }
1043 }
1044 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1045 // No need to wakeup for non wakeup alarms
1046 if (mPendingNonWakeupAlarms.size() == 0) {
1047 mStartCurrentDelayTime = nowELAPSED;
1048 mNextNonWakeupDeliveryTime = nowELAPSED
1049 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1050 }
1051 mPendingNonWakeupAlarms.addAll(alarms);
1052 mNumDelayedAlarms += alarms.size();
1053 } else {
1054 if (DEBUG_BG_LIMIT) {
1055 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1056 }
1057 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1058 if (mPendingNonWakeupAlarms.size() > 0) {
1059 alarms.addAll(mPendingNonWakeupAlarms);
1060 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1061 mTotalDelayTime += thisDelayTime;
1062 if (mMaxDelayTime < thisDelayTime) {
1063 mMaxDelayTime = thisDelayTime;
1064 }
1065 mPendingNonWakeupAlarms.clear();
1066 }
1067 calculateDeliveryPriorities(alarms);
1068 Collections.sort(alarms, mAlarmDispatchComparator);
1069 deliverAlarmsLocked(alarms, nowELAPSED);
1070 }
1071 }
1072
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001073 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001074 if (RECORD_DEVICE_IDLE_ALARMS) {
1075 IdleDispatchEntry ent = new IdleDispatchEntry();
1076 ent.uid = 0;
1077 ent.pkg = "FINISH IDLE";
1078 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1079 mAllowWhileIdleDispatches.add(ent);
1080 }
1081
Dianne Hackborn35d54032015-04-23 10:30:43 -07001082 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001083 if (mPendingWhileIdleAlarms.size() > 0) {
1084 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1085 mPendingWhileIdleAlarms = new ArrayList<>();
1086 final long nowElapsed = SystemClock.elapsedRealtime();
1087 for (int i=alarms.size() - 1; i >= 0; i--) {
1088 Alarm a = alarms.get(i);
1089 reAddAlarmLocked(a, nowElapsed, false);
1090 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001091 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001092
1093 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001094 rescheduleKernelAlarmsLocked();
1095 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001096
1097 // And send a TIME_TICK right now, since it is important to get the UI updated.
1098 try {
1099 mTimeTickSender.send();
1100 } catch (PendingIntent.CanceledException e) {
1101 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001102 }
1103
Christopher Tate14a7bb02015-10-01 10:24:31 -07001104 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001105 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001106 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001107 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001108 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001109 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001110 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001111 final BroadcastStats mBroadcastStats;
1112 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001113 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001114
Christopher Tate14a7bb02015-10-01 10:24:31 -07001115 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1116 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1117 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001118 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001119 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001120 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001121 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001122 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001123 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001124 mBroadcastStats = (pendingIntent != null)
1125 ? service.getStatsLocked(pendingIntent)
1126 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001127 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001128 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001129 fs = new FilterStats(mBroadcastStats, mTag);
1130 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001131 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001132 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001133 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001134 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001135 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001136
1137 @Override
1138 public String toString() {
1139 return "InFlight{"
1140 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001141 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001142 + ", workSource=" + mWorkSource
1143 + ", uid=" + mUid
1144 + ", tag=" + mTag
1145 + ", broadcastStats=" + mBroadcastStats
1146 + ", filterStats=" + mFilterStats
1147 + ", alarmType=" + mAlarmType
1148 + "}";
1149 }
Kweku Adams61e03292017-10-19 14:27:12 -07001150
1151 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1152 final long token = proto.start(fieldId);
1153
1154 proto.write(InFlightProto.UID, mUid);
1155 proto.write(InFlightProto.TAG, mTag);
1156 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1157 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1158 if (mPendingIntent != null) {
1159 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1160 }
1161 if (mBroadcastStats != null) {
1162 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1163 }
1164 if (mFilterStats != null) {
1165 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1166 }
1167 if (mWorkSource != null) {
1168 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1169 }
1170
1171 proto.end(token);
1172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001174
Adam Lesinski182f73f2013-12-05 16:48:06 -08001175 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001176 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001177 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001178
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001179 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001181 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 int numWakeup;
1183 long startTime;
1184 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001185
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001186 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001187 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001188 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001189 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001190
1191 @Override
1192 public String toString() {
1193 return "FilterStats{"
1194 + "tag=" + mTag
1195 + ", lastTime=" + lastTime
1196 + ", aggregateTime=" + aggregateTime
1197 + ", count=" + count
1198 + ", numWakeup=" + numWakeup
1199 + ", startTime=" + startTime
1200 + ", nesting=" + nesting
1201 + "}";
1202 }
Kweku Adams61e03292017-10-19 14:27:12 -07001203
1204 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1205 final long token = proto.start(fieldId);
1206
1207 proto.write(FilterStatsProto.TAG, mTag);
1208 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1209 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1210 proto.write(FilterStatsProto.COUNT, count);
1211 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1212 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1213 proto.write(FilterStatsProto.NESTING, nesting);
1214
1215 proto.end(token);
1216 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001217 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001218
Adam Lesinski182f73f2013-12-05 16:48:06 -08001219 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001220 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001221 final String mPackageName;
1222
1223 long aggregateTime;
1224 int count;
1225 int numWakeup;
1226 long startTime;
1227 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001228 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001229
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001230 BroadcastStats(int uid, String packageName) {
1231 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001232 mPackageName = packageName;
1233 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001234
1235 @Override
1236 public String toString() {
1237 return "BroadcastStats{"
1238 + "uid=" + mUid
1239 + ", packageName=" + mPackageName
1240 + ", aggregateTime=" + aggregateTime
1241 + ", count=" + count
1242 + ", numWakeup=" + numWakeup
1243 + ", startTime=" + startTime
1244 + ", nesting=" + nesting
1245 + "}";
1246 }
Kweku Adams61e03292017-10-19 14:27:12 -07001247
1248 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1249 final long token = proto.start(fieldId);
1250
1251 proto.write(BroadcastStatsProto.UID, mUid);
1252 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1253 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1254 proto.write(BroadcastStatsProto.COUNT, count);
1255 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1256 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1257 proto.write(BroadcastStatsProto.NESTING, nesting);
1258
1259 proto.end(token);
1260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001262
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001263 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1264 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001265
1266 int mNumDelayedAlarms = 0;
1267 long mTotalDelayTime = 0;
1268 long mMaxDelayTime = 0;
1269
Adam Lesinski182f73f2013-12-05 16:48:06 -08001270 @Override
1271 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001272 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001273 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001274
1275 // We have to set current TimeZone info to kernel
1276 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001277 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001278
Christopher Tate247571462017-04-10 11:45:05 -07001279 // Also sure that we're booting with a halfway sensible current time
1280 if (mNativeData != 0) {
1281 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1282 if (System.currentTimeMillis() < systemBuildTime) {
1283 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1284 + ", advancing to build time " + systemBuildTime);
1285 setKernelTime(mNativeData, systemBuildTime);
1286 }
1287 }
1288
Christopher Tatebb9cce52017-04-18 14:19:43 -07001289 // Determine SysUI's uid
1290 final PackageManager packMan = getContext().getPackageManager();
1291 try {
1292 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1293 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1294 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1295 mSystemUiUid = sysUi.uid;
1296 } else {
1297 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1298 + " defined by non-privileged app " + sysUi.packageName
1299 + " - ignoring");
1300 }
1301 } catch (NameNotFoundException e) {
1302 }
1303
1304 if (mSystemUiUid <= 0) {
1305 Slog.wtf(TAG, "SysUI package not found!");
1306 }
1307
Adam Lesinski182f73f2013-12-05 16:48:06 -08001308 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001309 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001310
Adam Lesinski182f73f2013-12-05 16:48:06 -08001311 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001313 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001314 | Intent.FLAG_RECEIVER_FOREGROUND
1315 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001316 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001317 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001318 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1319 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001320 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001321 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001324 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 mClockReceiver.scheduleTimeTickEvent();
1326 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001327 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001329
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001330 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001331 AlarmThread waitThread = new AlarmThread();
1332 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001336
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001337 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001338 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001339 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1340 | ActivityManager.UID_OBSERVER_ACTIVE,
1341 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001342 } catch (RemoteException e) {
1343 // ignored; both services live in system_server
1344 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001347
1348 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001349 public void onBootPhase(int phase) {
1350 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1351 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001352 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001353 mLocalDeviceIdleController
1354 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001355 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1356 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001357
1358 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1359 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001360 }
1361 }
1362
1363 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 protected void finalize() throws Throwable {
1365 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001366 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 } finally {
1368 super.finalize();
1369 }
1370 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001371
Adam Lesinski182f73f2013-12-05 16:48:06 -08001372 void setTimeZoneImpl(String tz) {
1373 if (TextUtils.isEmpty(tz)) {
1374 return;
David Christieebe51fc2013-07-26 13:23:29 -07001375 }
1376
Adam Lesinski182f73f2013-12-05 16:48:06 -08001377 TimeZone zone = TimeZone.getTimeZone(tz);
1378 // Prevent reentrant calls from stepping on each other when writing
1379 // the time zone property
1380 boolean timeZoneWasChanged = false;
1381 synchronized (this) {
1382 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1383 if (current == null || !current.equals(zone.getID())) {
1384 if (localLOGV) {
1385 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1386 }
1387 timeZoneWasChanged = true;
1388 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1389 }
1390
1391 // Update the kernel timezone information
1392 // Kernel tracks time offsets as 'minutes west of GMT'
1393 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001394 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001395 }
1396
1397 TimeZone.setDefault(null);
1398
1399 if (timeZoneWasChanged) {
1400 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001401 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001402 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001403 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001404 intent.putExtra("time-zone", zone.getID());
1405 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001408
Adam Lesinski182f73f2013-12-05 16:48:06 -08001409 void removeImpl(PendingIntent operation) {
1410 if (operation == null) {
1411 return;
1412 }
1413 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001414 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001415 }
1416 }
1417
1418 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001419 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1420 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1421 int callingUid, String callingPackage) {
1422 // must be *either* PendingIntent or AlarmReceiver, but not both
1423 if ((operation == null && directReceiver == null)
1424 || (operation != null && directReceiver != null)) {
1425 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1426 // NB: previous releases failed silently here, so we are continuing to do the same
1427 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 return;
1429 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001430
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001431 // Sanity check the window length. This will catch people mistakenly
1432 // trying to pass an end-of-window timestamp rather than a duration.
1433 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1434 Slog.w(TAG, "Window length " + windowLength
1435 + "ms suspiciously long; limiting to 1 hour");
1436 windowLength = AlarmManager.INTERVAL_HOUR;
1437 }
1438
Christopher Tate498c6cb2014-11-17 16:09:27 -08001439 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001440 // seconds when the API expects milliseconds, or apps trying shenanigans
1441 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001442 final long minInterval = mConstants.MIN_INTERVAL;
1443 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001444 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001445 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001446 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001447 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001448 } else if (interval > mConstants.MAX_INTERVAL) {
1449 Slog.w(TAG, "Suspiciously long interval " + interval
1450 + " millis; clamping");
1451 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001452 }
1453
Christopher Tatee0a22b32013-07-11 14:43:13 -07001454 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1455 throw new IllegalArgumentException("Invalid alarm type " + type);
1456 }
1457
Christopher Tate5f221e82013-07-30 17:13:15 -07001458 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001459 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001460 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001461 + " pid=" + what);
1462 triggerAtTime = 0;
1463 }
1464
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001465 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001466 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1467 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001468 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001469 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1470
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001471 final long maxElapsed;
1472 if (windowLength == AlarmManager.WINDOW_EXACT) {
1473 maxElapsed = triggerElapsed;
1474 } else if (windowLength < 0) {
1475 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001476 // Fix this window in place, so that as time approaches we don't collapse it.
1477 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001478 } else {
1479 maxElapsed = triggerElapsed + windowLength;
1480 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001483 if (DEBUG_BATCH) {
1484 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001485 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001486 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001487 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001489 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001490 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1491 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494
Christopher Tate3e04b472013-10-21 17:51:31 -07001495 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001496 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1497 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1498 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001499 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001500 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1501 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001502 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001503 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001504 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1505 + " -- package not allowed to start");
1506 return;
1507 }
1508 } catch (RemoteException e) {
1509 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001510 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001511 setImplLocked(a, false, doValidate);
1512 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001513
Suprabh Shukla75edab12018-01-29 14:09:06 -08001514 private long getMinDelayForBucketLocked(int bucket) {
1515 // Return the minimum time that should elapse before an app in the specified bucket
1516 // can receive alarms again
1517 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
1518 return mConstants.APP_STANDBY_MIN_DELAYS[4];
1519 }
1520 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) {
1521 return mConstants.APP_STANDBY_MIN_DELAYS[3];
1522 }
1523 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1524 return mConstants.APP_STANDBY_MIN_DELAYS[2];
1525 }
1526 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1527 return mConstants.APP_STANDBY_MIN_DELAYS[1];
1528 }
1529 else return mConstants.APP_STANDBY_MIN_DELAYS[0];
1530 }
1531
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001532 /**
1533 * Adjusts the alarm delivery time based on the current app standby bucket.
1534 * @param alarm The alarm to adjust
1535 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001536 */
1537 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001538 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001539 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001540 }
1541 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001542 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001543 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001544 alarm.whenElapsed = alarm.expectedWhenElapsed;
1545 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1546 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001547 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001548 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001549 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001550 final long oldWhenElapsed = alarm.whenElapsed;
1551 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1552
Suprabh Shukla75edab12018-01-29 14:09:06 -08001553 final String sourcePackage = alarm.sourcePackage;
1554 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1555 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1556 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1557
1558 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1559 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1560 if (lastElapsed > 0) {
1561 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001562 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001563 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001564 } else {
1565 // app is now eligible to run alarms at the originally requested window.
1566 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001567 alarm.whenElapsed = alarm.expectedWhenElapsed;
1568 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001569 }
1570 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001571 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001572 }
1573
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001574 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1575 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001576 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001577 // The caller has given the time they want this to happen at, however we need
1578 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001579 // bring us out of idle at an earlier time.
1580 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001581 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001582 }
1583 // Add fuzz to make the alarm go off some time before the actual desired time.
1584 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001585 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001586 if (fuzz > 0) {
1587 if (mRandom == null) {
1588 mRandom = new Random();
1589 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001590 final int delta = mRandom.nextInt(fuzz);
1591 a.whenElapsed -= delta;
1592 if (false) {
1593 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1594 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1595 Slog.d(TAG, "Applied fuzz: " + fuzz);
1596 Slog.d(TAG, "Final delta: " + delta);
1597 Slog.d(TAG, "Final when: " + a.whenElapsed);
1598 }
1599 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001600 }
1601
1602 } else if (mPendingIdleUntil != null) {
1603 // We currently have an idle until alarm scheduled; if the new alarm has
1604 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001605 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1606 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1607 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001608 == 0) {
1609 mPendingWhileIdleAlarms.add(a);
1610 return;
1611 }
1612 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001613 if (RECORD_DEVICE_IDLE_ALARMS) {
1614 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1615 IdleDispatchEntry ent = new IdleDispatchEntry();
1616 ent.uid = a.uid;
1617 ent.pkg = a.operation.getCreatorPackage();
1618 ent.tag = a.operation.getTag("");
1619 ent.op = "SET";
1620 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1621 ent.argRealtime = a.whenElapsed;
1622 mAllowWhileIdleDispatches.add(ent);
1623 }
1624 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001625 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001626 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001628 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001629 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001630 }
1631
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001632 boolean needRebatch = false;
1633
1634 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001635 if (RECORD_DEVICE_IDLE_ALARMS) {
1636 if (mPendingIdleUntil == null) {
1637 IdleDispatchEntry ent = new IdleDispatchEntry();
1638 ent.uid = 0;
1639 ent.pkg = "START IDLE";
1640 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1641 mAllowWhileIdleDispatches.add(ent);
1642 }
1643 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001644 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1645 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1646 + " to " + a);
1647 }
1648
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001649 mPendingIdleUntil = a;
1650 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001651 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1652 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1653 mNextWakeFromIdle = a;
1654 // If this wake from idle is earlier than whatever was previously scheduled,
1655 // and we are currently idling, then we need to rebatch alarms in case the idle
1656 // until time needs to be updated.
1657 if (mPendingIdleUntil != null) {
1658 needRebatch = true;
1659 }
1660 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001661 }
1662
1663 if (!rebatching) {
1664 if (DEBUG_VALIDATE) {
1665 if (doValidate && !validateConsistencyLocked()) {
1666 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1667 + " when(hex)=" + Long.toHexString(a.when)
1668 + " whenElapsed=" + a.whenElapsed
1669 + " maxWhenElapsed=" + a.maxWhenElapsed
1670 + " interval=" + a.repeatInterval + " op=" + a.operation
1671 + " flags=0x" + Integer.toHexString(a.flags));
1672 rebatchAllAlarmsLocked(false);
1673 needRebatch = false;
1674 }
1675 }
1676
1677 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001678 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001679 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001680
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001681 rescheduleKernelAlarmsLocked();
1682 updateNextAlarmClockLocked();
1683 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001684 }
1685
Christopher Tate1d99c392017-12-07 16:54:04 -08001686 /**
1687 * System-process internal API
1688 */
1689 private final class LocalService implements AlarmManagerInternal {
1690 @Override
1691 public void removeAlarmsForUid(int uid) {
1692 synchronized (mLock) {
1693 removeLocked(uid);
1694 }
1695 }
1696 }
1697
1698 /**
1699 * Public-facing binder interface
1700 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001701 private final IBinder mService = new IAlarmManager.Stub() {
1702 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001703 public void set(String callingPackage,
1704 int type, long triggerAtTime, long windowLength, long interval, int flags,
1705 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1706 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001707 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001708
1709 // make sure the caller is not lying about which package should be blamed for
1710 // wakelock time spent in alarm delivery
1711 mAppOps.checkPackage(callingUid, callingPackage);
1712
1713 // Repeating alarms must use PendingIntent, not direct listener
1714 if (interval != 0) {
1715 if (directReceiver != null) {
1716 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1717 }
1718 }
1719
Adam Lesinski182f73f2013-12-05 16:48:06 -08001720 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001721 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001722 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001723 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001724 }
1725
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001726 // No incoming callers can request either WAKE_FROM_IDLE or
1727 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1728 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1729 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1730
1731 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1732 // manager when to come out of idle mode, which is only for DeviceIdleController.
1733 if (callingUid != Process.SYSTEM_UID) {
1734 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1735 }
1736
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001737 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001738 if (windowLength == AlarmManager.WINDOW_EXACT) {
1739 flags |= AlarmManager.FLAG_STANDALONE;
1740 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001741
1742 // If this alarm is for an alarm clock, then it must be standalone and we will
1743 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001744 if (alarmClock != null) {
1745 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001746
1747 // If the caller is a core system component or on the user's whitelist, and not calling
1748 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1749 // This means we will allow these alarms to go off as normal even while idle, with no
1750 // timing restrictions.
1751 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001752 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001753 || ((mAppStateTracker != null)
1754 && mAppStateTracker.isUidPowerSaveWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001755 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1756 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001757 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001758
Christopher Tate14a7bb02015-10-01 10:24:31 -07001759 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1760 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001761 }
Christopher Tate89779822012-08-31 14:40:03 -07001762
Adam Lesinski182f73f2013-12-05 16:48:06 -08001763 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001764 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001765 getContext().enforceCallingOrSelfPermission(
1766 "android.permission.SET_TIME",
1767 "setTime");
1768
Greg Hackmann0cab8962014-02-21 16:35:52 -08001769 if (mNativeData == 0) {
1770 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1771 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001772 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001773
1774 synchronized (mLock) {
1775 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001778
1779 @Override
1780 public void setTimeZone(String tz) {
1781 getContext().enforceCallingOrSelfPermission(
1782 "android.permission.SET_TIME_ZONE",
1783 "setTimeZone");
1784
1785 final long oldId = Binder.clearCallingIdentity();
1786 try {
1787 setTimeZoneImpl(tz);
1788 } finally {
1789 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001792
Adam Lesinski182f73f2013-12-05 16:48:06 -08001793 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001794 public void remove(PendingIntent operation, IAlarmListener listener) {
1795 if (operation == null && listener == null) {
1796 Slog.w(TAG, "remove() with no intent or listener");
1797 return;
1798 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001799
Christopher Tate14a7bb02015-10-01 10:24:31 -07001800 synchronized (mLock) {
1801 removeLocked(operation, listener);
1802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001804
Adam Lesinski182f73f2013-12-05 16:48:06 -08001805 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001806 public long getNextWakeFromIdleTime() {
1807 return getNextWakeFromIdleTimeImpl();
1808 }
1809
1810 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001811 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001812 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1813 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1814 "getNextAlarmClock", null);
1815
1816 return getNextAlarmClockImpl(userId);
1817 }
1818
1819 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001820 public long currentNetworkTimeMillis() {
1821 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1822 if (time.hasCache()) {
1823 return time.currentTimeMillis();
1824 } else {
1825 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1826 }
1827 }
1828
1829 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001830 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001831 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001832
1833 if (args.length > 0 && "--proto".equals(args[0])) {
1834 dumpProto(fd);
1835 } else {
1836 dumpImpl(pw);
1837 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001838 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001839 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001840
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 synchronized (mLock) {
1843 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001844 mConstants.dump(pw);
1845 pw.println();
1846
Makoto Onukie4918212018-02-06 11:30:15 -08001847 if (mAppStateTracker != null) {
1848 mAppStateTracker.dump(pw, " ");
1849 pw.println();
1850 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001851
Suprabh Shukla75edab12018-01-29 14:09:06 -08001852 pw.println(" App Standby Parole: " + mAppStandbyParole);
1853 pw.println();
1854
Christopher Tatee0a22b32013-07-11 14:43:13 -07001855 final long nowRTC = System.currentTimeMillis();
1856 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001857 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001858
Dianne Hackborna750a632015-06-16 17:18:23 -07001859 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001860 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001861 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001862 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001863 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001864 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001865 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1866 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001867 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001868 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1869 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001870 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1871 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001872 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001873 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001874 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001875 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1876 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001877 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001878 pw.print(" Max wakeup delay: ");
1879 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1880 pw.println();
1881 pw.print(" Time since last dispatch: ");
1882 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1883 pw.println();
1884 pw.print(" Next non-wakeup delivery time: ");
1885 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1886 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001887
1888 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1889 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001890 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001891 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001892 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001893 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001894 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1895 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001896 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001897 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1898 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001899 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001900 pw.print(" = "); pw.println(mLastWakeup);
1901 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1902 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001903 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001904
John Spurlock604a5ee2015-06-01 12:27:22 -04001905 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001906 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001907 final TreeSet<Integer> users = new TreeSet<>();
1908 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1909 users.add(mNextAlarmClockForUser.keyAt(i));
1910 }
1911 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1912 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1913 }
1914 for (int user : users) {
1915 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1916 final long time = next != null ? next.getTriggerTime() : 0;
1917 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001918 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001919 pw.print(" pendingSend:"); pw.print(pendingSend);
1920 pw.print(" time:"); pw.print(time);
1921 if (time > 0) {
1922 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1923 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1924 }
1925 pw.println();
1926 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001927 if (mAlarmBatches.size() > 0) {
1928 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001929 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001930 pw.println(mAlarmBatches.size());
1931 for (Batch b : mAlarmBatches) {
1932 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001933 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001935 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001936 pw.println();
1937 pw.println(" Pending user blocked background alarms: ");
1938 boolean blocked = false;
1939 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1940 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1941 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1942 blocked = true;
1943 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1944 }
1945 }
1946 if (!blocked) {
1947 pw.println(" none");
1948 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001949
Suprabh Shukla75edab12018-01-29 14:09:06 -08001950 pw.println(" mLastAlarmDeliveredForPackage:");
1951 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1952 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1953 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1954 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1955 pw.println();
1956 }
1957 pw.println();
1958
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001959 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001960 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001961 pw.println(" Idle mode state:");
1962 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001963 if (mPendingIdleUntil != null) {
1964 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001965 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001966 } else {
1967 pw.println("null");
1968 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001969 pw.println(" Pending alarms:");
1970 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001971 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001972 if (mNextWakeFromIdle != null) {
1973 pw.println();
1974 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001975 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001976 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001977
1978 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001979 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001980 if (mPendingNonWakeupAlarms.size() > 0) {
1981 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001982 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001983 } else {
1984 pw.println("(none)");
1985 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001986 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001987 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1988 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001989 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001990 pw.print(", max non-interactive time: ");
1991 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1992 pw.println();
1993
1994 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001995 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001996 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1997 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1998 pw.print(" Listener send count: "); pw.println(mListenerCount);
1999 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002000 pw.println();
2001
Christopher Tate7f2a0352015-12-08 10:24:33 -08002002 if (mInFlight.size() > 0) {
2003 pw.println("Outstanding deliveries:");
2004 for (int i = 0; i < mInFlight.size(); i++) {
2005 pw.print(" #"); pw.print(i); pw.print(": ");
2006 pw.println(mInFlight.get(i));
2007 }
2008 pw.println();
2009 }
2010
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002011 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002012 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002013 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002014 pw.print(" UID ");
2015 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2016 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002017 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002018 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2019 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2020
2021 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2022 pw.print(" Next allowed:");
2023 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2024 pw.print(" (");
2025 TimeUtils.formatDuration(minInterval, 0, pw);
2026 pw.print(")");
2027
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002028 pw.println();
2029 }
2030 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002031
2032 pw.print(" mUseAllowWhileIdleShortTime: [");
2033 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2034 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2035 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2036 pw.print(" ");
2037 }
2038 }
2039 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002040 pw.println();
2041
Dianne Hackborn81038902012-11-26 17:04:09 -08002042 if (mLog.dump(pw, " Recent problems", " ")) {
2043 pw.println();
2044 }
2045
2046 final FilterStats[] topFilters = new FilterStats[10];
2047 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2048 @Override
2049 public int compare(FilterStats lhs, FilterStats rhs) {
2050 if (lhs.aggregateTime < rhs.aggregateTime) {
2051 return 1;
2052 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2053 return -1;
2054 }
2055 return 0;
2056 }
2057 };
2058 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002059 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002060 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2061 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2062 for (int ip=0; ip<uidStats.size(); ip++) {
2063 BroadcastStats bs = uidStats.valueAt(ip);
2064 for (int is=0; is<bs.filterStats.size(); is++) {
2065 FilterStats fs = bs.filterStats.valueAt(is);
2066 int pos = len > 0
2067 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2068 if (pos < 0) {
2069 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002070 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002071 if (pos < topFilters.length) {
2072 int copylen = topFilters.length - pos - 1;
2073 if (copylen > 0) {
2074 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2075 }
2076 topFilters[pos] = fs;
2077 if (len < topFilters.length) {
2078 len++;
2079 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002080 }
2081 }
2082 }
2083 }
2084 if (len > 0) {
2085 pw.println(" Top Alarms:");
2086 for (int i=0; i<len; i++) {
2087 FilterStats fs = topFilters[i];
2088 pw.print(" ");
2089 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2090 TimeUtils.formatDuration(fs.aggregateTime, pw);
2091 pw.print(" running, "); pw.print(fs.numWakeup);
2092 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002093 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2094 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002095 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002096 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002097 pw.println();
2098 }
2099 }
2100
2101 pw.println(" ");
2102 pw.println(" Alarm Stats:");
2103 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002104 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2105 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2106 for (int ip=0; ip<uidStats.size(); ip++) {
2107 BroadcastStats bs = uidStats.valueAt(ip);
2108 pw.print(" ");
2109 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2110 UserHandle.formatUid(pw, bs.mUid);
2111 pw.print(":");
2112 pw.print(bs.mPackageName);
2113 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2114 pw.print(" running, "); pw.print(bs.numWakeup);
2115 pw.println(" wakeups:");
2116 tmpFilters.clear();
2117 for (int is=0; is<bs.filterStats.size(); is++) {
2118 tmpFilters.add(bs.filterStats.valueAt(is));
2119 }
2120 Collections.sort(tmpFilters, comparator);
2121 for (int i=0; i<tmpFilters.size(); i++) {
2122 FilterStats fs = tmpFilters.get(i);
2123 pw.print(" ");
2124 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2125 TimeUtils.formatDuration(fs.aggregateTime, pw);
2126 pw.print(" "); pw.print(fs.numWakeup);
2127 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002128 pw.print(" alarms, last ");
2129 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2130 pw.println(":");
2131 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002132 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002133 pw.println();
2134 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002135 }
2136 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002137 pw.println();
2138 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002139
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002140 if (RECORD_DEVICE_IDLE_ALARMS) {
2141 pw.println();
2142 pw.println(" Allow while idle dispatches:");
2143 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2144 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2145 pw.print(" ");
2146 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2147 pw.print(": ");
2148 UserHandle.formatUid(pw, ent.uid);
2149 pw.print(":");
2150 pw.println(ent.pkg);
2151 if (ent.op != null) {
2152 pw.print(" ");
2153 pw.print(ent.op);
2154 pw.print(" / ");
2155 pw.print(ent.tag);
2156 if (ent.argRealtime != 0) {
2157 pw.print(" (");
2158 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2159 pw.print(")");
2160 }
2161 pw.println();
2162 }
2163 }
2164 }
2165
Christopher Tate18a75f12013-07-01 18:18:59 -07002166 if (WAKEUP_STATS) {
2167 pw.println();
2168 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002169 long last = -1;
2170 for (WakeupEvent event : mRecentWakeups) {
2171 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2172 pw.print('|');
2173 if (last < 0) {
2174 pw.print('0');
2175 } else {
2176 pw.print(event.when - last);
2177 }
2178 last = event.when;
2179 pw.print('|'); pw.print(event.uid);
2180 pw.print('|'); pw.print(event.action);
2181 pw.println();
2182 }
2183 pw.println();
2184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
2186 }
2187
Kweku Adams61e03292017-10-19 14:27:12 -07002188 void dumpProto(FileDescriptor fd) {
2189 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2190
2191 synchronized (mLock) {
2192 final long nowRTC = System.currentTimeMillis();
2193 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002194 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2195 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2196 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002197 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002198 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002199 mLastTimeChangeRealtime);
2200
Yi Jin2b30f322018-02-20 15:41:47 -08002201 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002202
Makoto Onukie4918212018-02-06 11:30:15 -08002203 if (mAppStateTracker != null) {
2204 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002205 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002206 }
Kweku Adams61e03292017-10-19 14:27:12 -07002207
Yi Jin2b30f322018-02-20 15:41:47 -08002208 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002209 if (!mInteractive) {
2210 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002211 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002212 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002213 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002214 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002215 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002216 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002217 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002218 nowElapsed - mNextNonWakeupDeliveryTime);
2219 }
2220
Yi Jin2b30f322018-02-20 15:41:47 -08002221 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002222 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002223 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002224 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002225 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002226 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002227 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002228 nowElapsed - mLastWakeupSet);
Yi Jin2b30f322018-02-20 15:41:47 -08002229 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002230
2231 final TreeSet<Integer> users = new TreeSet<>();
2232 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2233 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2234 users.add(mNextAlarmClockForUser.keyAt(i));
2235 }
2236 final int pendingSendNextAlarmClockChangedForUserSize =
2237 mPendingSendNextAlarmClockChangedForUser.size();
2238 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2239 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2240 }
2241 for (int user : users) {
2242 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2243 final long time = next != null ? next.getTriggerTime() : 0;
2244 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002245 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002246 proto.write(AlarmClockMetadataProto.USER, user);
2247 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2248 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2249 proto.end(aToken);
2250 }
2251 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002252 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002253 nowElapsed, nowRTC);
2254 }
2255 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2256 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2257 if (blockedAlarms != null) {
2258 for (Alarm a : blockedAlarms) {
2259 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002260 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002261 nowElapsed, nowRTC);
2262 }
2263 }
2264 }
2265 if (mPendingIdleUntil != null) {
2266 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002267 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002268 }
2269 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002270 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002271 nowElapsed, nowRTC);
2272 }
2273 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002274 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002275 nowElapsed, nowRTC);
2276 }
2277
2278 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002279 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002280 nowElapsed, nowRTC);
2281 }
2282
Yi Jin2b30f322018-02-20 15:41:47 -08002283 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2284 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2285 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2286 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002287 mNonInteractiveTime);
2288
Yi Jin2b30f322018-02-20 15:41:47 -08002289 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2290 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2291 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2292 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2293 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002294
2295 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002296 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002297 }
2298
Kweku Adams61e03292017-10-19 14:27:12 -07002299 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2300 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002301 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002302 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2303 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2304
Yi Jin2b30f322018-02-20 15:41:47 -08002305 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2306 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2307 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002308 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002309 proto.end(token);
2310 }
2311
Makoto Onukiadb50d82018-01-29 16:20:30 -08002312 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2313 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002314 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002315 mUseAllowWhileIdleShortTime.keyAt(i));
2316 }
2317 }
2318
Yi Jin2b30f322018-02-20 15:41:47 -08002319 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002320
2321 final FilterStats[] topFilters = new FilterStats[10];
2322 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2323 @Override
2324 public int compare(FilterStats lhs, FilterStats rhs) {
2325 if (lhs.aggregateTime < rhs.aggregateTime) {
2326 return 1;
2327 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2328 return -1;
2329 }
2330 return 0;
2331 }
2332 };
2333 int len = 0;
2334 // Get the top 10 FilterStats, ordered by aggregateTime.
2335 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2336 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2337 for (int ip = 0; ip < uidStats.size(); ++ip) {
2338 BroadcastStats bs = uidStats.valueAt(ip);
2339 for (int is = 0; is < bs.filterStats.size(); ++is) {
2340 FilterStats fs = bs.filterStats.valueAt(is);
2341 int pos = len > 0
2342 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2343 if (pos < 0) {
2344 pos = -pos - 1;
2345 }
2346 if (pos < topFilters.length) {
2347 int copylen = topFilters.length - pos - 1;
2348 if (copylen > 0) {
2349 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2350 }
2351 topFilters[pos] = fs;
2352 if (len < topFilters.length) {
2353 len++;
2354 }
2355 }
2356 }
2357 }
2358 }
2359 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002360 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002361 FilterStats fs = topFilters[i];
2362
Yi Jin2b30f322018-02-20 15:41:47 -08002363 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2364 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002365 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002366 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002367
2368 proto.end(token);
2369 }
2370
2371 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2372 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2373 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2374 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002375 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002376
2377 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002378 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002379
2380 // uidStats is an ArrayMap, which we can't sort.
2381 tmpFilters.clear();
2382 for (int is = 0; is < bs.filterStats.size(); ++is) {
2383 tmpFilters.add(bs.filterStats.valueAt(is));
2384 }
2385 Collections.sort(tmpFilters, comparator);
2386 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002387 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002388 }
2389
2390 proto.end(token);
2391 }
2392 }
2393
2394 if (RECORD_DEVICE_IDLE_ALARMS) {
2395 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2396 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2397 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002398 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002399
2400 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2401 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2402 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2403 proto.write(IdleDispatchEntryProto.OP, ent.op);
2404 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2405 ent.elapsedRealtime);
2406 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2407
2408 proto.end(token);
2409 }
2410 }
2411
2412 if (WAKEUP_STATS) {
2413 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002414 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002415 proto.write(WakeupEventProto.UID, event.uid);
2416 proto.write(WakeupEventProto.ACTION, event.action);
2417 proto.write(WakeupEventProto.WHEN, event.when);
2418 proto.end(token);
2419 }
2420 }
2421 }
2422
2423 proto.flush();
2424 }
2425
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002426 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002427 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2428 PrintWriter pw = new PrintWriter(bs);
2429 final long nowRTC = System.currentTimeMillis();
2430 final long nowELAPSED = SystemClock.elapsedRealtime();
2431 final int NZ = mAlarmBatches.size();
2432 for (int iz = 0; iz < NZ; iz++) {
2433 Batch bz = mAlarmBatches.get(iz);
2434 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002435 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002436 pw.flush();
2437 Slog.v(TAG, bs.toString());
2438 bs.reset();
2439 }
2440 }
2441
2442 private boolean validateConsistencyLocked() {
2443 if (DEBUG_VALIDATE) {
2444 long lastTime = Long.MIN_VALUE;
2445 final int N = mAlarmBatches.size();
2446 for (int i = 0; i < N; i++) {
2447 Batch b = mAlarmBatches.get(i);
2448 if (b.start >= lastTime) {
2449 // duplicate start times are okay because of standalone batches
2450 lastTime = b.start;
2451 } else {
2452 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002453 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2454 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002455 return false;
2456 }
2457 }
2458 }
2459 return true;
2460 }
2461
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002462 private Batch findFirstWakeupBatchLocked() {
2463 final int N = mAlarmBatches.size();
2464 for (int i = 0; i < N; i++) {
2465 Batch b = mAlarmBatches.get(i);
2466 if (b.hasWakeups()) {
2467 return b;
2468 }
2469 }
2470 return null;
2471 }
2472
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002473 long getNextWakeFromIdleTimeImpl() {
2474 synchronized (mLock) {
2475 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2476 }
2477 }
2478
2479 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002480 synchronized (mLock) {
2481 return mNextAlarmClockForUser.get(userId);
2482 }
2483 }
2484
2485 /**
2486 * Recomputes the next alarm clock for all users.
2487 */
2488 private void updateNextAlarmClockLocked() {
2489 if (!mNextAlarmClockMayChange) {
2490 return;
2491 }
2492 mNextAlarmClockMayChange = false;
2493
Jose Lima235510e2014-08-13 12:50:01 -07002494 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002495 nextForUser.clear();
2496
2497 final int N = mAlarmBatches.size();
2498 for (int i = 0; i < N; i++) {
2499 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2500 final int M = alarms.size();
2501
2502 for (int j = 0; j < M; j++) {
2503 Alarm a = alarms.get(j);
2504 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002505 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002506 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002507
2508 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002509 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002510 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002511 " for user " + userId);
2512 }
2513
2514 // Alarms and batches are sorted by time, no need to compare times here.
2515 if (nextForUser.get(userId) == null) {
2516 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002517 } else if (a.alarmClock.equals(current)
2518 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2519 // same/earlier time and it's the one we cited before, so stick with it
2520 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002521 }
2522 }
2523 }
2524 }
2525
2526 // Update mNextAlarmForUser with new values.
2527 final int NN = nextForUser.size();
2528 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002529 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002530 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002531 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002532 if (!newAlarm.equals(currentAlarm)) {
2533 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2534 }
2535 }
2536
2537 // Remove users without any alarm clocks scheduled.
2538 final int NNN = mNextAlarmClockForUser.size();
2539 for (int i = NNN - 1; i >= 0; i--) {
2540 int userId = mNextAlarmClockForUser.keyAt(i);
2541 if (nextForUser.get(userId) == null) {
2542 updateNextAlarmInfoForUserLocked(userId, null);
2543 }
2544 }
2545 }
2546
Jose Lima235510e2014-08-13 12:50:01 -07002547 private void updateNextAlarmInfoForUserLocked(int userId,
2548 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002549 if (alarmClock != null) {
2550 if (DEBUG_ALARM_CLOCK) {
2551 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002552 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002553 }
2554 mNextAlarmClockForUser.put(userId, alarmClock);
2555 } else {
2556 if (DEBUG_ALARM_CLOCK) {
2557 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2558 }
2559 mNextAlarmClockForUser.remove(userId);
2560 }
2561
2562 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2563 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2564 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2565 }
2566
2567 /**
2568 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2569 * for which alarm clocks have changed since the last call to this.
2570 *
2571 * Do not call with a lock held. Only call from mHandler's thread.
2572 *
2573 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2574 */
2575 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002576 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002577 pendingUsers.clear();
2578
2579 synchronized (mLock) {
2580 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2581 for (int i = 0; i < N; i++) {
2582 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2583 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2584 }
2585 mPendingSendNextAlarmClockChangedForUser.clear();
2586 }
2587
2588 final int N = pendingUsers.size();
2589 for (int i = 0; i < N; i++) {
2590 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002591 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002592 Settings.System.putStringForUser(getContext().getContentResolver(),
2593 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002594 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002595 userId);
2596
2597 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2598 new UserHandle(userId));
2599 }
2600 }
2601
2602 /**
2603 * Formats an alarm like platform/packages/apps/DeskClock used to.
2604 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002605 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2606 int userId) {
2607 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002608 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2609 return (info == null) ? "" :
2610 DateFormat.format(pattern, info.getTriggerTime()).toString();
2611 }
2612
Adam Lesinski182f73f2013-12-05 16:48:06 -08002613 void rescheduleKernelAlarmsLocked() {
2614 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2615 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002616 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002617 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002618 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002619 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002620 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002621 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002622 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002623 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002624 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002625 if (firstBatch != firstWakeup) {
2626 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002627 }
2628 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002629 if (mPendingNonWakeupAlarms.size() > 0) {
2630 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2631 nextNonWakeup = mNextNonWakeupDeliveryTime;
2632 }
2633 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002634 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002635 mNextNonWakeup = nextNonWakeup;
2636 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2637 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002638 }
2639
Christopher Tate14a7bb02015-10-01 10:24:31 -07002640 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002641 if (operation == null && directReceiver == null) {
2642 if (localLOGV) {
2643 Slog.w(TAG, "requested remove() of null operation",
2644 new RuntimeException("here"));
2645 }
2646 return;
2647 }
2648
Adam Lesinski182f73f2013-12-05 16:48:06 -08002649 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002650 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002651 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2652 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002653 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002654 if (b.size() == 0) {
2655 mAlarmBatches.remove(i);
2656 }
2657 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002658 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002659 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002660 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2661 mPendingWhileIdleAlarms.remove(i);
2662 }
2663 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002664 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2665 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2666 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2667 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2668 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2669 alarmsForUid.remove(j);
2670 }
2671 }
2672 if (alarmsForUid.size() == 0) {
2673 mPendingBackgroundAlarms.removeAt(i);
2674 }
2675 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002676 if (didRemove) {
2677 if (DEBUG_BATCH) {
2678 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2679 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002680 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002681 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002682 mPendingIdleUntil = null;
2683 restorePending = true;
2684 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002685 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002686 mNextWakeFromIdle = null;
2687 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002688 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002689 if (restorePending) {
2690 restorePendingWhileIdleAlarmsLocked();
2691 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002692 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002693 }
2694 }
2695
Christopher Tate1d99c392017-12-07 16:54:04 -08002696 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002697 if (uid == Process.SYSTEM_UID) {
2698 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2699 return;
2700 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002701 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002702 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002703 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2704 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002705 didRemove |= b.remove(whichAlarms);
2706 if (b.size() == 0) {
2707 mAlarmBatches.remove(i);
2708 }
2709 }
2710 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2711 final Alarm a = mPendingWhileIdleAlarms.get(i);
2712 if (a.uid == uid) {
2713 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2714 mPendingWhileIdleAlarms.remove(i);
2715 }
2716 }
2717 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2718 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2719 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2720 if (alarmsForUid.get(j).uid == uid) {
2721 alarmsForUid.remove(j);
2722 }
2723 }
2724 if (alarmsForUid.size() == 0) {
2725 mPendingBackgroundAlarms.removeAt(i);
2726 }
2727 }
2728 if (didRemove) {
2729 if (DEBUG_BATCH) {
2730 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2731 }
2732 rebatchAllAlarmsLocked(true);
2733 rescheduleKernelAlarmsLocked();
2734 updateNextAlarmClockLocked();
2735 }
2736 }
2737
2738 void removeLocked(final String packageName) {
2739 if (packageName == null) {
2740 if (localLOGV) {
2741 Slog.w(TAG, "requested remove() of null packageName",
2742 new RuntimeException("here"));
2743 }
2744 return;
2745 }
2746
2747 boolean didRemove = false;
2748 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002749 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002750 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2751 Batch b = mAlarmBatches.get(i);
2752 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002753 if (b.size() == 0) {
2754 mAlarmBatches.remove(i);
2755 }
2756 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002757 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2758 if (oldHasTick != newHasTick) {
2759 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2760 }
2761
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002762 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002763 final Alarm a = mPendingWhileIdleAlarms.get(i);
2764 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002765 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2766 mPendingWhileIdleAlarms.remove(i);
2767 }
2768 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002769 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2770 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2771 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2772 if (alarmsForUid.get(j).matches(packageName)) {
2773 alarmsForUid.remove(j);
2774 }
2775 }
2776 if (alarmsForUid.size() == 0) {
2777 mPendingBackgroundAlarms.removeAt(i);
2778 }
2779 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002780 if (didRemove) {
2781 if (DEBUG_BATCH) {
2782 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2783 }
2784 rebatchAllAlarmsLocked(true);
2785 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002786 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002787 }
2788 }
2789
Christopher Tate1d99c392017-12-07 16:54:04 -08002790 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002791 if (uid == Process.SYSTEM_UID) {
2792 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2793 return;
2794 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002795 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002796 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2797 try {
2798 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2799 uid, a.packageName)) {
2800 return true;
2801 }
2802 } catch (RemoteException e) { /* fall through */}
2803 return false;
2804 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002805 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2806 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002807 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002808 if (b.size() == 0) {
2809 mAlarmBatches.remove(i);
2810 }
2811 }
2812 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2813 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002814 if (a.uid == uid) {
2815 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2816 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002817 }
2818 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002819 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2820 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2821 mPendingBackgroundAlarms.removeAt(i);
2822 }
2823 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002824 if (didRemove) {
2825 if (DEBUG_BATCH) {
2826 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2827 }
2828 rebatchAllAlarmsLocked(true);
2829 rescheduleKernelAlarmsLocked();
2830 updateNextAlarmClockLocked();
2831 }
2832 }
2833
Adam Lesinski182f73f2013-12-05 16:48:06 -08002834 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002835 if (userHandle == UserHandle.USER_SYSTEM) {
2836 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2837 return;
2838 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002839 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002840 final Predicate<Alarm> whichAlarms =
2841 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002842 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2843 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002844 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002845 if (b.size() == 0) {
2846 mAlarmBatches.remove(i);
2847 }
2848 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002849 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002850 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002851 == userHandle) {
2852 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2853 mPendingWhileIdleAlarms.remove(i);
2854 }
2855 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002856 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2857 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2858 mPendingBackgroundAlarms.removeAt(i);
2859 }
2860 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002861 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2862 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2863 mLastAllowWhileIdleDispatch.removeAt(i);
2864 }
2865 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002866
2867 if (didRemove) {
2868 if (DEBUG_BATCH) {
2869 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2870 }
2871 rebatchAllAlarmsLocked(true);
2872 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002873 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002874 }
2875 }
2876
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002877 void interactiveStateChangedLocked(boolean interactive) {
2878 if (mInteractive != interactive) {
2879 mInteractive = interactive;
2880 final long nowELAPSED = SystemClock.elapsedRealtime();
2881 if (interactive) {
2882 if (mPendingNonWakeupAlarms.size() > 0) {
2883 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2884 mTotalDelayTime += thisDelayTime;
2885 if (mMaxDelayTime < thisDelayTime) {
2886 mMaxDelayTime = thisDelayTime;
2887 }
2888 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2889 mPendingNonWakeupAlarms.clear();
2890 }
2891 if (mNonInteractiveStartTime > 0) {
2892 long dur = nowELAPSED - mNonInteractiveStartTime;
2893 if (dur > mNonInteractiveTime) {
2894 mNonInteractiveTime = dur;
2895 }
2896 }
2897 } else {
2898 mNonInteractiveStartTime = nowELAPSED;
2899 }
2900 }
2901 }
2902
Adam Lesinski182f73f2013-12-05 16:48:06 -08002903 boolean lookForPackageLocked(String packageName) {
2904 for (int i = 0; i < mAlarmBatches.size(); i++) {
2905 Batch b = mAlarmBatches.get(i);
2906 if (b.hasPackage(packageName)) {
2907 return true;
2908 }
2909 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002910 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002911 final Alarm a = mPendingWhileIdleAlarms.get(i);
2912 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002913 return true;
2914 }
2915 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002916 return false;
2917 }
2918
2919 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002920 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002921 // The kernel never triggers alarms with negative wakeup times
2922 // so we ensure they are positive.
2923 long alarmSeconds, alarmNanoseconds;
2924 if (when < 0) {
2925 alarmSeconds = 0;
2926 alarmNanoseconds = 0;
2927 } else {
2928 alarmSeconds = when / 1000;
2929 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2930 }
Kweku Adams61e03292017-10-19 14:27:12 -07002931
Christopher Tate8b98ade2018-02-09 11:13:19 -08002932 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2933 if (result != 0) {
2934 final long nowElapsed = SystemClock.elapsedRealtime();
2935 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2936 + " type=" + type + " when=" + when
2937 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2938 + "), ret = " + result + " = " + Os.strerror(result));
2939 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002940 } else {
2941 Message msg = Message.obtain();
2942 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002943
Adam Lesinski182f73f2013-12-05 16:48:06 -08002944 mHandler.removeMessages(ALARM_EVENT);
2945 mHandler.sendMessageAtTime(msg, when);
2946 }
2947 }
2948
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002949 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002950 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002951 for (int i=list.size()-1; i>=0; i--) {
2952 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002953 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2954 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002955 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002956 }
2957 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002958
2959 private static final String labelForType(int type) {
2960 switch (type) {
2961 case RTC: return "RTC";
2962 case RTC_WAKEUP : return "RTC_WAKEUP";
2963 case ELAPSED_REALTIME : return "ELAPSED";
2964 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002965 }
2966 return "--unknown--";
2967 }
2968
2969 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002970 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002971 for (int i=list.size()-1; i>=0; i--) {
2972 Alarm a = list.get(i);
2973 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002974 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2975 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002976 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002977 }
2978 }
2979
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002980 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002981 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002982 if (alarm.alarmClock != null) {
2983 // Don't block alarm clocks
2984 return false;
2985 }
2986 if (alarm.operation != null
2987 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2988 // Don't block starting foreground components
2989 return false;
2990 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002991 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002992 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08002993 return (mAppStateTracker != null) &&
2994 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage, allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002995 }
2996
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002997 private native long init();
2998 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002999 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003000 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003001 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003002 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003003
Makoto Onukiadb50d82018-01-29 16:20:30 -08003004 private long getWhileIdleMinIntervalLocked(int uid) {
3005 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003006 final boolean ebs = (mAppStateTracker != null)
3007 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003008 if (!dozing && !ebs) {
3009 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3010 }
3011 if (dozing) {
3012 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3013 }
3014 if (mUseAllowWhileIdleShortTime.get(uid)) {
3015 // if the last allow-while-idle went off while uid was fg, or the uid
3016 // recently came into fg, don't block the alarm for long.
3017 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3018 }
3019 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3020 }
3021
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003022 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003023 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003024 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003025 // batches are temporally sorted, so we need only pull from the
3026 // start of the list until we either empty it or hit a batch
3027 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003028 while (mAlarmBatches.size() > 0) {
3029 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003030 if (batch.start > nowELAPSED) {
3031 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003032 break;
3033 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003034
Christopher Tatee0a22b32013-07-11 14:43:13 -07003035 // We will (re)schedule some alarms now; don't let that interfere
3036 // with delivery of this current batch
3037 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003038
Christopher Tatee0a22b32013-07-11 14:43:13 -07003039 final int N = batch.size();
3040 for (int i = 0; i < N; i++) {
3041 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003042
3043 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3044 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
3045 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003046 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003047 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003048 if (nowELAPSED < minTime) {
3049 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3050 // alarm went off for this app. Reschedule the alarm to be in the
3051 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003052 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003053 if (alarm.maxWhenElapsed < minTime) {
3054 alarm.maxWhenElapsed = minTime;
3055 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003056 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003057 if (RECORD_DEVICE_IDLE_ALARMS) {
3058 IdleDispatchEntry ent = new IdleDispatchEntry();
3059 ent.uid = alarm.uid;
3060 ent.pkg = alarm.operation.getCreatorPackage();
3061 ent.tag = alarm.operation.getTag("");
3062 ent.op = "RESCHEDULE";
3063 ent.elapsedRealtime = nowELAPSED;
3064 ent.argRealtime = lastTime;
3065 mAllowWhileIdleDispatches.add(ent);
3066 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003067 setImplLocked(alarm, true, false);
3068 continue;
3069 }
3070 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003071 if (isBackgroundRestricted(alarm)) {
3072 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3073 if (DEBUG_BG_LIMIT) {
3074 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3075 }
3076 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3077 if (alarmsForUid == null) {
3078 alarmsForUid = new ArrayList<>();
3079 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3080 }
3081 alarmsForUid.add(alarm);
3082 continue;
3083 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003084
Christopher Tatee0a22b32013-07-11 14:43:13 -07003085 alarm.count = 1;
3086 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003087 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3088 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003089 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003090 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003091 if (mPendingIdleUntil == alarm) {
3092 mPendingIdleUntil = null;
3093 rebatchAllAlarmsLocked(false);
3094 restorePendingWhileIdleAlarmsLocked();
3095 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003096 if (mNextWakeFromIdle == alarm) {
3097 mNextWakeFromIdle = null;
3098 rebatchAllAlarmsLocked(false);
3099 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003100
3101 // Recurring alarms may have passed several alarm intervals while the
3102 // phone was asleep or off, so pass a trigger count when sending them.
3103 if (alarm.repeatInterval > 0) {
3104 // this adjustment will be zero if we're late by
3105 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003106 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003107
3108 // Also schedule its next recurrence
3109 final long delta = alarm.count * alarm.repeatInterval;
3110 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003111 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003112 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003113 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3114 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116
Christopher Tate864d42e2014-12-02 11:48:53 -08003117 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003118 hasWakeup = true;
3119 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003120
3121 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3122 if (alarm.alarmClock != null) {
3123 mNextAlarmClockMayChange = true;
3124 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003127
Christopher Tate1590f1e2014-10-02 17:27:57 -07003128 // This is a new alarm delivery set; bump the sequence number to indicate that
3129 // all apps' alarm delivery classes should be recalculated.
3130 mCurrentSeq++;
3131 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003132 Collections.sort(triggerList, mAlarmDispatchComparator);
3133
3134 if (localLOGV) {
3135 for (int i=0; i<triggerList.size(); i++) {
3136 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3137 }
3138 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003139
3140 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003141 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003142
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003143 /**
3144 * This Comparator sorts Alarms into increasing time order.
3145 */
3146 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3147 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003148 long when1 = a1.whenElapsed;
3149 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003150 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151 return 1;
3152 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003153 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003154 return -1;
3155 }
3156 return 0;
3157 }
3158 }
Kweku Adams61e03292017-10-19 14:27:12 -07003159
Makoto Onuki2206af32017-11-21 16:25:35 -08003160 @VisibleForTesting
3161 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003162 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003163 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003164 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003165 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003166 public final IAlarmListener listener;
3167 public final String listenerTag;
3168 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003169 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003170 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003171 public final AlarmManager.AlarmClockInfo alarmClock;
3172 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003173 public final int creatorUid;
3174 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003175 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003176 public int count;
3177 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003178 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003179 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003180 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003181 // Expected alarm expiry time before app standby deferring is applied.
3182 public long expectedWhenElapsed;
3183 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003184 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003185 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003186
Christopher Tate3e04b472013-10-21 17:51:31 -07003187 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003188 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3189 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3190 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003191 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003192 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003193 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3194 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003195 when = _when;
3196 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003197 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003198 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003199 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003200 repeatInterval = _interval;
3201 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003202 listener = _rec;
3203 listenerTag = _listenerTag;
3204 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003205 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003206 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003207 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003208 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003209 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003210 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003211 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003212 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003213
Christopher Tate14a7bb02015-10-01 10:24:31 -07003214 public static String makeTag(PendingIntent pi, String tag, int type) {
3215 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3216 ? "*walarm*:" : "*alarm*:";
3217 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3218 }
3219
3220 public WakeupEvent makeWakeupEvent(long nowRTC) {
3221 return new WakeupEvent(nowRTC, creatorUid,
3222 (operation != null)
3223 ? operation.getIntent().getAction()
3224 : ("<listener>:" + listenerTag));
3225 }
3226
3227 // Returns true if either matches
3228 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3229 return (operation != null)
3230 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003231 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003232 }
3233
3234 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003235 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003236 }
3237
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003238 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003239 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003240 StringBuilder sb = new StringBuilder(128);
3241 sb.append("Alarm{");
3242 sb.append(Integer.toHexString(System.identityHashCode(this)));
3243 sb.append(" type ");
3244 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003245 sb.append(" when ");
3246 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003247 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003248 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003249 sb.append('}');
3250 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003251 }
3252
Kweku Adams61e03292017-10-19 14:27:12 -07003253 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003254 SimpleDateFormat sdf) {
3255 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003256 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003257 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003258 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3259 expectedWhenElapsed, nowELAPSED, pw);
3260 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3261 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003262 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3263 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003264 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3265 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003266 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003267 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003268 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003269 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003270 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003271 }
3272 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003273 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003274 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003275 pw.print(" count="); pw.print(count);
3276 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003277 if (alarmClock != null) {
3278 pw.print(prefix); pw.println("Alarm clock:");
3279 pw.print(prefix); pw.print(" triggerTime=");
3280 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3281 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3282 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003283 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003284 if (listener != null) {
3285 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 }
Kweku Adams61e03292017-10-19 14:27:12 -07003288
3289 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3290 long nowRTC) {
3291 final long token = proto.start(fieldId);
3292
3293 proto.write(AlarmProto.TAG, statsTag);
3294 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003295 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003296 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3297 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3298 proto.write(AlarmProto.COUNT, count);
3299 proto.write(AlarmProto.FLAGS, flags);
3300 if (alarmClock != null) {
3301 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3302 }
3303 if (operation != null) {
3304 operation.writeToProto(proto, AlarmProto.OPERATION);
3305 }
3306 if (listener != null) {
3307 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3308 }
3309
3310 proto.end(token);
3311 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003313
Christopher Tatee0a22b32013-07-11 14:43:13 -07003314 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3315 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003316 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3317 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003318 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003319 break;
3320 }
3321
Christopher Tatee0a22b32013-07-11 14:43:13 -07003322 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003323 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3324 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003325 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003326 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003327 }
3328 }
3329
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003330 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3331 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3332 if (timeSinceOn < 5*60*1000) {
3333 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3334 return 2*60*1000;
3335 } else if (timeSinceOn < 30*60*1000) {
3336 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3337 return 15*60*1000;
3338 } else {
3339 // Otherwise, we will delay by at most an hour.
3340 return 60*60*1000;
3341 }
3342 }
3343
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003344 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003345 if (duration < 15*60*1000) {
3346 // If the duration until the time is less than 15 minutes, the maximum fuzz
3347 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003348 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003349 } else if (duration < 90*60*1000) {
3350 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3351 return 15*60*1000;
3352 } else {
3353 // Otherwise, we will fuzz by at most half an hour.
3354 return 30*60*1000;
3355 }
3356 }
3357
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003358 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3359 if (mInteractive) {
3360 return false;
3361 }
3362 if (mLastAlarmDeliveryTime <= 0) {
3363 return false;
3364 }
minho.choo649acab2014-12-12 16:13:55 +09003365 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003366 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3367 // and the next delivery time is in the past, then just deliver them all. This
3368 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3369 return false;
3370 }
3371 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3372 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3373 }
3374
3375 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3376 mLastAlarmDeliveryTime = nowELAPSED;
3377 for (int i=0; i<triggerList.size(); i++) {
3378 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003379 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003380 if (alarm.wakeup) {
3381 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3382 } else {
3383 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3384 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003385 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003386 if (localLOGV) {
3387 Slog.v(TAG, "sending alarm " + alarm);
3388 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003389 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003390 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3391 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003392 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003393 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003394 } catch (RuntimeException e) {
3395 Slog.w(TAG, "Failure sending alarm.", e);
3396 }
Tim Murray175c0f92017-11-28 15:01:04 -08003397 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003398 }
3399 }
3400
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003401 private boolean isExemptFromAppStandby(Alarm a) {
3402 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3403 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3404 }
3405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003406 private class AlarmThread extends Thread
3407 {
3408 public AlarmThread()
3409 {
3410 super("AlarmManager");
3411 }
Kweku Adams61e03292017-10-19 14:27:12 -07003412
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003413 public void run()
3414 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003415 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 while (true)
3418 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003419 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003420
Dianne Hackbornc3527222015-05-13 14:03:20 -07003421 final long nowRTC = System.currentTimeMillis();
3422 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003423 synchronized (mLock) {
3424 mLastWakeup = nowELAPSED;
3425 }
3426
3427 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003428
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003429 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003430 // The kernel can give us spurious time change notifications due to
3431 // small adjustments it makes internally; we want to filter those out.
3432 final long lastTimeChangeClockTime;
3433 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003434 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003435 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3436 expectedClockTime = lastTimeChangeClockTime
3437 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003438 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003439 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3440 || nowRTC > (expectedClockTime+1000)) {
3441 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003442 // let's do it!
3443 if (DEBUG_BATCH) {
3444 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3445 }
3446 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003447 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003448 rebatchAllAlarms();
3449 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003450 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003451 synchronized (mLock) {
3452 mNumTimeChanged++;
3453 mLastTimeChangeClockTime = nowRTC;
3454 mLastTimeChangeRealtime = nowELAPSED;
3455 }
3456 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3457 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003458 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003459 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3460 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003461 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3462
3463 // The world has changed on us, so we need to re-evaluate alarms
3464 // regardless of whether the kernel has told us one went off.
3465 result |= IS_WAKEUP_MASK;
3466 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003468
Dianne Hackbornc3527222015-05-13 14:03:20 -07003469 if (result != TIME_CHANGED_MASK) {
3470 // If this was anything besides just a time change, then figure what if
3471 // anything to do about alarms.
3472 synchronized (mLock) {
3473 if (localLOGV) Slog.v(
3474 TAG, "Checking for alarms... rtc=" + nowRTC
3475 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003476
Dianne Hackbornc3527222015-05-13 14:03:20 -07003477 if (WAKEUP_STATS) {
3478 if ((result & IS_WAKEUP_MASK) != 0) {
3479 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3480 int n = 0;
3481 for (WakeupEvent event : mRecentWakeups) {
3482 if (event.when > newEarliest) break;
3483 n++; // number of now-stale entries at the list head
3484 }
3485 for (int i = 0; i < n; i++) {
3486 mRecentWakeups.remove();
3487 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003488
Dianne Hackbornc3527222015-05-13 14:03:20 -07003489 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003490 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003491 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003492
Christopher Tate8b98ade2018-02-09 11:13:19 -08003493 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003494 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3495 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3496 // if there are no wakeup alarms and the screen is off, we can
3497 // delay what we have so far until the future.
3498 if (mPendingNonWakeupAlarms.size() == 0) {
3499 mStartCurrentDelayTime = nowELAPSED;
3500 mNextNonWakeupDeliveryTime = nowELAPSED
3501 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3502 }
3503 mPendingNonWakeupAlarms.addAll(triggerList);
3504 mNumDelayedAlarms += triggerList.size();
3505 rescheduleKernelAlarmsLocked();
3506 updateNextAlarmClockLocked();
3507 } else {
3508 // now deliver the alarm intents; if there are pending non-wakeup
3509 // alarms, we need to merge them in to the list. note we don't
3510 // just deliver them first because we generally want non-wakeup
3511 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003512 if (mPendingNonWakeupAlarms.size() > 0) {
3513 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3514 triggerList.addAll(mPendingNonWakeupAlarms);
3515 Collections.sort(triggerList, mAlarmDispatchComparator);
3516 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3517 mTotalDelayTime += thisDelayTime;
3518 if (mMaxDelayTime < thisDelayTime) {
3519 mMaxDelayTime = thisDelayTime;
3520 }
3521 mPendingNonWakeupAlarms.clear();
3522 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003523 final ArraySet<Pair<String, Integer>> triggerPackages =
3524 new ArraySet<>();
3525 for (int i = 0; i < triggerList.size(); i++) {
3526 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003527 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003528 triggerPackages.add(Pair.create(
3529 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003530 }
3531 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003532 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003533 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3534 rescheduleKernelAlarmsLocked();
3535 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003536 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003537 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003538
3539 } else {
3540 // Just in case -- even though no wakeup flag was set, make sure
3541 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003542 synchronized (mLock) {
3543 rescheduleKernelAlarmsLocked();
3544 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003545 }
3546 }
3547 }
3548 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003549
David Christieebe51fc2013-07-26 13:23:29 -07003550 /**
3551 * Attribute blame for a WakeLock.
3552 * @param pi PendingIntent to attribute blame to if ws is null.
3553 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003554 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003555 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003556 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003557 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003558 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003559 final boolean unimportant = pi == mTimeTickSender;
3560 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003561 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003562 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003563 } else {
3564 mWakeLock.setHistoryTag(null);
3565 }
3566 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003567 if (ws != null) {
3568 mWakeLock.setWorkSource(ws);
3569 return;
3570 }
3571
Christopher Tate14a7bb02015-10-01 10:24:31 -07003572 final int uid = (knownUid >= 0)
3573 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003574 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003575 if (uid >= 0) {
3576 mWakeLock.setWorkSource(new WorkSource(uid));
3577 return;
3578 }
3579 } catch (Exception e) {
3580 }
3581
3582 // Something went wrong; fall back to attributing the lock to the OS
3583 mWakeLock.setWorkSource(null);
3584 }
3585
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003586 private class AlarmHandler extends Handler {
3587 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003588 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3589 public static final int LISTENER_TIMEOUT = 3;
3590 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003591 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3592 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003593 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003595 public AlarmHandler() {
3596 }
Kweku Adams61e03292017-10-19 14:27:12 -07003597
Makoto Onuki4d298b52018-02-05 10:54:58 -08003598 public void postRemoveForStopped(int uid) {
3599 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3600 }
3601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003602 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003603 switch (msg.what) {
3604 case ALARM_EVENT: {
3605 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3606 synchronized (mLock) {
3607 final long nowRTC = System.currentTimeMillis();
3608 final long nowELAPSED = SystemClock.elapsedRealtime();
3609 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3610 updateNextAlarmClockLocked();
3611 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003612
Christopher Tate14a7bb02015-10-01 10:24:31 -07003613 // now trigger the alarms without the lock held
3614 for (int i=0; i<triggerList.size(); i++) {
3615 Alarm alarm = triggerList.get(i);
3616 try {
3617 alarm.operation.send();
3618 } catch (PendingIntent.CanceledException e) {
3619 if (alarm.repeatInterval > 0) {
3620 // This IntentSender is no longer valid, but this
3621 // is a repeating alarm, so toss the hoser.
3622 removeImpl(alarm.operation);
3623 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003624 }
3625 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003626 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003627 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003628
3629 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3630 sendNextAlarmClockChanged();
3631 break;
3632
3633 case LISTENER_TIMEOUT:
3634 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3635 break;
3636
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003637 case REPORT_ALARMS_ACTIVE:
3638 if (mLocalDeviceIdleController != null) {
3639 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3640 }
3641 break;
3642
Suprabh Shukla75edab12018-01-29 14:09:06 -08003643 case APP_STANDBY_PAROLE_CHANGED:
3644 synchronized (mLock) {
3645 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003646 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3647 rescheduleKernelAlarmsLocked();
3648 updateNextAlarmClockLocked();
3649 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003650 }
3651 break;
3652
3653 case APP_STANDBY_BUCKET_CHANGED:
3654 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003655 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3656 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3657 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3658 rescheduleKernelAlarmsLocked();
3659 updateNextAlarmClockLocked();
3660 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003661 }
3662 break;
3663
Makoto Onuki4d298b52018-02-05 10:54:58 -08003664 case REMOVE_FOR_STOPPED:
3665 synchronized (mLock) {
3666 removeForStoppedLocked(msg.arg1);
3667 }
3668 break;
3669
Christopher Tate14a7bb02015-10-01 10:24:31 -07003670 default:
3671 // nope, just ignore it
3672 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 }
3674 }
3675 }
Kweku Adams61e03292017-10-19 14:27:12 -07003676
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003677 class ClockReceiver extends BroadcastReceiver {
3678 public ClockReceiver() {
3679 IntentFilter filter = new IntentFilter();
3680 filter.addAction(Intent.ACTION_TIME_TICK);
3681 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003682 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
Kweku Adams61e03292017-10-19 14:27:12 -07003684
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003685 @Override
3686 public void onReceive(Context context, Intent intent) {
3687 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003688 if (DEBUG_BATCH) {
3689 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3690 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003691 synchronized (mLock) {
3692 mLastTickReceived = System.currentTimeMillis();
3693 }
Christopher Tate385e4982013-07-23 18:22:29 -07003694 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003695 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3696 // Since the kernel does not keep track of DST, we need to
3697 // reset the TZ information at the beginning of each day
3698 // based off of the current Zone gmt offset + userspace tracked
3699 // daylight savings information.
3700 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003701 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003702 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003703 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003704 }
3705 }
Kweku Adams61e03292017-10-19 14:27:12 -07003706
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003708 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003709 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003710
3711 // Schedule this event for the amount of time that it would take to get to
3712 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003713 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003714
David Christieebe51fc2013-07-26 13:23:29 -07003715 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003716 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003717 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3718 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003719
3720 // Finally, remember when we set the tick alarm
3721 synchronized (mLock) {
3722 mLastTickSet = currentTime;
3723 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
Christopher Tate385e4982013-07-23 18:22:29 -07003725
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003726 public void scheduleDateChangedEvent() {
3727 Calendar calendar = Calendar.getInstance();
3728 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003729 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 calendar.set(Calendar.MINUTE, 0);
3731 calendar.set(Calendar.SECOND, 0);
3732 calendar.set(Calendar.MILLISECOND, 0);
3733 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003734
3735 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003736 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3737 AlarmManager.FLAG_STANDALONE, workSource, null,
3738 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 }
3740 }
Kweku Adams61e03292017-10-19 14:27:12 -07003741
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003742 class InteractiveStateReceiver extends BroadcastReceiver {
3743 public InteractiveStateReceiver() {
3744 IntentFilter filter = new IntentFilter();
3745 filter.addAction(Intent.ACTION_SCREEN_OFF);
3746 filter.addAction(Intent.ACTION_SCREEN_ON);
3747 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3748 getContext().registerReceiver(this, filter);
3749 }
3750
3751 @Override
3752 public void onReceive(Context context, Intent intent) {
3753 synchronized (mLock) {
3754 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3755 }
3756 }
3757 }
3758
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 class UninstallReceiver extends BroadcastReceiver {
3760 public UninstallReceiver() {
3761 IntentFilter filter = new IntentFilter();
3762 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3763 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003764 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003765 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003766 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003767 // Register for events related to sdcard installation.
3768 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003769 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003770 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003771 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003772 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
Kweku Adams61e03292017-10-19 14:27:12 -07003774
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003775 @Override
3776 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003777 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003778 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003779 String action = intent.getAction();
3780 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003781 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3782 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3783 for (String packageName : pkgList) {
3784 if (lookForPackageLocked(packageName)) {
3785 setResultCode(Activity.RESULT_OK);
3786 return;
3787 }
3788 }
3789 return;
3790 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003791 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003792 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3793 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3794 if (userHandle >= 0) {
3795 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003796 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3797 final Pair<String, Integer> packageUser =
3798 mLastAlarmDeliveredForPackage.keyAt(i);
3799 if (packageUser.second == userHandle) {
3800 mLastAlarmDeliveredForPackage.removeAt(i);
3801 }
3802 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003803 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003804 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003805 if (uid >= 0) {
3806 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003807 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003808 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003809 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003810 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3811 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3812 // This package is being updated; don't kill its alarms.
3813 return;
3814 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003815 Uri data = intent.getData();
3816 if (data != null) {
3817 String pkg = data.getSchemeSpecificPart();
3818 if (pkg != null) {
3819 pkgList = new String[]{pkg};
3820 }
3821 }
3822 }
3823 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003824 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3825 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3826 if (ArrayUtils.contains(pkgList, packageUser.first)
3827 && packageUser.second == UserHandle.getUserId(uid)) {
3828 mLastAlarmDeliveredForPackage.removeAt(i);
3829 }
3830 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003831 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003832 if (uid >= 0) {
3833 // package-removed case
3834 removeLocked(uid);
3835 } else {
3836 // external-applications-unavailable etc case
3837 removeLocked(pkg);
3838 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003839 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003840 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3841 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3842 if (uidStats.remove(pkg) != null) {
3843 if (uidStats.size() <= 0) {
3844 mBroadcastStats.removeAt(i);
3845 }
3846 }
3847 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003848 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 }
3850 }
3851 }
3852 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003853
3854 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003855 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003856 }
3857
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003858 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003859 if (disabled) {
3860 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003861 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003862 }
3863
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003864 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003865 }
3866
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003867 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003868 if (disabled) {
3869 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003870 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003871 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003872
3873 @Override public void onUidCachedChanged(int uid, boolean cached) {
3874 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003875 };
3876
Suprabh Shukla75edab12018-01-29 14:09:06 -08003877 /**
3878 * Tracking of app assignments to standby buckets
3879 */
3880 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3881 @Override
3882 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08003883 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003884 if (DEBUG_STANDBY) {
3885 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3886 bucket);
3887 }
3888 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003889 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3890 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003891 }
3892
3893 @Override
3894 public void onParoleStateChanged(boolean isParoleOn) {
3895 if (DEBUG_STANDBY) {
3896 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3897 }
3898 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3899 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3900 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3901 Boolean.valueOf(isParoleOn)).sendToTarget();
3902 }
3903 };
3904
Makoto Onuki2206af32017-11-21 16:25:35 -08003905 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003906 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003907 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003908 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003909 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003910 }
3911 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003912
3913 @Override
3914 public void unblockAlarmsForUid(int uid) {
3915 synchronized (mLock) {
3916 sendPendingBackgroundAlarmsLocked(uid, null);
3917 }
3918 }
3919
3920 @Override
3921 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3922 synchronized (mLock) {
3923 sendPendingBackgroundAlarmsLocked(uid, packageName);
3924 }
3925 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003926
3927 @Override
3928 public void onUidForeground(int uid, boolean foreground) {
3929 synchronized (mLock) {
3930 if (foreground) {
3931 mUseAllowWhileIdleShortTime.put(uid, true);
3932
3933 // Note we don't have to drain the pending while-idle alarms here, because
3934 // this event should coincide with unblockAlarmsForUid().
3935 }
3936 }
3937 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003938 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003941 String pkg = pi.getCreatorPackage();
3942 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003943 return getStatsLocked(uid, pkg);
3944 }
3945
3946 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003947 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3948 if (uidStats == null) {
3949 uidStats = new ArrayMap<String, BroadcastStats>();
3950 mBroadcastStats.put(uid, uidStats);
3951 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003952 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003953 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003954 bs = new BroadcastStats(uid, pkgName);
3955 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003956 }
3957 return bs;
3958 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003959
Christopher Tate21e9f192017-08-08 13:49:11 -07003960 /**
3961 * Canonical count of (operation.send() - onSendFinished()) and
3962 * listener send/complete/timeout invocations.
3963 * Guarded by the usual lock.
3964 */
3965 @GuardedBy("mLock")
3966 private int mSendCount = 0;
3967 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003968 private int mSendFinishCount = 0;
3969 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003970 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003971 @GuardedBy("mLock")
3972 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003973
Christopher Tate14a7bb02015-10-01 10:24:31 -07003974 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003975
Christopher Tate14a7bb02015-10-01 10:24:31 -07003976 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3977 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003978 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003979 return mInFlight.remove(i);
3980 }
3981 }
3982 mLog.w("No in-flight alarm for " + pi + " " + intent);
3983 return null;
3984 }
3985
3986 private InFlight removeLocked(IBinder listener) {
3987 for (int i = 0; i < mInFlight.size(); i++) {
3988 if (mInFlight.get(i).mListener == listener) {
3989 return mInFlight.remove(i);
3990 }
3991 }
3992 mLog.w("No in-flight alarm for listener " + listener);
3993 return null;
3994 }
3995
3996 private void updateStatsLocked(InFlight inflight) {
3997 final long nowELAPSED = SystemClock.elapsedRealtime();
3998 BroadcastStats bs = inflight.mBroadcastStats;
3999 bs.nesting--;
4000 if (bs.nesting <= 0) {
4001 bs.nesting = 0;
4002 bs.aggregateTime += nowELAPSED - bs.startTime;
4003 }
4004 FilterStats fs = inflight.mFilterStats;
4005 fs.nesting--;
4006 if (fs.nesting <= 0) {
4007 fs.nesting = 0;
4008 fs.aggregateTime += nowELAPSED - fs.startTime;
4009 }
4010 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004011 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4012 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004013 }
4014 }
4015
4016 private void updateTrackingLocked(InFlight inflight) {
4017 if (inflight != null) {
4018 updateStatsLocked(inflight);
4019 }
4020 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004021 if (DEBUG_WAKELOCK) {
4022 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4023 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004024 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004025 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004026 mWakeLock.release();
4027 if (mInFlight.size() > 0) {
4028 mLog.w("Finished all dispatches with " + mInFlight.size()
4029 + " remaining inflights");
4030 for (int i=0; i<mInFlight.size(); i++) {
4031 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4032 }
4033 mInFlight.clear();
4034 }
4035 } else {
4036 // the next of our alarms is now in flight. reattribute the wakelock.
4037 if (mInFlight.size() > 0) {
4038 InFlight inFlight = mInFlight.get(0);
4039 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4040 inFlight.mAlarmType, inFlight.mTag, -1, false);
4041 } else {
4042 // should never happen
4043 mLog.w("Alarm wakelock still held but sent queue empty");
4044 mWakeLock.setWorkSource(null);
4045 }
4046 }
4047 }
4048
4049 /**
4050 * Callback that arrives when a direct-call alarm reports that delivery has finished
4051 */
4052 @Override
4053 public void alarmComplete(IBinder who) {
4054 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004055 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004056 + " pid=" + Binder.getCallingPid());
4057 return;
4058 }
4059
4060 final long ident = Binder.clearCallingIdentity();
4061 try {
4062 synchronized (mLock) {
4063 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4064 InFlight inflight = removeLocked(who);
4065 if (inflight != null) {
4066 if (DEBUG_LISTENER_CALLBACK) {
4067 Slog.i(TAG, "alarmComplete() from " + who);
4068 }
4069 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004070 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004071 } else {
4072 // Delivery timed out, and the timeout handling already took care of
4073 // updating our tracking here, so we needn't do anything further.
4074 if (DEBUG_LISTENER_CALLBACK) {
4075 Slog.i(TAG, "Late alarmComplete() from " + who);
4076 }
4077 }
4078 }
4079 } finally {
4080 Binder.restoreCallingIdentity(ident);
4081 }
4082 }
4083
4084 /**
4085 * Callback that arrives when a PendingIntent alarm has finished delivery
4086 */
4087 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004088 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4089 String resultData, Bundle resultExtras) {
4090 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004091 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004092 updateTrackingLocked(removeLocked(pi, intent));
4093 }
4094 }
4095
4096 /**
4097 * Timeout of a direct-call alarm delivery
4098 */
4099 public void alarmTimedOut(IBinder who) {
4100 synchronized (mLock) {
4101 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004102 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004103 // TODO: implement ANR policy for the target
4104 if (DEBUG_LISTENER_CALLBACK) {
4105 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004106 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004107 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004108 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004109 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004110 if (DEBUG_LISTENER_CALLBACK) {
4111 Slog.i(TAG, "Spurious timeout of listener " + who);
4112 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004113 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004114 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004115 }
4116 }
4117
4118 /**
4119 * Deliver an alarm and set up the post-delivery handling appropriately
4120 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004121 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004122 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4123 if (alarm.operation != null) {
4124 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004125 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004126
4127 if (alarm.priorityClass.priority == PRIO_TICK) {
4128 mLastTickIssued = nowELAPSED;
4129 }
4130
Christopher Tate14a7bb02015-10-01 10:24:31 -07004131 try {
4132 alarm.operation.send(getContext(), 0,
4133 mBackgroundIntent.putExtra(
4134 Intent.EXTRA_ALARM_COUNT, alarm.count),
4135 mDeliveryTracker, mHandler, null,
4136 allowWhileIdle ? mIdleOptions : null);
4137 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004138 if (alarm.operation == mTimeTickSender) {
4139 Slog.wtf(TAG, "mTimeTickSender canceled");
4140 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004141 if (alarm.repeatInterval > 0) {
4142 // This IntentSender is no longer valid, but this
4143 // is a repeating alarm, so toss it
4144 removeImpl(alarm.operation);
4145 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004146 // No actual delivery was possible, so the delivery tracker's
4147 // 'finished' callback won't be invoked. We also don't need
4148 // to do any wakelock or stats tracking, so we have nothing
4149 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004150 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004151 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004152 }
4153 } else {
4154 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004155 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004156 try {
4157 if (DEBUG_LISTENER_CALLBACK) {
4158 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4159 + " listener=" + alarm.listener.asBinder());
4160 }
4161 alarm.listener.doAlarm(this);
4162 mHandler.sendMessageDelayed(
4163 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4164 alarm.listener.asBinder()),
4165 mConstants.LISTENER_TIMEOUT);
4166 } catch (Exception e) {
4167 if (DEBUG_LISTENER_CALLBACK) {
4168 Slog.i(TAG, "Alarm undeliverable to listener "
4169 + alarm.listener.asBinder(), e);
4170 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004171 // As in the PendingIntent.CanceledException case, delivery of the
4172 // alarm was not possible, so we have no wakelock or timeout or
4173 // stats management to do. It threw before we posted the delayed
4174 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004175 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004176 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004177 }
4178 }
4179
4180 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004181 if (DEBUG_WAKELOCK) {
4182 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4183 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004184 if (mBroadcastRefCount == 0) {
4185 setWakelockWorkSource(alarm.operation, alarm.workSource,
4186 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4187 true);
4188 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004189 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004190 }
4191 final InFlight inflight = new InFlight(AlarmManagerService.this,
4192 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4193 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4194 mInFlight.add(inflight);
4195 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004196 if (allowWhileIdle) {
4197 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004198 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004199 if ((mAppStateTracker == null)
4200 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004201 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4202 } else {
4203 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4204 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004205 if (RECORD_DEVICE_IDLE_ALARMS) {
4206 IdleDispatchEntry ent = new IdleDispatchEntry();
4207 ent.uid = alarm.uid;
4208 ent.pkg = alarm.packageName;
4209 ent.tag = alarm.statsTag;
4210 ent.op = "DELIVER";
4211 ent.elapsedRealtime = nowELAPSED;
4212 mAllowWhileIdleDispatches.add(ent);
4213 }
4214 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004215 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004216 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4217 UserHandle.getUserId(alarm.creatorUid));
4218 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4219 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004220
4221 final BroadcastStats bs = inflight.mBroadcastStats;
4222 bs.count++;
4223 if (bs.nesting == 0) {
4224 bs.nesting = 1;
4225 bs.startTime = nowELAPSED;
4226 } else {
4227 bs.nesting++;
4228 }
4229 final FilterStats fs = inflight.mFilterStats;
4230 fs.count++;
4231 if (fs.nesting == 0) {
4232 fs.nesting = 1;
4233 fs.startTime = nowELAPSED;
4234 } else {
4235 fs.nesting++;
4236 }
4237 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4238 || alarm.type == RTC_WAKEUP) {
4239 bs.numWakeup++;
4240 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004241 ActivityManager.noteWakeupAlarm(
4242 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4243 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004244 }
4245 }
4246 }
4247}