blob: 6ca81c2889ab90069e086cc1cb0bbccc93b018aa [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;
mswest463f4c99d2018-02-01 10:13:10 -080060import android.os.ResultReceiver;
61import android.os.ShellCallback;
62import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.os.SystemClock;
64import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080065import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070066import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070067import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020068import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080069import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020071import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080072import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080073import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080074import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070075import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020076import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070077import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080078import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080079import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080080import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020081import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070082import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070083import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070084import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Jeff Sharkey9911a282018-02-14 22:29:11 -070086import com.android.internal.annotations.GuardedBy;
87import com.android.internal.annotations.VisibleForTesting;
88import com.android.internal.util.ArrayUtils;
89import com.android.internal.util.DumpUtils;
90import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070091import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070092import com.android.server.AppStateTracker.Listener;
93
Christopher Tate4cb338d2013-07-26 13:11:31 -070094import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.io.FileDescriptor;
96import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070097import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -070098import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800100import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import java.util.Calendar;
102import java.util.Collections;
103import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500104import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700105import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700106import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200107import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700108import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400110import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800111import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Makoto Onuki2206af32017-11-21 16:25:35 -0800113/**
114 * Alarm manager implementaion.
115 *
116 * Unit test:
117 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
118 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800119class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700120 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
121 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700123 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final int TIME_CHANGED_MASK = 1 << 16;
125 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800126
Christopher Tatee0a22b32013-07-11 14:43:13 -0700127 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800128 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800129
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 static final boolean localLOGV = false;
132 static final boolean DEBUG_BATCH = localLOGV || false;
133 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200134 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700135 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800136 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700137 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800138 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700139 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700140 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800141 static final int ALARM_EVENT = 1;
142 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200143
Christopher Tatef2159712018-03-27 16:04:14 -0700144 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
145 static final int ACTIVE_INDEX = 0;
146 static final int WORKING_INDEX = 1;
147 static final int FREQUENT_INDEX = 2;
148 static final int RARE_INDEX = 3;
149 static final int NEVER_INDEX = 4;
150
Christopher Tate14a7bb02015-10-01 10:24:31 -0700151 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800153 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700154
Adam Lesinski182f73f2013-12-05 16:48:06 -0800155 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700156
Christopher Tate24cd46f2016-02-02 14:28:01 -0800157 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
158 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700159 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
160 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200161
Adam Lesinski182f73f2013-12-05 16:48:06 -0800162 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800163
Christopher Tate14a7bb02015-10-01 10:24:31 -0700164 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800165 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800166 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700167
Adam Lesinski182f73f2013-12-05 16:48:06 -0800168 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800169
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700170 // List of alarms per uid deferred due to user applied background restrictions on the source app
171 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800172 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800173 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700174 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700175 private long mLastWakeupSet;
176 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800177 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800178 private long mLastTickSet;
179 private long mLastTickIssued; // elapsed
180 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800181 private long mLastTickAdded;
182 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800183 int mBroadcastRefCount = 0;
184 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700185 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700186 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
187 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800188 final AlarmHandler mHandler = new AlarmHandler();
189 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700190 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800191 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700192 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800193 PendingIntent mTimeTickSender;
194 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700195 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700196 boolean mInteractive = true;
197 long mNonInteractiveStartTime;
198 long mNonInteractiveTime;
199 long mLastAlarmDeliveryTime;
200 long mStartCurrentDelayTime;
201 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700202 long mLastTimeChangeClockTime;
203 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700204 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800205
Christopher Tatebb9cce52017-04-18 14:19:43 -0700206 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
207
208 /**
209 * This permission must be defined by the canonical System UI package,
210 * with protection level "signature".
211 */
212 private static final String SYSTEM_UI_SELF_PERMISSION =
213 "android.permission.systemui.IDENTITY";
214
215 /**
216 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
217 */
218 int mSystemUiUid;
219
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700220 /**
221 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700222 * used to determine the earliest we can dispatch the next such alarm. Times are in the
223 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700224 */
225 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
226
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800227 /**
228 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
229 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
230 */
231 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
232
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700233 final static class IdleDispatchEntry {
234 int uid;
235 String pkg;
236 String tag;
237 String op;
238 long elapsedRealtime;
239 long argRealtime;
240 }
241 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
242
Suprabh Shukla75edab12018-01-29 14:09:06 -0800243 interface Stats {
244 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800245 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800246 }
247
248 private final StatLogger mStatLogger = new StatLogger(new String[] {
249 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800250 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800251 });
252
Dianne Hackborna750a632015-06-16 17:18:23 -0700253 /**
254 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
255 */
256 Bundle mIdleOptions;
257
Jose Lima235510e2014-08-13 12:50:01 -0700258 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
259 new SparseArray<>();
260 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
261 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200262 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
263 new SparseBooleanArray();
264 private boolean mNextAlarmClockMayChange;
265
266 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700267 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
268 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200269
Makoto Onukie4918212018-02-06 11:30:15 -0800270 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800271 private boolean mAppStandbyParole;
272 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800273
Dianne Hackborna750a632015-06-16 17:18:23 -0700274 /**
275 * All times are in milliseconds. These constants are kept synchronized with the system
276 * global Settings. Any access to this class or its fields should be done while
277 * holding the AlarmManagerService.mLock lock.
278 */
279 private final class Constants extends ContentObserver {
280 // Key names stored in the settings value.
281 private static final String KEY_MIN_FUTURITY = "min_futurity";
282 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800283 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700284 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
285 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
286 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
287 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700288 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700289
Suprabh Shukla75edab12018-01-29 14:09:06 -0800290 // Keys for specifying throttling delay based on app standby bucketing
291 private final String[] KEYS_APP_STANDBY_DELAY = {
292 "standby_active_delay",
293 "standby_working_delay",
294 "standby_frequent_delay",
295 "standby_rare_delay",
296 "standby_never_delay",
297 };
298
Dianne Hackborna750a632015-06-16 17:18:23 -0700299 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
300 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800301 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700302 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700303 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700304 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700305 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800306 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
307 0, // Active
308 6 * 60_000, // Working
309 30 * 60_000, // Frequent
310 2 * 60 * 60_000, // Rare
311 10 * 24 * 60 * 60_000 // Never
312 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700313
Dianne Hackborna750a632015-06-16 17:18:23 -0700314 // Minimum futurity of a new alarm
315 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
316
317 // Minimum alarm recurrence interval
318 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
319
Christopher Tate22e919d2018-02-16 16:16:50 -0800320 // Maximum alarm recurrence interval
321 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
322
Dianne Hackborna750a632015-06-16 17:18:23 -0700323 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
324 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
325
326 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
327 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
328
329 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
330 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
331 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
332
Christopher Tate14a7bb02015-10-01 10:24:31 -0700333 // Direct alarm listener callback timeout
334 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
335
Suprabh Shukla75edab12018-01-29 14:09:06 -0800336 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
337
Dianne Hackborna750a632015-06-16 17:18:23 -0700338 private ContentResolver mResolver;
339 private final KeyValueListParser mParser = new KeyValueListParser(',');
340 private long mLastAllowWhileIdleWhitelistDuration = -1;
341
342 public Constants(Handler handler) {
343 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700344 updateAllowWhileIdleWhitelistDurationLocked();
345 }
346
347 public void start(ContentResolver resolver) {
348 mResolver = resolver;
349 mResolver.registerContentObserver(Settings.Global.getUriFor(
350 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
351 updateConstants();
352 }
353
Dianne Hackborna750a632015-06-16 17:18:23 -0700354 public void updateAllowWhileIdleWhitelistDurationLocked() {
355 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
356 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
357 BroadcastOptions opts = BroadcastOptions.makeBasic();
358 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
359 mIdleOptions = opts.toBundle();
360 }
361 }
362
363 @Override
364 public void onChange(boolean selfChange, Uri uri) {
365 updateConstants();
366 }
367
368 private void updateConstants() {
369 synchronized (mLock) {
370 try {
371 mParser.setString(Settings.Global.getString(mResolver,
372 Settings.Global.ALARM_MANAGER_CONSTANTS));
373 } catch (IllegalArgumentException e) {
374 // Failed to parse the settings string, log this and move on
375 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800376 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700377 }
378
379 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
380 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800381 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700382 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
383 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
384 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
385 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
386 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
387 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
388 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700389 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
390 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700391 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
392 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
393 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
394 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800395 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
396 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
397 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700398 updateAllowWhileIdleWhitelistDurationLocked();
399 }
400 }
401
402 void dump(PrintWriter pw) {
403 pw.println(" Settings:");
404
405 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
406 TimeUtils.formatDuration(MIN_FUTURITY, pw);
407 pw.println();
408
409 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
410 TimeUtils.formatDuration(MIN_INTERVAL, pw);
411 pw.println();
412
Christopher Tate22e919d2018-02-16 16:16:50 -0800413 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
414 TimeUtils.formatDuration(MAX_INTERVAL, pw);
415 pw.println();
416
Christopher Tate14a7bb02015-10-01 10:24:31 -0700417 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
418 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
419 pw.println();
420
Dianne Hackborna750a632015-06-16 17:18:23 -0700421 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
422 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
423 pw.println();
424
425 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
426 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
427 pw.println();
428
429 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
430 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
431 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800432
433 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
434 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
435 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
436 pw.println();
437 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700438 }
Kweku Adams61e03292017-10-19 14:27:12 -0700439
440 void dumpProto(ProtoOutputStream proto, long fieldId) {
441 final long token = proto.start(fieldId);
442
443 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
444 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800445 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700446 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
447 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
448 ALLOW_WHILE_IDLE_SHORT_TIME);
449 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
450 ALLOW_WHILE_IDLE_LONG_TIME);
451 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
452 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
453
454 proto.end(token);
455 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700456 }
457
458 final Constants mConstants;
459
Christopher Tate1590f1e2014-10-02 17:27:57 -0700460 // Alarm delivery ordering bookkeeping
461 static final int PRIO_TICK = 0;
462 static final int PRIO_WAKEUP = 1;
463 static final int PRIO_NORMAL = 2;
464
Dianne Hackborna750a632015-06-16 17:18:23 -0700465 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700466 int seq;
467 int priority;
468
469 PriorityClass() {
470 seq = mCurrentSeq - 1;
471 priority = PRIO_NORMAL;
472 }
473 }
474
Dianne Hackborna750a632015-06-16 17:18:23 -0700475 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700476 int mCurrentSeq = 0;
477
Dianne Hackborna750a632015-06-16 17:18:23 -0700478 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700479 public long when;
480 public int uid;
481 public String action;
482
483 public WakeupEvent(long theTime, int theUid, String theAction) {
484 when = theTime;
485 uid = theUid;
486 action = theAction;
487 }
488 }
489
Adam Lesinski182f73f2013-12-05 16:48:06 -0800490 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
491 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700492
Adrian Roosc42a1e12014-07-07 23:35:53 +0200493 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700494 long start; // These endpoints are always in ELAPSED
495 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700496 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700497
498 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
499
500 Batch() {
501 start = 0;
502 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700503 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700504 }
505
506 Batch(Alarm seed) {
507 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800508 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700509 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700510 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800511 if (seed.operation == mTimeTickSender) {
512 mLastTickAdded = System.currentTimeMillis();
513 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700514 }
515
516 int size() {
517 return alarms.size();
518 }
519
520 Alarm get(int index) {
521 return alarms.get(index);
522 }
523
524 boolean canHold(long whenElapsed, long maxWhen) {
525 return (end >= whenElapsed) && (start <= maxWhen);
526 }
527
528 boolean add(Alarm alarm) {
529 boolean newStart = false;
530 // narrows the batch if necessary; presumes that canHold(alarm) is true
531 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
532 if (index < 0) {
533 index = 0 - index - 1;
534 }
535 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800536 if (alarm.operation == mTimeTickSender) {
537 mLastTickAdded = System.currentTimeMillis();
538 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700539 if (DEBUG_BATCH) {
540 Slog.v(TAG, "Adding " + alarm + " to " + this);
541 }
542 if (alarm.whenElapsed > start) {
543 start = alarm.whenElapsed;
544 newStart = true;
545 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700546 if (alarm.maxWhenElapsed < end) {
547 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700548 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700549 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550
551 if (DEBUG_BATCH) {
552 Slog.v(TAG, " => now " + this);
553 }
554 return newStart;
555 }
556
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800557 boolean remove(Alarm alarm) {
558 return remove(a -> (a == alarm));
559 }
560
Christopher Tate1d99c392017-12-07 16:54:04 -0800561 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700562 boolean didRemove = false;
563 long newStart = 0; // recalculate endpoints as we go
564 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700565 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700566 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700567 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800568 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700569 alarms.remove(i);
570 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200571 if (alarm.alarmClock != null) {
572 mNextAlarmClockMayChange = true;
573 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800574 if (alarm.operation == mTimeTickSender) {
575 mLastTickRemoved = System.currentTimeMillis();
576 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700577 } else {
578 if (alarm.whenElapsed > newStart) {
579 newStart = alarm.whenElapsed;
580 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700581 if (alarm.maxWhenElapsed < newEnd) {
582 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700583 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700584 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 i++;
586 }
587 }
588 if (didRemove) {
589 // commit the new batch bounds
590 start = newStart;
591 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700592 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700593 }
594 return didRemove;
595 }
596
Christopher Tatee0a22b32013-07-11 14:43:13 -0700597 boolean hasPackage(final String packageName) {
598 final int N = alarms.size();
599 for (int i = 0; i < N; i++) {
600 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700601 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700602 return true;
603 }
604 }
605 return false;
606 }
607
608 boolean hasWakeups() {
609 final int N = alarms.size();
610 for (int i = 0; i < N; i++) {
611 Alarm a = alarms.get(i);
612 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
613 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
614 return true;
615 }
616 }
617 return false;
618 }
619
620 @Override
621 public String toString() {
622 StringBuilder b = new StringBuilder(40);
623 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
624 b.append(" num="); b.append(size());
625 b.append(" start="); b.append(start);
626 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700627 if (flags != 0) {
628 b.append(" flgs=0x");
629 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700630 }
631 b.append('}');
632 return b.toString();
633 }
Kweku Adams61e03292017-10-19 14:27:12 -0700634
635 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
636 long nowRTC) {
637 final long token = proto.start(fieldId);
638
639 proto.write(BatchProto.START_REALTIME, start);
640 proto.write(BatchProto.END_REALTIME, end);
641 proto.write(BatchProto.FLAGS, flags);
642 for (Alarm a : alarms) {
643 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
644 }
645
646 proto.end(token);
647 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700648 }
649
650 static class BatchTimeOrder implements Comparator<Batch> {
651 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800652 long when1 = b1.start;
653 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800654 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700655 return 1;
656 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800657 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700658 return -1;
659 }
660 return 0;
661 }
662 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800663
664 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
665 @Override
666 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700667 // priority class trumps everything. TICK < WAKEUP < NORMAL
668 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
669 return -1;
670 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
671 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800672 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700673
674 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800675 if (lhs.whenElapsed < rhs.whenElapsed) {
676 return -1;
677 } else if (lhs.whenElapsed > rhs.whenElapsed) {
678 return 1;
679 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700680
681 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800682 return 0;
683 }
684 };
685
Christopher Tate1590f1e2014-10-02 17:27:57 -0700686 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
687 final int N = alarms.size();
688 for (int i = 0; i < N; i++) {
689 Alarm a = alarms.get(i);
690
691 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700692 if (a.operation != null
693 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700694 alarmPrio = PRIO_TICK;
695 } else if (a.wakeup) {
696 alarmPrio = PRIO_WAKEUP;
697 } else {
698 alarmPrio = PRIO_NORMAL;
699 }
700
701 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800702 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700703 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700704 if (packagePrio == null) {
705 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700706 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700707 }
708 a.priorityClass = packagePrio;
709
710 if (packagePrio.seq != mCurrentSeq) {
711 // first alarm we've seen in the current delivery generation from this package
712 packagePrio.priority = alarmPrio;
713 packagePrio.seq = mCurrentSeq;
714 } else {
715 // Multiple alarms from this package being delivered in this generation;
716 // bump the package's delivery class if it's warranted.
717 // TICK < WAKEUP < NORMAL
718 if (alarmPrio < packagePrio.priority) {
719 packagePrio.priority = alarmPrio;
720 }
721 }
722 }
723 }
724
Christopher Tatee0a22b32013-07-11 14:43:13 -0700725 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800726 static final long MIN_FUZZABLE_INTERVAL = 10000;
727 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700728 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
729
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700730 // 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 -0700731 // to run during this time are placed in mPendingWhileIdleAlarms
732 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700733 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700734 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700735
Jeff Brownb880d882014-02-10 19:47:07 -0800736 public AlarmManagerService(Context context) {
737 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700738 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800739
Christopher Tate1d99c392017-12-07 16:54:04 -0800740 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800741 }
742
Christopher Tatee0a22b32013-07-11 14:43:13 -0700743 static long convertToElapsed(long when, int type) {
744 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
745 if (isRtc) {
746 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
747 }
748 return when;
749 }
750
751 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
752 // calculate the end of our nominal delivery window for the alarm.
753 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
754 // Current heuristic: batchable window is 75% of either the recurrence interval
755 // [for a periodic alarm] or of the time from now to the desired delivery time,
756 // with a minimum delay/interval of 10 seconds, under which we will simply not
757 // defer the alarm.
758 long futurity = (interval == 0)
759 ? (triggerAtTime - now)
760 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700761 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700762 futurity = 0;
763 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800764 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700765 }
766
767 // returns true if the batch was added at the head
768 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
769 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
770 if (index < 0) {
771 index = 0 - index - 1;
772 }
773 list.add(index, newBatch);
774 return (index == 0);
775 }
776
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800777 private void insertAndBatchAlarmLocked(Alarm alarm) {
778 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
779 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
780
781 if (whichBatch < 0) {
782 addBatchLocked(mAlarmBatches, new Batch(alarm));
783 } else {
784 final Batch batch = mAlarmBatches.get(whichBatch);
785 if (batch.add(alarm)) {
786 // The start time of this batch advanced, so batch ordering may
787 // have just been broken. Move it to where it now belongs.
788 mAlarmBatches.remove(whichBatch);
789 addBatchLocked(mAlarmBatches, batch);
790 }
791 }
792 }
793
Christopher Tate385e4982013-07-23 18:22:29 -0700794 // Return the index of the matching batch, or -1 if none found.
795 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700796 final int N = mAlarmBatches.size();
797 for (int i = 0; i < N; i++) {
798 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700799 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700800 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700801 }
802 }
Christopher Tate385e4982013-07-23 18:22:29 -0700803 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700804 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800805 /** @return total count of the alarms in a set of alarm batches. */
806 static int getAlarmCount(ArrayList<Batch> batches) {
807 int ret = 0;
808
809 final int size = batches.size();
810 for (int i = 0; i < size; i++) {
811 ret += batches.get(i).size();
812 }
813 return ret;
814 }
815
816 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
817 if (alarms.size() == 0) {
818 return false;
819 }
820 final int batchSize = alarms.size();
821 for (int j = 0; j < batchSize; j++) {
822 if (alarms.get(j).operation == mTimeTickSender) {
823 return true;
824 }
825 }
826 return false;
827 }
828
829 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
830 final int numBatches = batches.size();
831 for (int i = 0; i < numBatches; i++) {
832 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
833 return true;
834 }
835 }
836 return false;
837 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700838
839 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
840 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700841 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700842 rebatchAllAlarmsLocked(true);
843 }
844 }
845
846 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800847 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800848 final int oldCount =
849 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
850 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
851 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
852
Christopher Tate4cb338d2013-07-26 13:11:31 -0700853 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
854 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700855 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700856 final long nowElapsed = SystemClock.elapsedRealtime();
857 final int oldBatches = oldSet.size();
858 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
859 Batch batch = oldSet.get(batchNum);
860 final int N = batch.size();
861 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700862 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700863 }
864 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700865 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
866 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
867 + " to " + mPendingIdleUntil);
868 if (mPendingIdleUntil == null) {
869 // Somehow we lost this... we need to restore all of the pending alarms.
870 restorePendingWhileIdleAlarmsLocked();
871 }
872 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800873 final int newCount =
874 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
875 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
876 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
877
878 if (oldCount != newCount) {
879 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
880 }
881 if (oldHasTick != newHasTick) {
882 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
883 }
884
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700885 rescheduleKernelAlarmsLocked();
886 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800887 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700888 }
889
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800890 /**
891 * Re-orders the alarm batches based on newly evaluated send times based on the current
892 * app-standby buckets
893 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
894 * null indicates all
895 * @return True if there was any reordering done to the current list.
896 */
897 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
898 final long start = mStatLogger.getTime();
899 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
900
901 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
902 final Batch batch = mAlarmBatches.get(batchIndex);
903 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
904 final Alarm alarm = batch.get(alarmIndex);
905 final Pair<String, Integer> packageUser =
906 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
907 if (targetPackages != null && !targetPackages.contains(packageUser)) {
908 continue;
909 }
910 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
911 batch.remove(alarm);
912 rescheduledAlarms.add(alarm);
913 }
914 }
915 if (batch.size() == 0) {
916 mAlarmBatches.remove(batchIndex);
917 }
918 }
919 for (int i = 0; i < rescheduledAlarms.size(); i++) {
920 final Alarm a = rescheduledAlarms.get(i);
921 insertAndBatchAlarmLocked(a);
922 }
923
924 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
925 return rescheduledAlarms.size() > 0;
926 }
927
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700928 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
929 a.when = a.origWhen;
930 long whenElapsed = convertToElapsed(a.when, a.type);
931 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700932 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700933 // Exact
934 maxElapsed = whenElapsed;
935 } else {
936 // Not exact. Preserve any explicit window, otherwise recalculate
937 // the window based on the alarm's new futurity. Note that this
938 // reflects a policy of preferring timely to deferred delivery.
939 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800940 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700941 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
942 }
943 a.whenElapsed = whenElapsed;
944 a.maxWhenElapsed = maxElapsed;
945 setImplLocked(a, true, doValidate);
946 }
947
Christopher Tate22e919d2018-02-16 16:16:50 -0800948 static long clampPositive(long val) {
949 return (val >= 0) ? val : Long.MAX_VALUE;
950 }
951
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700952 /**
953 * Sends alarms that were blocked due to user applied background restrictions - either because
954 * the user lifted those or the uid came to foreground.
955 *
956 * @param uid uid to filter on
957 * @param packageName package to filter on, or null for all packages in uid
958 */
959 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
960 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
961 if (alarmsForUid == null || alarmsForUid.size() == 0) {
962 return;
963 }
964 final ArrayList<Alarm> alarmsToDeliver;
965 if (packageName != null) {
966 if (DEBUG_BG_LIMIT) {
967 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
968 }
969 alarmsToDeliver = new ArrayList<>();
970 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
971 final Alarm a = alarmsForUid.get(i);
972 if (a.matches(packageName)) {
973 alarmsToDeliver.add(alarmsForUid.remove(i));
974 }
975 }
976 if (alarmsForUid.size() == 0) {
977 mPendingBackgroundAlarms.remove(uid);
978 }
979 } else {
980 if (DEBUG_BG_LIMIT) {
981 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
982 }
983 alarmsToDeliver = alarmsForUid;
984 mPendingBackgroundAlarms.remove(uid);
985 }
986 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
987 }
988
Makoto Onuki2206af32017-11-21 16:25:35 -0800989 /**
990 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
991 * restricted.
992 *
993 * This is only called when the global "force all apps-standby" flag changes or when the
994 * power save whitelist changes, so it's okay to be slow.
995 */
996 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700997 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800998
999 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1000 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1001
1002 if (alarmsToDeliver.size() > 0) {
1003 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
1004 }
1005 }
1006
1007 @VisibleForTesting
1008 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1009 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1010 Predicate<Alarm> isBackgroundRestricted) {
1011
1012 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1013 final int uid = pendingAlarms.keyAt(uidIndex);
1014 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1015
1016 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1017 final Alarm alarm = alarmsForUid.get(alarmIndex);
1018
1019 if (isBackgroundRestricted.test(alarm)) {
1020 continue;
1021 }
1022
1023 unrestrictedAlarms.add(alarm);
1024 alarmsForUid.remove(alarmIndex);
1025 }
1026
1027 if (alarmsForUid.size() == 0) {
1028 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001029 }
1030 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001031 }
1032
1033 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1034 final int N = alarms.size();
1035 boolean hasWakeup = false;
1036 for (int i = 0; i < N; i++) {
1037 final Alarm alarm = alarms.get(i);
1038 if (alarm.wakeup) {
1039 hasWakeup = true;
1040 }
1041 alarm.count = 1;
1042 // Recurring alarms may have passed several alarm intervals while the
1043 // alarm was kept pending. Send the appropriate trigger count.
1044 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001045 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001046 // Also schedule its next recurrence
1047 final long delta = alarm.count * alarm.repeatInterval;
1048 final long nextElapsed = alarm.whenElapsed + delta;
1049 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1050 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1051 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1052 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1053 // Kernel alarms will be rescheduled as needed in setImplLocked
1054 }
1055 }
1056 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1057 // No need to wakeup for non wakeup alarms
1058 if (mPendingNonWakeupAlarms.size() == 0) {
1059 mStartCurrentDelayTime = nowELAPSED;
1060 mNextNonWakeupDeliveryTime = nowELAPSED
1061 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1062 }
1063 mPendingNonWakeupAlarms.addAll(alarms);
1064 mNumDelayedAlarms += alarms.size();
1065 } else {
1066 if (DEBUG_BG_LIMIT) {
1067 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1068 }
1069 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1070 if (mPendingNonWakeupAlarms.size() > 0) {
1071 alarms.addAll(mPendingNonWakeupAlarms);
1072 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1073 mTotalDelayTime += thisDelayTime;
1074 if (mMaxDelayTime < thisDelayTime) {
1075 mMaxDelayTime = thisDelayTime;
1076 }
1077 mPendingNonWakeupAlarms.clear();
1078 }
1079 calculateDeliveryPriorities(alarms);
1080 Collections.sort(alarms, mAlarmDispatchComparator);
1081 deliverAlarmsLocked(alarms, nowELAPSED);
1082 }
1083 }
1084
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001085 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001086 if (RECORD_DEVICE_IDLE_ALARMS) {
1087 IdleDispatchEntry ent = new IdleDispatchEntry();
1088 ent.uid = 0;
1089 ent.pkg = "FINISH IDLE";
1090 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1091 mAllowWhileIdleDispatches.add(ent);
1092 }
1093
Dianne Hackborn35d54032015-04-23 10:30:43 -07001094 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001095 if (mPendingWhileIdleAlarms.size() > 0) {
1096 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1097 mPendingWhileIdleAlarms = new ArrayList<>();
1098 final long nowElapsed = SystemClock.elapsedRealtime();
1099 for (int i=alarms.size() - 1; i >= 0; i--) {
1100 Alarm a = alarms.get(i);
1101 reAddAlarmLocked(a, nowElapsed, false);
1102 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001103 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001104
1105 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001106 rescheduleKernelAlarmsLocked();
1107 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001108
1109 // And send a TIME_TICK right now, since it is important to get the UI updated.
1110 try {
1111 mTimeTickSender.send();
1112 } catch (PendingIntent.CanceledException e) {
1113 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001114 }
1115
Christopher Tate14a7bb02015-10-01 10:24:31 -07001116 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001117 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001118 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001119 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001120 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001121 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001122 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001123 final BroadcastStats mBroadcastStats;
1124 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001125 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001126
Christopher Tate14a7bb02015-10-01 10:24:31 -07001127 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1128 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1129 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001130 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001131 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001132 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001133 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001134 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001135 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001136 mBroadcastStats = (pendingIntent != null)
1137 ? service.getStatsLocked(pendingIntent)
1138 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001139 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001140 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001141 fs = new FilterStats(mBroadcastStats, mTag);
1142 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001143 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001144 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001145 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001146 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001147 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001148
1149 @Override
1150 public String toString() {
1151 return "InFlight{"
1152 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001153 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001154 + ", workSource=" + mWorkSource
1155 + ", uid=" + mUid
1156 + ", tag=" + mTag
1157 + ", broadcastStats=" + mBroadcastStats
1158 + ", filterStats=" + mFilterStats
1159 + ", alarmType=" + mAlarmType
1160 + "}";
1161 }
Kweku Adams61e03292017-10-19 14:27:12 -07001162
1163 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1164 final long token = proto.start(fieldId);
1165
1166 proto.write(InFlightProto.UID, mUid);
1167 proto.write(InFlightProto.TAG, mTag);
1168 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1169 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1170 if (mPendingIntent != null) {
1171 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1172 }
1173 if (mBroadcastStats != null) {
1174 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1175 }
1176 if (mFilterStats != null) {
1177 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1178 }
1179 if (mWorkSource != null) {
1180 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1181 }
1182
1183 proto.end(token);
1184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001186
Adam Lesinski182f73f2013-12-05 16:48:06 -08001187 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001188 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001189 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001190
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001191 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001193 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001194 int numWakeup;
1195 long startTime;
1196 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001197
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001198 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001199 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001200 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001201 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001202
1203 @Override
1204 public String toString() {
1205 return "FilterStats{"
1206 + "tag=" + mTag
1207 + ", lastTime=" + lastTime
1208 + ", aggregateTime=" + aggregateTime
1209 + ", count=" + count
1210 + ", numWakeup=" + numWakeup
1211 + ", startTime=" + startTime
1212 + ", nesting=" + nesting
1213 + "}";
1214 }
Kweku Adams61e03292017-10-19 14:27:12 -07001215
1216 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1217 final long token = proto.start(fieldId);
1218
1219 proto.write(FilterStatsProto.TAG, mTag);
1220 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1221 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1222 proto.write(FilterStatsProto.COUNT, count);
1223 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1224 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1225 proto.write(FilterStatsProto.NESTING, nesting);
1226
1227 proto.end(token);
1228 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001229 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001230
Adam Lesinski182f73f2013-12-05 16:48:06 -08001231 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001232 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001233 final String mPackageName;
1234
1235 long aggregateTime;
1236 int count;
1237 int numWakeup;
1238 long startTime;
1239 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001240 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001241
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001242 BroadcastStats(int uid, String packageName) {
1243 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001244 mPackageName = packageName;
1245 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001246
1247 @Override
1248 public String toString() {
1249 return "BroadcastStats{"
1250 + "uid=" + mUid
1251 + ", packageName=" + mPackageName
1252 + ", aggregateTime=" + aggregateTime
1253 + ", count=" + count
1254 + ", numWakeup=" + numWakeup
1255 + ", startTime=" + startTime
1256 + ", nesting=" + nesting
1257 + "}";
1258 }
Kweku Adams61e03292017-10-19 14:27:12 -07001259
1260 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1261 final long token = proto.start(fieldId);
1262
1263 proto.write(BroadcastStatsProto.UID, mUid);
1264 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1265 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1266 proto.write(BroadcastStatsProto.COUNT, count);
1267 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1268 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1269 proto.write(BroadcastStatsProto.NESTING, nesting);
1270
1271 proto.end(token);
1272 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001274
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001275 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1276 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001277
1278 int mNumDelayedAlarms = 0;
1279 long mTotalDelayTime = 0;
1280 long mMaxDelayTime = 0;
1281
Adam Lesinski182f73f2013-12-05 16:48:06 -08001282 @Override
1283 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001284 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001285 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001286
1287 // We have to set current TimeZone info to kernel
1288 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001289 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001290
Christopher Tate247571462017-04-10 11:45:05 -07001291 // Also sure that we're booting with a halfway sensible current time
1292 if (mNativeData != 0) {
1293 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1294 if (System.currentTimeMillis() < systemBuildTime) {
1295 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1296 + ", advancing to build time " + systemBuildTime);
1297 setKernelTime(mNativeData, systemBuildTime);
1298 }
1299 }
1300
Christopher Tatebb9cce52017-04-18 14:19:43 -07001301 // Determine SysUI's uid
1302 final PackageManager packMan = getContext().getPackageManager();
1303 try {
1304 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1305 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1306 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1307 mSystemUiUid = sysUi.uid;
1308 } else {
1309 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1310 + " defined by non-privileged app " + sysUi.packageName
1311 + " - ignoring");
1312 }
1313 } catch (NameNotFoundException e) {
1314 }
1315
1316 if (mSystemUiUid <= 0) {
1317 Slog.wtf(TAG, "SysUI package not found!");
1318 }
1319
Adam Lesinski182f73f2013-12-05 16:48:06 -08001320 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001321 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001322
Adam Lesinski182f73f2013-12-05 16:48:06 -08001323 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001325 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001326 | Intent.FLAG_RECEIVER_FOREGROUND
1327 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001328 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001329 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001330 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1331 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001332 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001333 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001334
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001336 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001337 mClockReceiver.scheduleTimeTickEvent();
1338 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001339 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001341
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001342 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001343 AlarmThread waitThread = new AlarmThread();
1344 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001346 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001347 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001348
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001349 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001350 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001351 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1352 | ActivityManager.UID_OBSERVER_ACTIVE,
1353 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001354 } catch (RemoteException e) {
1355 // ignored; both services live in system_server
1356 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001357 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001359
1360 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001361 public void onBootPhase(int phase) {
1362 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1363 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001364 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001365 mLocalDeviceIdleController
1366 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001367 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1368 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001369
1370 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1371 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001372 }
1373 }
1374
1375 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 protected void finalize() throws Throwable {
1377 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001378 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 } finally {
1380 super.finalize();
1381 }
1382 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001383
mswest463f4c99d2018-02-01 10:13:10 -08001384 boolean setTimeImpl(long millis) {
1385 if (mNativeData == 0) {
1386 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1387 return false;
1388 }
1389
1390 synchronized (mLock) {
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001391 final long currentTimeMillis = System.currentTimeMillis();
1392 setKernelTime(mNativeData, millis);
1393 final TimeZone timeZone = TimeZone.getDefault();
1394 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1395 final int newTzOffset = timeZone.getOffset(millis);
1396 if (currentTzOffset != newTzOffset) {
1397 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
1398 setKernelTimezone(mNativeData, -(newTzOffset / 60000));
1399 }
1400 // The native implementation of setKernelTime can return -1 even when the kernel
1401 // time was set correctly, so assume setting kernel time was successful and always
1402 // return true.
1403 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001404 }
1405 }
1406
Adam Lesinski182f73f2013-12-05 16:48:06 -08001407 void setTimeZoneImpl(String tz) {
1408 if (TextUtils.isEmpty(tz)) {
1409 return;
David Christieebe51fc2013-07-26 13:23:29 -07001410 }
1411
Adam Lesinski182f73f2013-12-05 16:48:06 -08001412 TimeZone zone = TimeZone.getTimeZone(tz);
1413 // Prevent reentrant calls from stepping on each other when writing
1414 // the time zone property
1415 boolean timeZoneWasChanged = false;
1416 synchronized (this) {
1417 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1418 if (current == null || !current.equals(zone.getID())) {
1419 if (localLOGV) {
1420 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1421 }
1422 timeZoneWasChanged = true;
1423 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1424 }
1425
1426 // Update the kernel timezone information
1427 // Kernel tracks time offsets as 'minutes west of GMT'
1428 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001429 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001430 }
1431
1432 TimeZone.setDefault(null);
1433
1434 if (timeZoneWasChanged) {
1435 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001436 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001437 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001438 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001439 intent.putExtra("time-zone", zone.getID());
1440 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1441 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001443
Adam Lesinski182f73f2013-12-05 16:48:06 -08001444 void removeImpl(PendingIntent operation) {
1445 if (operation == null) {
1446 return;
1447 }
1448 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001449 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001450 }
1451 }
1452
1453 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001454 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1455 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1456 int callingUid, String callingPackage) {
1457 // must be *either* PendingIntent or AlarmReceiver, but not both
1458 if ((operation == null && directReceiver == null)
1459 || (operation != null && directReceiver != null)) {
1460 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1461 // NB: previous releases failed silently here, so we are continuing to do the same
1462 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 return;
1464 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001465
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001466 // Sanity check the window length. This will catch people mistakenly
1467 // trying to pass an end-of-window timestamp rather than a duration.
1468 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1469 Slog.w(TAG, "Window length " + windowLength
1470 + "ms suspiciously long; limiting to 1 hour");
1471 windowLength = AlarmManager.INTERVAL_HOUR;
1472 }
1473
Christopher Tate498c6cb2014-11-17 16:09:27 -08001474 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001475 // seconds when the API expects milliseconds, or apps trying shenanigans
1476 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001477 final long minInterval = mConstants.MIN_INTERVAL;
1478 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001479 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001480 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001481 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001482 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001483 } else if (interval > mConstants.MAX_INTERVAL) {
1484 Slog.w(TAG, "Suspiciously long interval " + interval
1485 + " millis; clamping");
1486 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001487 }
1488
Christopher Tatee0a22b32013-07-11 14:43:13 -07001489 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1490 throw new IllegalArgumentException("Invalid alarm type " + type);
1491 }
1492
Christopher Tate5f221e82013-07-30 17:13:15 -07001493 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001494 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001495 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001496 + " pid=" + what);
1497 triggerAtTime = 0;
1498 }
1499
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001500 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001501 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1502 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001503 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001504 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1505
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001506 final long maxElapsed;
1507 if (windowLength == AlarmManager.WINDOW_EXACT) {
1508 maxElapsed = triggerElapsed;
1509 } else if (windowLength < 0) {
1510 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001511 // Fix this window in place, so that as time approaches we don't collapse it.
1512 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001513 } else {
1514 maxElapsed = triggerElapsed + windowLength;
1515 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001516
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001518 if (DEBUG_BATCH) {
1519 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001520 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001521 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001522 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001523 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001524 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001525 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1526 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001527 }
1528 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001529
Christopher Tate3e04b472013-10-21 17:51:31 -07001530 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001531 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1532 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1533 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001534 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001535 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1536 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001537 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001538 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001539 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1540 + " -- package not allowed to start");
1541 return;
1542 }
1543 } catch (RemoteException e) {
1544 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001545 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001546 setImplLocked(a, false, doValidate);
1547 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001548
Christopher Tatef2159712018-03-27 16:04:14 -07001549 /**
1550 * Return the minimum time that should elapse before an app in the specified bucket
1551 * can receive alarms again
1552 */
Suprabh Shukla75edab12018-01-29 14:09:06 -08001553 private long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001554 // UsageStats bucket values are treated as floors of their behavioral range.
1555 // In other words, a bucket value between WORKING and ACTIVE is treated as
1556 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1557 // values.
1558 final int index;
1559
1560 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1561 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1562 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1563 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1564 else index = ACTIVE_INDEX;
1565
1566 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001567 }
1568
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001569 /**
1570 * Adjusts the alarm delivery time based on the current app standby bucket.
1571 * @param alarm The alarm to adjust
1572 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001573 */
1574 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001575 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001576 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001577 }
1578 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001579 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001580 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001581 alarm.whenElapsed = alarm.expectedWhenElapsed;
1582 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1583 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001584 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001585 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001586 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001587 final long oldWhenElapsed = alarm.whenElapsed;
1588 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1589
Suprabh Shukla75edab12018-01-29 14:09:06 -08001590 final String sourcePackage = alarm.sourcePackage;
1591 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1592 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1593 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1594
1595 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1596 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1597 if (lastElapsed > 0) {
1598 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001599 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001600 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001601 } else {
1602 // app is now eligible to run alarms at the originally requested window.
1603 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001604 alarm.whenElapsed = alarm.expectedWhenElapsed;
1605 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001606 }
1607 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001608 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001609 }
1610
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001611 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1612 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001613 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001614 // The caller has given the time they want this to happen at, however we need
1615 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001616 // bring us out of idle at an earlier time.
1617 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001618 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001619 }
1620 // Add fuzz to make the alarm go off some time before the actual desired time.
1621 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001622 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001623 if (fuzz > 0) {
1624 if (mRandom == null) {
1625 mRandom = new Random();
1626 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001627 final int delta = mRandom.nextInt(fuzz);
1628 a.whenElapsed -= delta;
1629 if (false) {
1630 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1631 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1632 Slog.d(TAG, "Applied fuzz: " + fuzz);
1633 Slog.d(TAG, "Final delta: " + delta);
1634 Slog.d(TAG, "Final when: " + a.whenElapsed);
1635 }
1636 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001637 }
1638
1639 } else if (mPendingIdleUntil != null) {
1640 // We currently have an idle until alarm scheduled; if the new alarm has
1641 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001642 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1643 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1644 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001645 == 0) {
1646 mPendingWhileIdleAlarms.add(a);
1647 return;
1648 }
1649 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001650 if (RECORD_DEVICE_IDLE_ALARMS) {
1651 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1652 IdleDispatchEntry ent = new IdleDispatchEntry();
1653 ent.uid = a.uid;
1654 ent.pkg = a.operation.getCreatorPackage();
1655 ent.tag = a.operation.getTag("");
1656 ent.op = "SET";
1657 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1658 ent.argRealtime = a.whenElapsed;
1659 mAllowWhileIdleDispatches.add(ent);
1660 }
1661 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001662 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001663 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001664
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001665 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001666 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001667 }
1668
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001669 boolean needRebatch = false;
1670
1671 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001672 if (RECORD_DEVICE_IDLE_ALARMS) {
1673 if (mPendingIdleUntil == null) {
1674 IdleDispatchEntry ent = new IdleDispatchEntry();
1675 ent.uid = 0;
1676 ent.pkg = "START IDLE";
1677 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1678 mAllowWhileIdleDispatches.add(ent);
1679 }
1680 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001681 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1682 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1683 + " to " + a);
1684 }
1685
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001686 mPendingIdleUntil = a;
1687 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001688 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1689 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1690 mNextWakeFromIdle = a;
1691 // If this wake from idle is earlier than whatever was previously scheduled,
1692 // and we are currently idling, then we need to rebatch alarms in case the idle
1693 // until time needs to be updated.
1694 if (mPendingIdleUntil != null) {
1695 needRebatch = true;
1696 }
1697 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001698 }
1699
1700 if (!rebatching) {
1701 if (DEBUG_VALIDATE) {
1702 if (doValidate && !validateConsistencyLocked()) {
1703 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1704 + " when(hex)=" + Long.toHexString(a.when)
1705 + " whenElapsed=" + a.whenElapsed
1706 + " maxWhenElapsed=" + a.maxWhenElapsed
1707 + " interval=" + a.repeatInterval + " op=" + a.operation
1708 + " flags=0x" + Integer.toHexString(a.flags));
1709 rebatchAllAlarmsLocked(false);
1710 needRebatch = false;
1711 }
1712 }
1713
1714 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001715 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001716 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001717
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001718 rescheduleKernelAlarmsLocked();
1719 updateNextAlarmClockLocked();
1720 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001721 }
1722
Christopher Tate1d99c392017-12-07 16:54:04 -08001723 /**
1724 * System-process internal API
1725 */
1726 private final class LocalService implements AlarmManagerInternal {
1727 @Override
1728 public void removeAlarmsForUid(int uid) {
1729 synchronized (mLock) {
1730 removeLocked(uid);
1731 }
1732 }
1733 }
1734
1735 /**
1736 * Public-facing binder interface
1737 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001738 private final IBinder mService = new IAlarmManager.Stub() {
1739 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001740 public void set(String callingPackage,
1741 int type, long triggerAtTime, long windowLength, long interval, int flags,
1742 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1743 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001744 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001745
1746 // make sure the caller is not lying about which package should be blamed for
1747 // wakelock time spent in alarm delivery
1748 mAppOps.checkPackage(callingUid, callingPackage);
1749
1750 // Repeating alarms must use PendingIntent, not direct listener
1751 if (interval != 0) {
1752 if (directReceiver != null) {
1753 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1754 }
1755 }
1756
Adam Lesinski182f73f2013-12-05 16:48:06 -08001757 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001758 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001759 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001760 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001761 }
1762
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001763 // No incoming callers can request either WAKE_FROM_IDLE or
1764 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1765 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1766 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1767
1768 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1769 // manager when to come out of idle mode, which is only for DeviceIdleController.
1770 if (callingUid != Process.SYSTEM_UID) {
1771 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1772 }
1773
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001774 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001775 if (windowLength == AlarmManager.WINDOW_EXACT) {
1776 flags |= AlarmManager.FLAG_STANDALONE;
1777 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001778
1779 // If this alarm is for an alarm clock, then it must be standalone and we will
1780 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001781 if (alarmClock != null) {
1782 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001783
1784 // If the caller is a core system component or on the user's whitelist, and not calling
1785 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1786 // This means we will allow these alarms to go off as normal even while idle, with no
1787 // timing restrictions.
1788 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001789 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001790 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001791 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001792 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1793 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001794 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001795
Christopher Tate14a7bb02015-10-01 10:24:31 -07001796 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1797 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001798 }
Christopher Tate89779822012-08-31 14:40:03 -07001799
Adam Lesinski182f73f2013-12-05 16:48:06 -08001800 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001801 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001802 getContext().enforceCallingOrSelfPermission(
1803 "android.permission.SET_TIME",
1804 "setTime");
1805
mswest463f4c99d2018-02-01 10:13:10 -08001806 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001808
1809 @Override
1810 public void setTimeZone(String tz) {
1811 getContext().enforceCallingOrSelfPermission(
1812 "android.permission.SET_TIME_ZONE",
1813 "setTimeZone");
1814
1815 final long oldId = Binder.clearCallingIdentity();
1816 try {
1817 setTimeZoneImpl(tz);
1818 } finally {
1819 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001822
Adam Lesinski182f73f2013-12-05 16:48:06 -08001823 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001824 public void remove(PendingIntent operation, IAlarmListener listener) {
1825 if (operation == null && listener == null) {
1826 Slog.w(TAG, "remove() with no intent or listener");
1827 return;
1828 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001829
Christopher Tate14a7bb02015-10-01 10:24:31 -07001830 synchronized (mLock) {
1831 removeLocked(operation, listener);
1832 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001833 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001834
Adam Lesinski182f73f2013-12-05 16:48:06 -08001835 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001836 public long getNextWakeFromIdleTime() {
1837 return getNextWakeFromIdleTimeImpl();
1838 }
1839
1840 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001841 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001842 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1843 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1844 "getNextAlarmClock", null);
1845
1846 return getNextAlarmClockImpl(userId);
1847 }
1848
1849 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001850 public long currentNetworkTimeMillis() {
1851 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1852 if (time.hasCache()) {
1853 return time.currentTimeMillis();
1854 } else {
1855 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1856 }
1857 }
1858
1859 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001860 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001861 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001862
1863 if (args.length > 0 && "--proto".equals(args[0])) {
1864 dumpProto(fd);
1865 } else {
1866 dumpImpl(pw);
1867 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001868 }
mswest463f4c99d2018-02-01 10:13:10 -08001869
1870 @Override
1871 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1872 FileDescriptor err, String[] args, ShellCallback callback,
1873 ResultReceiver resultReceiver) {
1874 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1875 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001876 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001877
Adam Lesinski182f73f2013-12-05 16:48:06 -08001878 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 synchronized (mLock) {
1880 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001881 mConstants.dump(pw);
1882 pw.println();
1883
Makoto Onukie4918212018-02-06 11:30:15 -08001884 if (mAppStateTracker != null) {
1885 mAppStateTracker.dump(pw, " ");
1886 pw.println();
1887 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001888
Suprabh Shukla75edab12018-01-29 14:09:06 -08001889 pw.println(" App Standby Parole: " + mAppStandbyParole);
1890 pw.println();
1891
Christopher Tatee0a22b32013-07-11 14:43:13 -07001892 final long nowRTC = System.currentTimeMillis();
1893 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001894 final long nowUPTIME = SystemClock.uptimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001895 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001896
Dianne Hackborna750a632015-06-16 17:18:23 -07001897 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001898 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001899 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001900 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001901 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001902 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001903 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1904 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001905 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001906 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1907 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001908 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1909 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001910
1911 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1912 if (ssm != null) {
1913 pw.println();
1914 pw.print(" RuntimeStarted=");
1915 pw.print(sdf.format(
1916 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1917 if (ssm.isRuntimeRestarted()) {
1918 pw.print(" (Runtime restarted)");
1919 }
1920 pw.println();
1921 pw.print(" Runtime uptime (elapsed): ");
1922 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1923 pw.println();
1924 pw.print(" Runtime uptime (uptime): ");
1925 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1926 pw.println();
1927 }
1928
Dianne Hackbornc3527222015-05-13 14:03:20 -07001929 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001930 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001931 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001932 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1933 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001934 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001935 pw.print(" Max wakeup delay: ");
1936 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1937 pw.println();
1938 pw.print(" Time since last dispatch: ");
1939 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1940 pw.println();
1941 pw.print(" Next non-wakeup delivery time: ");
1942 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1943 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001944
1945 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1946 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001947 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001948 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001949 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001950 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001951 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1952 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001953 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001954 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1955 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07001956
1957 pw.print(" Next kernel non-wakeup alarm: ");
1958 TimeUtils.formatDuration(getNextAlarm(mNativeData, ELAPSED_REALTIME), pw);
1959 pw.println();
1960 pw.print(" Next kernel wakeup alarm: ");
1961 TimeUtils.formatDuration(getNextAlarm(mNativeData, ELAPSED_REALTIME_WAKEUP), pw);
1962 pw.println();
1963
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001964 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001965 pw.print(" = "); pw.println(mLastWakeup);
1966 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1967 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001968 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001969
John Spurlock604a5ee2015-06-01 12:27:22 -04001970 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001971 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001972 final TreeSet<Integer> users = new TreeSet<>();
1973 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1974 users.add(mNextAlarmClockForUser.keyAt(i));
1975 }
1976 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1977 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1978 }
1979 for (int user : users) {
1980 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1981 final long time = next != null ? next.getTriggerTime() : 0;
1982 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001983 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001984 pw.print(" pendingSend:"); pw.print(pendingSend);
1985 pw.print(" time:"); pw.print(time);
1986 if (time > 0) {
1987 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1988 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1989 }
1990 pw.println();
1991 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001992 if (mAlarmBatches.size() > 0) {
1993 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001994 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001995 pw.println(mAlarmBatches.size());
1996 for (Batch b : mAlarmBatches) {
1997 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001998 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001999 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002000 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002001 pw.println();
2002 pw.println(" Pending user blocked background alarms: ");
2003 boolean blocked = false;
2004 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2005 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2006 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2007 blocked = true;
2008 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2009 }
2010 }
2011 if (!blocked) {
2012 pw.println(" none");
2013 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002014
Suprabh Shukla75edab12018-01-29 14:09:06 -08002015 pw.println(" mLastAlarmDeliveredForPackage:");
2016 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2017 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2018 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2019 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2020 pw.println();
2021 }
2022 pw.println();
2023
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002024 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002025 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002026 pw.println(" Idle mode state:");
2027 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002028 if (mPendingIdleUntil != null) {
2029 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002030 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002031 } else {
2032 pw.println("null");
2033 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002034 pw.println(" Pending alarms:");
2035 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002036 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002037 if (mNextWakeFromIdle != null) {
2038 pw.println();
2039 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002040 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002041 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002042
2043 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002044 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002045 if (mPendingNonWakeupAlarms.size() > 0) {
2046 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002047 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002048 } else {
2049 pw.println("(none)");
2050 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002051 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002052 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2053 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002054 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002055 pw.print(", max non-interactive time: ");
2056 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2057 pw.println();
2058
2059 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002060 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002061 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2062 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2063 pw.print(" Listener send count: "); pw.println(mListenerCount);
2064 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002065 pw.println();
2066
Christopher Tate7f2a0352015-12-08 10:24:33 -08002067 if (mInFlight.size() > 0) {
2068 pw.println("Outstanding deliveries:");
2069 for (int i = 0; i < mInFlight.size(); i++) {
2070 pw.print(" #"); pw.print(i); pw.print(": ");
2071 pw.println(mInFlight.get(i));
2072 }
2073 pw.println();
2074 }
2075
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002076 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002077 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002078 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002079 pw.print(" UID ");
2080 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2081 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002082 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002083 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2084 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2085
2086 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2087 pw.print(" Next allowed:");
2088 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2089 pw.print(" (");
2090 TimeUtils.formatDuration(minInterval, 0, pw);
2091 pw.print(")");
2092
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002093 pw.println();
2094 }
2095 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002096
2097 pw.print(" mUseAllowWhileIdleShortTime: [");
2098 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2099 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2100 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2101 pw.print(" ");
2102 }
2103 }
2104 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002105 pw.println();
2106
Dianne Hackborn81038902012-11-26 17:04:09 -08002107 if (mLog.dump(pw, " Recent problems", " ")) {
2108 pw.println();
2109 }
2110
2111 final FilterStats[] topFilters = new FilterStats[10];
2112 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2113 @Override
2114 public int compare(FilterStats lhs, FilterStats rhs) {
2115 if (lhs.aggregateTime < rhs.aggregateTime) {
2116 return 1;
2117 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2118 return -1;
2119 }
2120 return 0;
2121 }
2122 };
2123 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002124 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002125 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2126 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2127 for (int ip=0; ip<uidStats.size(); ip++) {
2128 BroadcastStats bs = uidStats.valueAt(ip);
2129 for (int is=0; is<bs.filterStats.size(); is++) {
2130 FilterStats fs = bs.filterStats.valueAt(is);
2131 int pos = len > 0
2132 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2133 if (pos < 0) {
2134 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002135 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002136 if (pos < topFilters.length) {
2137 int copylen = topFilters.length - pos - 1;
2138 if (copylen > 0) {
2139 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2140 }
2141 topFilters[pos] = fs;
2142 if (len < topFilters.length) {
2143 len++;
2144 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002145 }
2146 }
2147 }
2148 }
2149 if (len > 0) {
2150 pw.println(" Top Alarms:");
2151 for (int i=0; i<len; i++) {
2152 FilterStats fs = topFilters[i];
2153 pw.print(" ");
2154 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2155 TimeUtils.formatDuration(fs.aggregateTime, pw);
2156 pw.print(" running, "); pw.print(fs.numWakeup);
2157 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002158 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2159 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002160 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002161 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002162 pw.println();
2163 }
2164 }
2165
2166 pw.println(" ");
2167 pw.println(" Alarm Stats:");
2168 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002169 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2170 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2171 for (int ip=0; ip<uidStats.size(); ip++) {
2172 BroadcastStats bs = uidStats.valueAt(ip);
2173 pw.print(" ");
2174 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2175 UserHandle.formatUid(pw, bs.mUid);
2176 pw.print(":");
2177 pw.print(bs.mPackageName);
2178 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2179 pw.print(" running, "); pw.print(bs.numWakeup);
2180 pw.println(" wakeups:");
2181 tmpFilters.clear();
2182 for (int is=0; is<bs.filterStats.size(); is++) {
2183 tmpFilters.add(bs.filterStats.valueAt(is));
2184 }
2185 Collections.sort(tmpFilters, comparator);
2186 for (int i=0; i<tmpFilters.size(); i++) {
2187 FilterStats fs = tmpFilters.get(i);
2188 pw.print(" ");
2189 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2190 TimeUtils.formatDuration(fs.aggregateTime, pw);
2191 pw.print(" "); pw.print(fs.numWakeup);
2192 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002193 pw.print(" alarms, last ");
2194 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2195 pw.println(":");
2196 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002197 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002198 pw.println();
2199 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002200 }
2201 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002202 pw.println();
2203 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002204
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002205 if (RECORD_DEVICE_IDLE_ALARMS) {
2206 pw.println();
2207 pw.println(" Allow while idle dispatches:");
2208 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2209 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2210 pw.print(" ");
2211 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2212 pw.print(": ");
2213 UserHandle.formatUid(pw, ent.uid);
2214 pw.print(":");
2215 pw.println(ent.pkg);
2216 if (ent.op != null) {
2217 pw.print(" ");
2218 pw.print(ent.op);
2219 pw.print(" / ");
2220 pw.print(ent.tag);
2221 if (ent.argRealtime != 0) {
2222 pw.print(" (");
2223 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2224 pw.print(")");
2225 }
2226 pw.println();
2227 }
2228 }
2229 }
2230
Christopher Tate18a75f12013-07-01 18:18:59 -07002231 if (WAKEUP_STATS) {
2232 pw.println();
2233 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002234 long last = -1;
2235 for (WakeupEvent event : mRecentWakeups) {
2236 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2237 pw.print('|');
2238 if (last < 0) {
2239 pw.print('0');
2240 } else {
2241 pw.print(event.when - last);
2242 }
2243 last = event.when;
2244 pw.print('|'); pw.print(event.uid);
2245 pw.print('|'); pw.print(event.action);
2246 pw.println();
2247 }
2248 pw.println();
2249 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002250 }
2251 }
2252
Kweku Adams61e03292017-10-19 14:27:12 -07002253 void dumpProto(FileDescriptor fd) {
2254 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2255
2256 synchronized (mLock) {
2257 final long nowRTC = System.currentTimeMillis();
2258 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002259 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2260 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2261 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002262 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002263 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002264 mLastTimeChangeRealtime);
2265
Yi Jin2b30f322018-02-20 15:41:47 -08002266 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002267
Makoto Onukie4918212018-02-06 11:30:15 -08002268 if (mAppStateTracker != null) {
2269 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002270 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002271 }
Kweku Adams61e03292017-10-19 14:27:12 -07002272
Yi Jin2b30f322018-02-20 15:41:47 -08002273 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002274 if (!mInteractive) {
2275 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002276 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002277 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002278 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002279 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002280 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002281 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002282 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002283 nowElapsed - mNextNonWakeupDeliveryTime);
2284 }
2285
Yi Jin2b30f322018-02-20 15:41:47 -08002286 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002287 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002288 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002289 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002290 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002291 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002292 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002293 nowElapsed - mLastWakeupSet);
Yi Jin2b30f322018-02-20 15:41:47 -08002294 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002295
2296 final TreeSet<Integer> users = new TreeSet<>();
2297 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2298 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2299 users.add(mNextAlarmClockForUser.keyAt(i));
2300 }
2301 final int pendingSendNextAlarmClockChangedForUserSize =
2302 mPendingSendNextAlarmClockChangedForUser.size();
2303 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2304 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2305 }
2306 for (int user : users) {
2307 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2308 final long time = next != null ? next.getTriggerTime() : 0;
2309 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002310 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002311 proto.write(AlarmClockMetadataProto.USER, user);
2312 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2313 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2314 proto.end(aToken);
2315 }
2316 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002317 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002318 nowElapsed, nowRTC);
2319 }
2320 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2321 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2322 if (blockedAlarms != null) {
2323 for (Alarm a : blockedAlarms) {
2324 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002325 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002326 nowElapsed, nowRTC);
2327 }
2328 }
2329 }
2330 if (mPendingIdleUntil != null) {
2331 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002332 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002333 }
2334 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002335 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002336 nowElapsed, nowRTC);
2337 }
2338 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002339 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002340 nowElapsed, nowRTC);
2341 }
2342
2343 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002344 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002345 nowElapsed, nowRTC);
2346 }
2347
Yi Jin2b30f322018-02-20 15:41:47 -08002348 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2349 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2350 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2351 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002352 mNonInteractiveTime);
2353
Yi Jin2b30f322018-02-20 15:41:47 -08002354 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2355 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2356 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2357 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2358 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002359
2360 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002361 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002362 }
2363
Kweku Adams61e03292017-10-19 14:27:12 -07002364 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2365 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002366 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002367 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2368 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2369
Yi Jin2b30f322018-02-20 15:41:47 -08002370 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2371 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2372 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002373 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002374 proto.end(token);
2375 }
2376
Makoto Onukiadb50d82018-01-29 16:20:30 -08002377 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2378 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002379 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002380 mUseAllowWhileIdleShortTime.keyAt(i));
2381 }
2382 }
2383
Yi Jin2b30f322018-02-20 15:41:47 -08002384 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002385
2386 final FilterStats[] topFilters = new FilterStats[10];
2387 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2388 @Override
2389 public int compare(FilterStats lhs, FilterStats rhs) {
2390 if (lhs.aggregateTime < rhs.aggregateTime) {
2391 return 1;
2392 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2393 return -1;
2394 }
2395 return 0;
2396 }
2397 };
2398 int len = 0;
2399 // Get the top 10 FilterStats, ordered by aggregateTime.
2400 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2401 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2402 for (int ip = 0; ip < uidStats.size(); ++ip) {
2403 BroadcastStats bs = uidStats.valueAt(ip);
2404 for (int is = 0; is < bs.filterStats.size(); ++is) {
2405 FilterStats fs = bs.filterStats.valueAt(is);
2406 int pos = len > 0
2407 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2408 if (pos < 0) {
2409 pos = -pos - 1;
2410 }
2411 if (pos < topFilters.length) {
2412 int copylen = topFilters.length - pos - 1;
2413 if (copylen > 0) {
2414 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2415 }
2416 topFilters[pos] = fs;
2417 if (len < topFilters.length) {
2418 len++;
2419 }
2420 }
2421 }
2422 }
2423 }
2424 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002425 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002426 FilterStats fs = topFilters[i];
2427
Yi Jin2b30f322018-02-20 15:41:47 -08002428 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2429 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002430 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002431 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002432
2433 proto.end(token);
2434 }
2435
2436 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2437 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2438 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2439 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002440 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002441
2442 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002443 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002444
2445 // uidStats is an ArrayMap, which we can't sort.
2446 tmpFilters.clear();
2447 for (int is = 0; is < bs.filterStats.size(); ++is) {
2448 tmpFilters.add(bs.filterStats.valueAt(is));
2449 }
2450 Collections.sort(tmpFilters, comparator);
2451 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002452 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002453 }
2454
2455 proto.end(token);
2456 }
2457 }
2458
2459 if (RECORD_DEVICE_IDLE_ALARMS) {
2460 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2461 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2462 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002463 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002464
2465 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2466 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2467 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2468 proto.write(IdleDispatchEntryProto.OP, ent.op);
2469 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2470 ent.elapsedRealtime);
2471 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2472
2473 proto.end(token);
2474 }
2475 }
2476
2477 if (WAKEUP_STATS) {
2478 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002479 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002480 proto.write(WakeupEventProto.UID, event.uid);
2481 proto.write(WakeupEventProto.ACTION, event.action);
2482 proto.write(WakeupEventProto.WHEN, event.when);
2483 proto.end(token);
2484 }
2485 }
2486 }
2487
2488 proto.flush();
2489 }
2490
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002491 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002492 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2493 PrintWriter pw = new PrintWriter(bs);
2494 final long nowRTC = System.currentTimeMillis();
2495 final long nowELAPSED = SystemClock.elapsedRealtime();
2496 final int NZ = mAlarmBatches.size();
2497 for (int iz = 0; iz < NZ; iz++) {
2498 Batch bz = mAlarmBatches.get(iz);
2499 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002500 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002501 pw.flush();
2502 Slog.v(TAG, bs.toString());
2503 bs.reset();
2504 }
2505 }
2506
2507 private boolean validateConsistencyLocked() {
2508 if (DEBUG_VALIDATE) {
2509 long lastTime = Long.MIN_VALUE;
2510 final int N = mAlarmBatches.size();
2511 for (int i = 0; i < N; i++) {
2512 Batch b = mAlarmBatches.get(i);
2513 if (b.start >= lastTime) {
2514 // duplicate start times are okay because of standalone batches
2515 lastTime = b.start;
2516 } else {
2517 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002518 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2519 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002520 return false;
2521 }
2522 }
2523 }
2524 return true;
2525 }
2526
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002527 private Batch findFirstWakeupBatchLocked() {
2528 final int N = mAlarmBatches.size();
2529 for (int i = 0; i < N; i++) {
2530 Batch b = mAlarmBatches.get(i);
2531 if (b.hasWakeups()) {
2532 return b;
2533 }
2534 }
2535 return null;
2536 }
2537
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002538 long getNextWakeFromIdleTimeImpl() {
2539 synchronized (mLock) {
2540 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2541 }
2542 }
2543
2544 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002545 synchronized (mLock) {
2546 return mNextAlarmClockForUser.get(userId);
2547 }
2548 }
2549
2550 /**
2551 * Recomputes the next alarm clock for all users.
2552 */
2553 private void updateNextAlarmClockLocked() {
2554 if (!mNextAlarmClockMayChange) {
2555 return;
2556 }
2557 mNextAlarmClockMayChange = false;
2558
Jose Lima235510e2014-08-13 12:50:01 -07002559 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002560 nextForUser.clear();
2561
2562 final int N = mAlarmBatches.size();
2563 for (int i = 0; i < N; i++) {
2564 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2565 final int M = alarms.size();
2566
2567 for (int j = 0; j < M; j++) {
2568 Alarm a = alarms.get(j);
2569 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002570 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002571 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002572
2573 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002574 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002575 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002576 " for user " + userId);
2577 }
2578
2579 // Alarms and batches are sorted by time, no need to compare times here.
2580 if (nextForUser.get(userId) == null) {
2581 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002582 } else if (a.alarmClock.equals(current)
2583 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2584 // same/earlier time and it's the one we cited before, so stick with it
2585 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002586 }
2587 }
2588 }
2589 }
2590
2591 // Update mNextAlarmForUser with new values.
2592 final int NN = nextForUser.size();
2593 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002594 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002595 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002596 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002597 if (!newAlarm.equals(currentAlarm)) {
2598 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2599 }
2600 }
2601
2602 // Remove users without any alarm clocks scheduled.
2603 final int NNN = mNextAlarmClockForUser.size();
2604 for (int i = NNN - 1; i >= 0; i--) {
2605 int userId = mNextAlarmClockForUser.keyAt(i);
2606 if (nextForUser.get(userId) == null) {
2607 updateNextAlarmInfoForUserLocked(userId, null);
2608 }
2609 }
2610 }
2611
Jose Lima235510e2014-08-13 12:50:01 -07002612 private void updateNextAlarmInfoForUserLocked(int userId,
2613 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002614 if (alarmClock != null) {
2615 if (DEBUG_ALARM_CLOCK) {
2616 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002617 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002618 }
2619 mNextAlarmClockForUser.put(userId, alarmClock);
2620 } else {
2621 if (DEBUG_ALARM_CLOCK) {
2622 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2623 }
2624 mNextAlarmClockForUser.remove(userId);
2625 }
2626
2627 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2628 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2629 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2630 }
2631
2632 /**
2633 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2634 * for which alarm clocks have changed since the last call to this.
2635 *
2636 * Do not call with a lock held. Only call from mHandler's thread.
2637 *
2638 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2639 */
2640 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002641 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002642 pendingUsers.clear();
2643
2644 synchronized (mLock) {
2645 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2646 for (int i = 0; i < N; i++) {
2647 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2648 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2649 }
2650 mPendingSendNextAlarmClockChangedForUser.clear();
2651 }
2652
2653 final int N = pendingUsers.size();
2654 for (int i = 0; i < N; i++) {
2655 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002656 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002657 Settings.System.putStringForUser(getContext().getContentResolver(),
2658 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002659 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002660 userId);
2661
2662 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2663 new UserHandle(userId));
2664 }
2665 }
2666
2667 /**
2668 * Formats an alarm like platform/packages/apps/DeskClock used to.
2669 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002670 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2671 int userId) {
2672 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002673 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2674 return (info == null) ? "" :
2675 DateFormat.format(pattern, info.getTriggerTime()).toString();
2676 }
2677
Adam Lesinski182f73f2013-12-05 16:48:06 -08002678 void rescheduleKernelAlarmsLocked() {
2679 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2680 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002681 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002682 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002683 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002684 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002685 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002686 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002687 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002688 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002689 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002690 if (firstBatch != firstWakeup) {
2691 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002692 }
2693 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002694 if (mPendingNonWakeupAlarms.size() > 0) {
2695 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2696 nextNonWakeup = mNextNonWakeupDeliveryTime;
2697 }
2698 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002699 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002700 mNextNonWakeup = nextNonWakeup;
2701 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2702 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002703 }
2704
Christopher Tate14a7bb02015-10-01 10:24:31 -07002705 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002706 if (operation == null && directReceiver == null) {
2707 if (localLOGV) {
2708 Slog.w(TAG, "requested remove() of null operation",
2709 new RuntimeException("here"));
2710 }
2711 return;
2712 }
2713
Adam Lesinski182f73f2013-12-05 16:48:06 -08002714 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002715 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002716 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2717 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002718 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002719 if (b.size() == 0) {
2720 mAlarmBatches.remove(i);
2721 }
2722 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002723 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002724 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002725 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2726 mPendingWhileIdleAlarms.remove(i);
2727 }
2728 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002729 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2730 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2731 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2732 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2733 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2734 alarmsForUid.remove(j);
2735 }
2736 }
2737 if (alarmsForUid.size() == 0) {
2738 mPendingBackgroundAlarms.removeAt(i);
2739 }
2740 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002741 if (didRemove) {
2742 if (DEBUG_BATCH) {
2743 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2744 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002745 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002746 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002747 mPendingIdleUntil = null;
2748 restorePending = true;
2749 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002750 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002751 mNextWakeFromIdle = null;
2752 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002753 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002754 if (restorePending) {
2755 restorePendingWhileIdleAlarmsLocked();
2756 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002757 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002758 }
2759 }
2760
Christopher Tate1d99c392017-12-07 16:54:04 -08002761 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002762 if (uid == Process.SYSTEM_UID) {
2763 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2764 return;
2765 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002766 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002767 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002768 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2769 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002770 didRemove |= b.remove(whichAlarms);
2771 if (b.size() == 0) {
2772 mAlarmBatches.remove(i);
2773 }
2774 }
2775 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2776 final Alarm a = mPendingWhileIdleAlarms.get(i);
2777 if (a.uid == uid) {
2778 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2779 mPendingWhileIdleAlarms.remove(i);
2780 }
2781 }
2782 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2783 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2784 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2785 if (alarmsForUid.get(j).uid == uid) {
2786 alarmsForUid.remove(j);
2787 }
2788 }
2789 if (alarmsForUid.size() == 0) {
2790 mPendingBackgroundAlarms.removeAt(i);
2791 }
2792 }
2793 if (didRemove) {
2794 if (DEBUG_BATCH) {
2795 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2796 }
2797 rebatchAllAlarmsLocked(true);
2798 rescheduleKernelAlarmsLocked();
2799 updateNextAlarmClockLocked();
2800 }
2801 }
2802
2803 void removeLocked(final String packageName) {
2804 if (packageName == null) {
2805 if (localLOGV) {
2806 Slog.w(TAG, "requested remove() of null packageName",
2807 new RuntimeException("here"));
2808 }
2809 return;
2810 }
2811
2812 boolean didRemove = false;
2813 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002814 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002815 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2816 Batch b = mAlarmBatches.get(i);
2817 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002818 if (b.size() == 0) {
2819 mAlarmBatches.remove(i);
2820 }
2821 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002822 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2823 if (oldHasTick != newHasTick) {
2824 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2825 }
2826
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002827 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002828 final Alarm a = mPendingWhileIdleAlarms.get(i);
2829 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002830 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2831 mPendingWhileIdleAlarms.remove(i);
2832 }
2833 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002834 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2835 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2836 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2837 if (alarmsForUid.get(j).matches(packageName)) {
2838 alarmsForUid.remove(j);
2839 }
2840 }
2841 if (alarmsForUid.size() == 0) {
2842 mPendingBackgroundAlarms.removeAt(i);
2843 }
2844 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002845 if (didRemove) {
2846 if (DEBUG_BATCH) {
2847 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2848 }
2849 rebatchAllAlarmsLocked(true);
2850 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002851 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002852 }
2853 }
2854
Christopher Tate1d99c392017-12-07 16:54:04 -08002855 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002856 if (uid == Process.SYSTEM_UID) {
2857 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2858 return;
2859 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002860 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002861 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2862 try {
2863 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2864 uid, a.packageName)) {
2865 return true;
2866 }
2867 } catch (RemoteException e) { /* fall through */}
2868 return false;
2869 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002870 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2871 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002872 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002873 if (b.size() == 0) {
2874 mAlarmBatches.remove(i);
2875 }
2876 }
2877 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2878 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002879 if (a.uid == uid) {
2880 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2881 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002882 }
2883 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002884 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2885 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2886 mPendingBackgroundAlarms.removeAt(i);
2887 }
2888 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002889 if (didRemove) {
2890 if (DEBUG_BATCH) {
2891 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2892 }
2893 rebatchAllAlarmsLocked(true);
2894 rescheduleKernelAlarmsLocked();
2895 updateNextAlarmClockLocked();
2896 }
2897 }
2898
Adam Lesinski182f73f2013-12-05 16:48:06 -08002899 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002900 if (userHandle == UserHandle.USER_SYSTEM) {
2901 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2902 return;
2903 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002904 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002905 final Predicate<Alarm> whichAlarms =
2906 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002907 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2908 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002909 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002910 if (b.size() == 0) {
2911 mAlarmBatches.remove(i);
2912 }
2913 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002914 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002915 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002916 == userHandle) {
2917 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2918 mPendingWhileIdleAlarms.remove(i);
2919 }
2920 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002921 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2922 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2923 mPendingBackgroundAlarms.removeAt(i);
2924 }
2925 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002926 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2927 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2928 mLastAllowWhileIdleDispatch.removeAt(i);
2929 }
2930 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002931
2932 if (didRemove) {
2933 if (DEBUG_BATCH) {
2934 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2935 }
2936 rebatchAllAlarmsLocked(true);
2937 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002938 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002939 }
2940 }
2941
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002942 void interactiveStateChangedLocked(boolean interactive) {
2943 if (mInteractive != interactive) {
2944 mInteractive = interactive;
2945 final long nowELAPSED = SystemClock.elapsedRealtime();
2946 if (interactive) {
2947 if (mPendingNonWakeupAlarms.size() > 0) {
2948 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2949 mTotalDelayTime += thisDelayTime;
2950 if (mMaxDelayTime < thisDelayTime) {
2951 mMaxDelayTime = thisDelayTime;
2952 }
2953 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2954 mPendingNonWakeupAlarms.clear();
2955 }
2956 if (mNonInteractiveStartTime > 0) {
2957 long dur = nowELAPSED - mNonInteractiveStartTime;
2958 if (dur > mNonInteractiveTime) {
2959 mNonInteractiveTime = dur;
2960 }
2961 }
2962 } else {
2963 mNonInteractiveStartTime = nowELAPSED;
2964 }
2965 }
2966 }
2967
Adam Lesinski182f73f2013-12-05 16:48:06 -08002968 boolean lookForPackageLocked(String packageName) {
2969 for (int i = 0; i < mAlarmBatches.size(); i++) {
2970 Batch b = mAlarmBatches.get(i);
2971 if (b.hasPackage(packageName)) {
2972 return true;
2973 }
2974 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002975 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002976 final Alarm a = mPendingWhileIdleAlarms.get(i);
2977 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002978 return true;
2979 }
2980 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002981 return false;
2982 }
2983
2984 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002985 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002986 // The kernel never triggers alarms with negative wakeup times
2987 // so we ensure they are positive.
2988 long alarmSeconds, alarmNanoseconds;
2989 if (when < 0) {
2990 alarmSeconds = 0;
2991 alarmNanoseconds = 0;
2992 } else {
2993 alarmSeconds = when / 1000;
2994 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2995 }
Kweku Adams61e03292017-10-19 14:27:12 -07002996
Christopher Tate8b98ade2018-02-09 11:13:19 -08002997 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2998 if (result != 0) {
2999 final long nowElapsed = SystemClock.elapsedRealtime();
3000 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3001 + " type=" + type + " when=" + when
3002 + " @ (" + alarmSeconds + "," + alarmNanoseconds
3003 + "), ret = " + result + " = " + Os.strerror(result));
3004 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003005 } else {
3006 Message msg = Message.obtain();
3007 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003008
Adam Lesinski182f73f2013-12-05 16:48:06 -08003009 mHandler.removeMessages(ALARM_EVENT);
3010 mHandler.sendMessageAtTime(msg, when);
3011 }
3012 }
3013
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003014 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003015 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003016 for (int i=list.size()-1; i>=0; i--) {
3017 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003018 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3019 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003020 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003021 }
3022 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003023
3024 private static final String labelForType(int type) {
3025 switch (type) {
3026 case RTC: return "RTC";
3027 case RTC_WAKEUP : return "RTC_WAKEUP";
3028 case ELAPSED_REALTIME : return "ELAPSED";
3029 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003030 }
3031 return "--unknown--";
3032 }
3033
3034 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003035 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003036 for (int i=list.size()-1; i>=0; i--) {
3037 Alarm a = list.get(i);
3038 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003039 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3040 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003041 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003042 }
3043 }
3044
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003045 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003046 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003047 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003048 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003049 return false;
3050 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003051 if (alarm.operation != null) {
3052 if (alarm.operation.isActivity()) {
3053 // Don't defer starting actual UI
3054 return false;
3055 }
3056 if (alarm.operation.isForegroundService()) {
3057 // FG service alarms are nearly as important; consult AST policy
3058 exemptOnBatterySaver = true;
3059 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003060 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003061 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003062 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003063 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003064 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3065 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003066 }
3067
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003068 private native long init();
3069 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003070 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003071 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003072 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003073 private native int setKernelTimezone(long nativeData, int minuteswest);
Suprabh Shukla2324e982018-06-05 21:06:22 -07003074 private native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003075
Makoto Onukiadb50d82018-01-29 16:20:30 -08003076 private long getWhileIdleMinIntervalLocked(int uid) {
3077 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003078 final boolean ebs = (mAppStateTracker != null)
3079 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003080 if (!dozing && !ebs) {
3081 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3082 }
3083 if (dozing) {
3084 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3085 }
3086 if (mUseAllowWhileIdleShortTime.get(uid)) {
3087 // if the last allow-while-idle went off while uid was fg, or the uid
3088 // recently came into fg, don't block the alarm for long.
3089 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3090 }
3091 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3092 }
3093
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003094 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003095 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003096 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003097 // batches are temporally sorted, so we need only pull from the
3098 // start of the list until we either empty it or hit a batch
3099 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003100 while (mAlarmBatches.size() > 0) {
3101 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003102 if (batch.start > nowELAPSED) {
3103 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003104 break;
3105 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003106
Christopher Tatee0a22b32013-07-11 14:43:13 -07003107 // We will (re)schedule some alarms now; don't let that interfere
3108 // with delivery of this current batch
3109 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003110
Christopher Tatee0a22b32013-07-11 14:43:13 -07003111 final int N = batch.size();
3112 for (int i = 0; i < N; i++) {
3113 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003114
3115 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3116 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003117 // schedule such alarms. The first such alarm from an app is always delivered.
3118 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003119 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003120 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003121 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3122 // alarm went off for this app. Reschedule the alarm to be in the
3123 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003124 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003125 if (alarm.maxWhenElapsed < minTime) {
3126 alarm.maxWhenElapsed = minTime;
3127 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003128 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003129 if (RECORD_DEVICE_IDLE_ALARMS) {
3130 IdleDispatchEntry ent = new IdleDispatchEntry();
3131 ent.uid = alarm.uid;
3132 ent.pkg = alarm.operation.getCreatorPackage();
3133 ent.tag = alarm.operation.getTag("");
3134 ent.op = "RESCHEDULE";
3135 ent.elapsedRealtime = nowELAPSED;
3136 ent.argRealtime = lastTime;
3137 mAllowWhileIdleDispatches.add(ent);
3138 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003139 setImplLocked(alarm, true, false);
3140 continue;
3141 }
3142 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003143 if (isBackgroundRestricted(alarm)) {
3144 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3145 if (DEBUG_BG_LIMIT) {
3146 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3147 }
3148 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3149 if (alarmsForUid == null) {
3150 alarmsForUid = new ArrayList<>();
3151 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3152 }
3153 alarmsForUid.add(alarm);
3154 continue;
3155 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003156
Christopher Tatee0a22b32013-07-11 14:43:13 -07003157 alarm.count = 1;
3158 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003159 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3160 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003161 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003162 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003163 if (mPendingIdleUntil == alarm) {
3164 mPendingIdleUntil = null;
3165 rebatchAllAlarmsLocked(false);
3166 restorePendingWhileIdleAlarmsLocked();
3167 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003168 if (mNextWakeFromIdle == alarm) {
3169 mNextWakeFromIdle = null;
3170 rebatchAllAlarmsLocked(false);
3171 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003172
3173 // Recurring alarms may have passed several alarm intervals while the
3174 // phone was asleep or off, so pass a trigger count when sending them.
3175 if (alarm.repeatInterval > 0) {
3176 // this adjustment will be zero if we're late by
3177 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003178 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003179
3180 // Also schedule its next recurrence
3181 final long delta = alarm.count * alarm.repeatInterval;
3182 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003183 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003184 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003185 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3186 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003187 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188
Christopher Tate864d42e2014-12-02 11:48:53 -08003189 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003190 hasWakeup = true;
3191 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003192
3193 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3194 if (alarm.alarmClock != null) {
3195 mNextAlarmClockMayChange = true;
3196 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003197 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003199
Christopher Tate1590f1e2014-10-02 17:27:57 -07003200 // This is a new alarm delivery set; bump the sequence number to indicate that
3201 // all apps' alarm delivery classes should be recalculated.
3202 mCurrentSeq++;
3203 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003204 Collections.sort(triggerList, mAlarmDispatchComparator);
3205
3206 if (localLOGV) {
3207 for (int i=0; i<triggerList.size(); i++) {
3208 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3209 }
3210 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003211
3212 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003213 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003215 /**
3216 * This Comparator sorts Alarms into increasing time order.
3217 */
3218 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3219 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003220 long when1 = a1.whenElapsed;
3221 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003222 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 return 1;
3224 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003225 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 return -1;
3227 }
3228 return 0;
3229 }
3230 }
Kweku Adams61e03292017-10-19 14:27:12 -07003231
Makoto Onuki2206af32017-11-21 16:25:35 -08003232 @VisibleForTesting
3233 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003234 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003235 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003236 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003237 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003238 public final IAlarmListener listener;
3239 public final String listenerTag;
3240 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003241 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003242 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003243 public final AlarmManager.AlarmClockInfo alarmClock;
3244 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003245 public final int creatorUid;
3246 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003247 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003248 public int count;
3249 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003250 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003251 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003252 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003253 // Expected alarm expiry time before app standby deferring is applied.
3254 public long expectedWhenElapsed;
3255 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003257 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003258
Christopher Tate3e04b472013-10-21 17:51:31 -07003259 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003260 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3261 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3262 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003263 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003264 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003265 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3266 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003267 when = _when;
3268 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003269 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003270 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003271 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003272 repeatInterval = _interval;
3273 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003274 listener = _rec;
3275 listenerTag = _listenerTag;
3276 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003277 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003278 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003279 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003280 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003281 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003282 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003283 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003284 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003285
Christopher Tate14a7bb02015-10-01 10:24:31 -07003286 public static String makeTag(PendingIntent pi, String tag, int type) {
3287 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3288 ? "*walarm*:" : "*alarm*:";
3289 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3290 }
3291
3292 public WakeupEvent makeWakeupEvent(long nowRTC) {
3293 return new WakeupEvent(nowRTC, creatorUid,
3294 (operation != null)
3295 ? operation.getIntent().getAction()
3296 : ("<listener>:" + listenerTag));
3297 }
3298
3299 // Returns true if either matches
3300 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3301 return (operation != null)
3302 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003303 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003304 }
3305
3306 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003307 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003308 }
3309
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003310 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003311 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003312 StringBuilder sb = new StringBuilder(128);
3313 sb.append("Alarm{");
3314 sb.append(Integer.toHexString(System.identityHashCode(this)));
3315 sb.append(" type ");
3316 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003317 sb.append(" when ");
3318 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003319 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003320 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003321 sb.append('}');
3322 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003323 }
3324
Kweku Adams61e03292017-10-19 14:27:12 -07003325 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003326 SimpleDateFormat sdf) {
3327 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003328 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003329 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003330 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3331 expectedWhenElapsed, nowELAPSED, pw);
3332 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3333 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003334 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3335 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003336 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3337 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003338 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003339 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003340 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003341 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003342 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003343 }
3344 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003345 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003346 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003347 pw.print(" count="); pw.print(count);
3348 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003349 if (alarmClock != null) {
3350 pw.print(prefix); pw.println("Alarm clock:");
3351 pw.print(prefix); pw.print(" triggerTime=");
3352 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3353 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3354 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003355 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003356 if (listener != null) {
3357 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3358 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003359 }
Kweku Adams61e03292017-10-19 14:27:12 -07003360
3361 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3362 long nowRTC) {
3363 final long token = proto.start(fieldId);
3364
3365 proto.write(AlarmProto.TAG, statsTag);
3366 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003367 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003368 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3369 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3370 proto.write(AlarmProto.COUNT, count);
3371 proto.write(AlarmProto.FLAGS, flags);
3372 if (alarmClock != null) {
3373 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3374 }
3375 if (operation != null) {
3376 operation.writeToProto(proto, AlarmProto.OPERATION);
3377 }
3378 if (listener != null) {
3379 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3380 }
3381
3382 proto.end(token);
3383 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003384 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003385
Christopher Tatee0a22b32013-07-11 14:43:13 -07003386 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3387 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003388 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3389 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003390 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003391 break;
3392 }
3393
Christopher Tatee0a22b32013-07-11 14:43:13 -07003394 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003395 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3396 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003397 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003398 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003399 }
3400 }
3401
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003402 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3403 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3404 if (timeSinceOn < 5*60*1000) {
3405 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3406 return 2*60*1000;
3407 } else if (timeSinceOn < 30*60*1000) {
3408 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3409 return 15*60*1000;
3410 } else {
3411 // Otherwise, we will delay by at most an hour.
3412 return 60*60*1000;
3413 }
3414 }
3415
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003416 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003417 if (duration < 15*60*1000) {
3418 // If the duration until the time is less than 15 minutes, the maximum fuzz
3419 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003420 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003421 } else if (duration < 90*60*1000) {
3422 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3423 return 15*60*1000;
3424 } else {
3425 // Otherwise, we will fuzz by at most half an hour.
3426 return 30*60*1000;
3427 }
3428 }
3429
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003430 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3431 if (mInteractive) {
3432 return false;
3433 }
3434 if (mLastAlarmDeliveryTime <= 0) {
3435 return false;
3436 }
minho.choo649acab2014-12-12 16:13:55 +09003437 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003438 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3439 // and the next delivery time is in the past, then just deliver them all. This
3440 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3441 return false;
3442 }
3443 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3444 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3445 }
3446
3447 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3448 mLastAlarmDeliveryTime = nowELAPSED;
3449 for (int i=0; i<triggerList.size(); i++) {
3450 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003451 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003452 if (alarm.wakeup) {
3453 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3454 } else {
3455 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3456 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003457 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003458 if (localLOGV) {
3459 Slog.v(TAG, "sending alarm " + alarm);
3460 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003461 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003462 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3463 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003464 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003465 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003466 } catch (RuntimeException e) {
3467 Slog.w(TAG, "Failure sending alarm.", e);
3468 }
Tim Murray175c0f92017-11-28 15:01:04 -08003469 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003470 }
3471 }
3472
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003473 private boolean isExemptFromAppStandby(Alarm a) {
3474 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3475 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3476 }
3477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 private class AlarmThread extends Thread
3479 {
3480 public AlarmThread()
3481 {
3482 super("AlarmManager");
3483 }
Kweku Adams61e03292017-10-19 14:27:12 -07003484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 public void run()
3486 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003487 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3488
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003489 while (true)
3490 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003491 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003492
Dianne Hackbornc3527222015-05-13 14:03:20 -07003493 final long nowRTC = System.currentTimeMillis();
3494 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003495 synchronized (mLock) {
3496 mLastWakeup = nowELAPSED;
3497 }
3498
3499 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003500
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003502 // The kernel can give us spurious time change notifications due to
3503 // small adjustments it makes internally; we want to filter those out.
3504 final long lastTimeChangeClockTime;
3505 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003506 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003507 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3508 expectedClockTime = lastTimeChangeClockTime
3509 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003510 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003511 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3512 || nowRTC > (expectedClockTime+1000)) {
3513 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003514 // let's do it!
3515 if (DEBUG_BATCH) {
3516 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3517 }
3518 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003519 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003520 rebatchAllAlarms();
3521 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003522 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003523 synchronized (mLock) {
3524 mNumTimeChanged++;
3525 mLastTimeChangeClockTime = nowRTC;
3526 mLastTimeChangeRealtime = nowELAPSED;
3527 }
3528 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3529 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003530 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003531 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3532 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003533 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3534
3535 // The world has changed on us, so we need to re-evaluate alarms
3536 // regardless of whether the kernel has told us one went off.
3537 result |= IS_WAKEUP_MASK;
3538 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003539 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540
Dianne Hackbornc3527222015-05-13 14:03:20 -07003541 if (result != TIME_CHANGED_MASK) {
3542 // If this was anything besides just a time change, then figure what if
3543 // anything to do about alarms.
3544 synchronized (mLock) {
3545 if (localLOGV) Slog.v(
3546 TAG, "Checking for alarms... rtc=" + nowRTC
3547 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003548
Dianne Hackbornc3527222015-05-13 14:03:20 -07003549 if (WAKEUP_STATS) {
3550 if ((result & IS_WAKEUP_MASK) != 0) {
3551 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3552 int n = 0;
3553 for (WakeupEvent event : mRecentWakeups) {
3554 if (event.when > newEarliest) break;
3555 n++; // number of now-stale entries at the list head
3556 }
3557 for (int i = 0; i < n; i++) {
3558 mRecentWakeups.remove();
3559 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003560
Dianne Hackbornc3527222015-05-13 14:03:20 -07003561 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003562 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003563 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003564
Christopher Tate8b98ade2018-02-09 11:13:19 -08003565 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003566 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3567 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3568 // if there are no wakeup alarms and the screen is off, we can
3569 // delay what we have so far until the future.
3570 if (mPendingNonWakeupAlarms.size() == 0) {
3571 mStartCurrentDelayTime = nowELAPSED;
3572 mNextNonWakeupDeliveryTime = nowELAPSED
3573 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3574 }
3575 mPendingNonWakeupAlarms.addAll(triggerList);
3576 mNumDelayedAlarms += triggerList.size();
3577 rescheduleKernelAlarmsLocked();
3578 updateNextAlarmClockLocked();
3579 } else {
3580 // now deliver the alarm intents; if there are pending non-wakeup
3581 // alarms, we need to merge them in to the list. note we don't
3582 // just deliver them first because we generally want non-wakeup
3583 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003584 if (mPendingNonWakeupAlarms.size() > 0) {
3585 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3586 triggerList.addAll(mPendingNonWakeupAlarms);
3587 Collections.sort(triggerList, mAlarmDispatchComparator);
3588 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3589 mTotalDelayTime += thisDelayTime;
3590 if (mMaxDelayTime < thisDelayTime) {
3591 mMaxDelayTime = thisDelayTime;
3592 }
3593 mPendingNonWakeupAlarms.clear();
3594 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003595 final ArraySet<Pair<String, Integer>> triggerPackages =
3596 new ArraySet<>();
3597 for (int i = 0; i < triggerList.size(); i++) {
3598 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003599 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003600 triggerPackages.add(Pair.create(
3601 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003602 }
3603 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003604 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003605 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3606 rescheduleKernelAlarmsLocked();
3607 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003610
3611 } else {
3612 // Just in case -- even though no wakeup flag was set, make sure
3613 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003614 synchronized (mLock) {
3615 rescheduleKernelAlarmsLocked();
3616 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003617 }
3618 }
3619 }
3620 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003621
David Christieebe51fc2013-07-26 13:23:29 -07003622 /**
3623 * Attribute blame for a WakeLock.
3624 * @param pi PendingIntent to attribute blame to if ws is null.
3625 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003626 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003627 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003628 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003629 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003630 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003631 final boolean unimportant = pi == mTimeTickSender;
3632 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003633 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003634 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003635 } else {
3636 mWakeLock.setHistoryTag(null);
3637 }
3638 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003639 if (ws != null) {
3640 mWakeLock.setWorkSource(ws);
3641 return;
3642 }
3643
Christopher Tate14a7bb02015-10-01 10:24:31 -07003644 final int uid = (knownUid >= 0)
3645 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003646 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003647 if (uid >= 0) {
3648 mWakeLock.setWorkSource(new WorkSource(uid));
3649 return;
3650 }
3651 } catch (Exception e) {
3652 }
3653
3654 // Something went wrong; fall back to attributing the lock to the OS
3655 mWakeLock.setWorkSource(null);
3656 }
3657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 private class AlarmHandler extends Handler {
3659 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003660 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3661 public static final int LISTENER_TIMEOUT = 3;
3662 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003663 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3664 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003665 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003666
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003667 public AlarmHandler() {
3668 }
Kweku Adams61e03292017-10-19 14:27:12 -07003669
Makoto Onuki4d298b52018-02-05 10:54:58 -08003670 public void postRemoveForStopped(int uid) {
3671 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3672 }
3673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003674 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003675 switch (msg.what) {
3676 case ALARM_EVENT: {
3677 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3678 synchronized (mLock) {
3679 final long nowRTC = System.currentTimeMillis();
3680 final long nowELAPSED = SystemClock.elapsedRealtime();
3681 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3682 updateNextAlarmClockLocked();
3683 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003684
Christopher Tate14a7bb02015-10-01 10:24:31 -07003685 // now trigger the alarms without the lock held
3686 for (int i=0; i<triggerList.size(); i++) {
3687 Alarm alarm = triggerList.get(i);
3688 try {
3689 alarm.operation.send();
3690 } catch (PendingIntent.CanceledException e) {
3691 if (alarm.repeatInterval > 0) {
3692 // This IntentSender is no longer valid, but this
3693 // is a repeating alarm, so toss the hoser.
3694 removeImpl(alarm.operation);
3695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003696 }
3697 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003698 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003700
3701 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3702 sendNextAlarmClockChanged();
3703 break;
3704
3705 case LISTENER_TIMEOUT:
3706 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3707 break;
3708
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003709 case REPORT_ALARMS_ACTIVE:
3710 if (mLocalDeviceIdleController != null) {
3711 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3712 }
3713 break;
3714
Suprabh Shukla75edab12018-01-29 14:09:06 -08003715 case APP_STANDBY_PAROLE_CHANGED:
3716 synchronized (mLock) {
3717 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003718 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3719 rescheduleKernelAlarmsLocked();
3720 updateNextAlarmClockLocked();
3721 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003722 }
3723 break;
3724
3725 case APP_STANDBY_BUCKET_CHANGED:
3726 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003727 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3728 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3729 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3730 rescheduleKernelAlarmsLocked();
3731 updateNextAlarmClockLocked();
3732 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003733 }
3734 break;
3735
Makoto Onuki4d298b52018-02-05 10:54:58 -08003736 case REMOVE_FOR_STOPPED:
3737 synchronized (mLock) {
3738 removeForStoppedLocked(msg.arg1);
3739 }
3740 break;
3741
Christopher Tate14a7bb02015-10-01 10:24:31 -07003742 default:
3743 // nope, just ignore it
3744 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003745 }
3746 }
3747 }
Kweku Adams61e03292017-10-19 14:27:12 -07003748
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003749 class ClockReceiver extends BroadcastReceiver {
3750 public ClockReceiver() {
3751 IntentFilter filter = new IntentFilter();
3752 filter.addAction(Intent.ACTION_TIME_TICK);
3753 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003754 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
Kweku Adams61e03292017-10-19 14:27:12 -07003756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003757 @Override
3758 public void onReceive(Context context, Intent intent) {
3759 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003760 if (DEBUG_BATCH) {
3761 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3762 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003763 synchronized (mLock) {
3764 mLastTickReceived = System.currentTimeMillis();
3765 }
Christopher Tate385e4982013-07-23 18:22:29 -07003766 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003767 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3768 // Since the kernel does not keep track of DST, we need to
3769 // reset the TZ information at the beginning of each day
3770 // based off of the current Zone gmt offset + userspace tracked
3771 // daylight savings information.
3772 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003773 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003774 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003775 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003776 }
3777 }
Kweku Adams61e03292017-10-19 14:27:12 -07003778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003780 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003781 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003782
3783 // Schedule this event for the amount of time that it would take to get to
3784 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003785 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003786
David Christieebe51fc2013-07-26 13:23:29 -07003787 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003788 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003789 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3790 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003791
3792 // Finally, remember when we set the tick alarm
3793 synchronized (mLock) {
3794 mLastTickSet = currentTime;
3795 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003796 }
Christopher Tate385e4982013-07-23 18:22:29 -07003797
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 public void scheduleDateChangedEvent() {
3799 Calendar calendar = Calendar.getInstance();
3800 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003801 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003802 calendar.set(Calendar.MINUTE, 0);
3803 calendar.set(Calendar.SECOND, 0);
3804 calendar.set(Calendar.MILLISECOND, 0);
3805 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003806
3807 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003808 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3809 AlarmManager.FLAG_STANDALONE, workSource, null,
3810 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 }
3812 }
Kweku Adams61e03292017-10-19 14:27:12 -07003813
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003814 class InteractiveStateReceiver extends BroadcastReceiver {
3815 public InteractiveStateReceiver() {
3816 IntentFilter filter = new IntentFilter();
3817 filter.addAction(Intent.ACTION_SCREEN_OFF);
3818 filter.addAction(Intent.ACTION_SCREEN_ON);
3819 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3820 getContext().registerReceiver(this, filter);
3821 }
3822
3823 @Override
3824 public void onReceive(Context context, Intent intent) {
3825 synchronized (mLock) {
3826 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3827 }
3828 }
3829 }
3830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 class UninstallReceiver extends BroadcastReceiver {
3832 public UninstallReceiver() {
3833 IntentFilter filter = new IntentFilter();
3834 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3835 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003836 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003837 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003838 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003839 // Register for events related to sdcard installation.
3840 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003841 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003842 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003843 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003844 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003845 }
Kweku Adams61e03292017-10-19 14:27:12 -07003846
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003847 @Override
3848 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003849 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003850 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003851 String action = intent.getAction();
3852 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003853 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3854 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3855 for (String packageName : pkgList) {
3856 if (lookForPackageLocked(packageName)) {
3857 setResultCode(Activity.RESULT_OK);
3858 return;
3859 }
3860 }
3861 return;
3862 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003863 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003864 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3865 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3866 if (userHandle >= 0) {
3867 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003868 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3869 final Pair<String, Integer> packageUser =
3870 mLastAlarmDeliveredForPackage.keyAt(i);
3871 if (packageUser.second == userHandle) {
3872 mLastAlarmDeliveredForPackage.removeAt(i);
3873 }
3874 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003875 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003876 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003877 if (uid >= 0) {
3878 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003879 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003880 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003881 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003882 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3883 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3884 // This package is being updated; don't kill its alarms.
3885 return;
3886 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003887 Uri data = intent.getData();
3888 if (data != null) {
3889 String pkg = data.getSchemeSpecificPart();
3890 if (pkg != null) {
3891 pkgList = new String[]{pkg};
3892 }
3893 }
3894 }
3895 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003896 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3897 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3898 if (ArrayUtils.contains(pkgList, packageUser.first)
3899 && packageUser.second == UserHandle.getUserId(uid)) {
3900 mLastAlarmDeliveredForPackage.removeAt(i);
3901 }
3902 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003903 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003904 if (uid >= 0) {
3905 // package-removed case
3906 removeLocked(uid);
3907 } else {
3908 // external-applications-unavailable etc case
3909 removeLocked(pkg);
3910 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003911 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003912 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3913 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3914 if (uidStats.remove(pkg) != null) {
3915 if (uidStats.size() <= 0) {
3916 mBroadcastStats.removeAt(i);
3917 }
3918 }
3919 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003920 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003921 }
3922 }
3923 }
3924 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003925
3926 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003927 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003928 }
3929
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003930 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003931 if (disabled) {
3932 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003933 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003934 }
3935
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003936 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003937 }
3938
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003939 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003940 if (disabled) {
3941 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003942 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003943 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003944
3945 @Override public void onUidCachedChanged(int uid, boolean cached) {
3946 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003947 };
3948
Suprabh Shukla75edab12018-01-29 14:09:06 -08003949 /**
3950 * Tracking of app assignments to standby buckets
3951 */
3952 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3953 @Override
3954 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08003955 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003956 if (DEBUG_STANDBY) {
3957 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3958 bucket);
3959 }
3960 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003961 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3962 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003963 }
3964
3965 @Override
3966 public void onParoleStateChanged(boolean isParoleOn) {
3967 if (DEBUG_STANDBY) {
3968 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3969 }
3970 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3971 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3972 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3973 Boolean.valueOf(isParoleOn)).sendToTarget();
3974 }
3975 };
3976
Makoto Onuki2206af32017-11-21 16:25:35 -08003977 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003978 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003979 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003980 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003981 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003982 }
3983 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003984
3985 @Override
3986 public void unblockAlarmsForUid(int uid) {
3987 synchronized (mLock) {
3988 sendPendingBackgroundAlarmsLocked(uid, null);
3989 }
3990 }
3991
3992 @Override
3993 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3994 synchronized (mLock) {
3995 sendPendingBackgroundAlarmsLocked(uid, packageName);
3996 }
3997 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003998
3999 @Override
4000 public void onUidForeground(int uid, boolean foreground) {
4001 synchronized (mLock) {
4002 if (foreground) {
4003 mUseAllowWhileIdleShortTime.put(uid, true);
4004
4005 // Note we don't have to drain the pending while-idle alarms here, because
4006 // this event should coincide with unblockAlarmsForUid().
4007 }
4008 }
4009 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004010 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004011
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004013 String pkg = pi.getCreatorPackage();
4014 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004015 return getStatsLocked(uid, pkg);
4016 }
4017
4018 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004019 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4020 if (uidStats == null) {
4021 uidStats = new ArrayMap<String, BroadcastStats>();
4022 mBroadcastStats.put(uid, uidStats);
4023 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004024 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004025 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004026 bs = new BroadcastStats(uid, pkgName);
4027 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004028 }
4029 return bs;
4030 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004031
Christopher Tate21e9f192017-08-08 13:49:11 -07004032 /**
4033 * Canonical count of (operation.send() - onSendFinished()) and
4034 * listener send/complete/timeout invocations.
4035 * Guarded by the usual lock.
4036 */
4037 @GuardedBy("mLock")
4038 private int mSendCount = 0;
4039 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004040 private int mSendFinishCount = 0;
4041 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004042 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004043 @GuardedBy("mLock")
4044 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004045
Christopher Tate14a7bb02015-10-01 10:24:31 -07004046 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004047
Christopher Tate14a7bb02015-10-01 10:24:31 -07004048 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4049 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004050 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004051 return mInFlight.remove(i);
4052 }
4053 }
4054 mLog.w("No in-flight alarm for " + pi + " " + intent);
4055 return null;
4056 }
4057
4058 private InFlight removeLocked(IBinder listener) {
4059 for (int i = 0; i < mInFlight.size(); i++) {
4060 if (mInFlight.get(i).mListener == listener) {
4061 return mInFlight.remove(i);
4062 }
4063 }
4064 mLog.w("No in-flight alarm for listener " + listener);
4065 return null;
4066 }
4067
4068 private void updateStatsLocked(InFlight inflight) {
4069 final long nowELAPSED = SystemClock.elapsedRealtime();
4070 BroadcastStats bs = inflight.mBroadcastStats;
4071 bs.nesting--;
4072 if (bs.nesting <= 0) {
4073 bs.nesting = 0;
4074 bs.aggregateTime += nowELAPSED - bs.startTime;
4075 }
4076 FilterStats fs = inflight.mFilterStats;
4077 fs.nesting--;
4078 if (fs.nesting <= 0) {
4079 fs.nesting = 0;
4080 fs.aggregateTime += nowELAPSED - fs.startTime;
4081 }
4082 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004083 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4084 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004085 }
4086 }
4087
4088 private void updateTrackingLocked(InFlight inflight) {
4089 if (inflight != null) {
4090 updateStatsLocked(inflight);
4091 }
4092 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004093 if (DEBUG_WAKELOCK) {
4094 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4095 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004096 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004097 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004098 mWakeLock.release();
4099 if (mInFlight.size() > 0) {
4100 mLog.w("Finished all dispatches with " + mInFlight.size()
4101 + " remaining inflights");
4102 for (int i=0; i<mInFlight.size(); i++) {
4103 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4104 }
4105 mInFlight.clear();
4106 }
4107 } else {
4108 // the next of our alarms is now in flight. reattribute the wakelock.
4109 if (mInFlight.size() > 0) {
4110 InFlight inFlight = mInFlight.get(0);
4111 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4112 inFlight.mAlarmType, inFlight.mTag, -1, false);
4113 } else {
4114 // should never happen
4115 mLog.w("Alarm wakelock still held but sent queue empty");
4116 mWakeLock.setWorkSource(null);
4117 }
4118 }
4119 }
4120
4121 /**
4122 * Callback that arrives when a direct-call alarm reports that delivery has finished
4123 */
4124 @Override
4125 public void alarmComplete(IBinder who) {
4126 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004127 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004128 + " pid=" + Binder.getCallingPid());
4129 return;
4130 }
4131
4132 final long ident = Binder.clearCallingIdentity();
4133 try {
4134 synchronized (mLock) {
4135 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4136 InFlight inflight = removeLocked(who);
4137 if (inflight != null) {
4138 if (DEBUG_LISTENER_CALLBACK) {
4139 Slog.i(TAG, "alarmComplete() from " + who);
4140 }
4141 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004142 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004143 } else {
4144 // Delivery timed out, and the timeout handling already took care of
4145 // updating our tracking here, so we needn't do anything further.
4146 if (DEBUG_LISTENER_CALLBACK) {
4147 Slog.i(TAG, "Late alarmComplete() from " + who);
4148 }
4149 }
4150 }
4151 } finally {
4152 Binder.restoreCallingIdentity(ident);
4153 }
4154 }
4155
4156 /**
4157 * Callback that arrives when a PendingIntent alarm has finished delivery
4158 */
4159 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004160 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4161 String resultData, Bundle resultExtras) {
4162 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004163 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004164 updateTrackingLocked(removeLocked(pi, intent));
4165 }
4166 }
4167
4168 /**
4169 * Timeout of a direct-call alarm delivery
4170 */
4171 public void alarmTimedOut(IBinder who) {
4172 synchronized (mLock) {
4173 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004174 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004175 // TODO: implement ANR policy for the target
4176 if (DEBUG_LISTENER_CALLBACK) {
4177 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004178 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004179 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004180 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004181 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004182 if (DEBUG_LISTENER_CALLBACK) {
4183 Slog.i(TAG, "Spurious timeout of listener " + who);
4184 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004185 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004186 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004187 }
4188 }
4189
4190 /**
4191 * Deliver an alarm and set up the post-delivery handling appropriately
4192 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004193 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004194 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4195 if (alarm.operation != null) {
4196 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004197 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004198
4199 if (alarm.priorityClass.priority == PRIO_TICK) {
4200 mLastTickIssued = nowELAPSED;
4201 }
4202
Christopher Tate14a7bb02015-10-01 10:24:31 -07004203 try {
4204 alarm.operation.send(getContext(), 0,
4205 mBackgroundIntent.putExtra(
4206 Intent.EXTRA_ALARM_COUNT, alarm.count),
4207 mDeliveryTracker, mHandler, null,
4208 allowWhileIdle ? mIdleOptions : null);
4209 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004210 if (alarm.operation == mTimeTickSender) {
4211 Slog.wtf(TAG, "mTimeTickSender canceled");
4212 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004213 if (alarm.repeatInterval > 0) {
4214 // This IntentSender is no longer valid, but this
4215 // is a repeating alarm, so toss it
4216 removeImpl(alarm.operation);
4217 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004218 // No actual delivery was possible, so the delivery tracker's
4219 // 'finished' callback won't be invoked. We also don't need
4220 // to do any wakelock or stats tracking, so we have nothing
4221 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004222 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004223 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004224 }
4225 } else {
4226 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004227 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004228 try {
4229 if (DEBUG_LISTENER_CALLBACK) {
4230 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4231 + " listener=" + alarm.listener.asBinder());
4232 }
4233 alarm.listener.doAlarm(this);
4234 mHandler.sendMessageDelayed(
4235 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4236 alarm.listener.asBinder()),
4237 mConstants.LISTENER_TIMEOUT);
4238 } catch (Exception e) {
4239 if (DEBUG_LISTENER_CALLBACK) {
4240 Slog.i(TAG, "Alarm undeliverable to listener "
4241 + alarm.listener.asBinder(), e);
4242 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004243 // As in the PendingIntent.CanceledException case, delivery of the
4244 // alarm was not possible, so we have no wakelock or timeout or
4245 // stats management to do. It threw before we posted the delayed
4246 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004247 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004248 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004249 }
4250 }
4251
4252 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004253 if (DEBUG_WAKELOCK) {
4254 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4255 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004256 if (mBroadcastRefCount == 0) {
4257 setWakelockWorkSource(alarm.operation, alarm.workSource,
4258 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4259 true);
4260 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004261 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004262 }
4263 final InFlight inflight = new InFlight(AlarmManagerService.this,
4264 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4265 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4266 mInFlight.add(inflight);
4267 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004268 if (allowWhileIdle) {
4269 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004270 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004271 if ((mAppStateTracker == null)
4272 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004273 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4274 } else {
4275 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4276 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004277 if (RECORD_DEVICE_IDLE_ALARMS) {
4278 IdleDispatchEntry ent = new IdleDispatchEntry();
4279 ent.uid = alarm.uid;
4280 ent.pkg = alarm.packageName;
4281 ent.tag = alarm.statsTag;
4282 ent.op = "DELIVER";
4283 ent.elapsedRealtime = nowELAPSED;
4284 mAllowWhileIdleDispatches.add(ent);
4285 }
4286 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004287 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004288 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4289 UserHandle.getUserId(alarm.creatorUid));
4290 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4291 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004292
4293 final BroadcastStats bs = inflight.mBroadcastStats;
4294 bs.count++;
4295 if (bs.nesting == 0) {
4296 bs.nesting = 1;
4297 bs.startTime = nowELAPSED;
4298 } else {
4299 bs.nesting++;
4300 }
4301 final FilterStats fs = inflight.mFilterStats;
4302 fs.count++;
4303 if (fs.nesting == 0) {
4304 fs.nesting = 1;
4305 fs.startTime = nowELAPSED;
4306 } else {
4307 fs.nesting++;
4308 }
4309 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4310 || alarm.type == RTC_WAKEUP) {
4311 bs.numWakeup++;
4312 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004313 ActivityManager.noteWakeupAlarm(
4314 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4315 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004316 }
4317 }
4318 }
mswest463f4c99d2018-02-01 10:13:10 -08004319
4320 private class ShellCmd extends ShellCommand {
4321
4322 IAlarmManager getBinderService() {
4323 return IAlarmManager.Stub.asInterface(mService);
4324 }
4325
4326 @Override
4327 public int onCommand(String cmd) {
4328 if (cmd == null) {
4329 return handleDefaultCommands(cmd);
4330 }
4331
4332 final PrintWriter pw = getOutPrintWriter();
4333 try {
4334 switch (cmd) {
4335 case "set-time":
4336 final long millis = Long.parseLong(getNextArgRequired());
4337 return (getBinderService().setTime(millis)) ? 0 : -1;
4338 case "set-timezone":
4339 final String tz = getNextArgRequired();
4340 getBinderService().setTimeZone(tz);
4341 return 0;
4342 default:
4343 return handleDefaultCommands(cmd);
4344 }
4345 } catch (Exception e) {
4346 pw.println(e);
4347 }
4348 return -1;
4349 }
4350
4351 @Override
4352 public void onHelp() {
4353 PrintWriter pw = getOutPrintWriter();
4354 pw.println("Alarm manager service (alarm) commands:");
4355 pw.println(" help");
4356 pw.println(" Print this help text.");
4357 pw.println(" set-time TIME");
4358 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4359 pw.println(" since the Epoch.");
4360 pw.println(" set-timezone TZ");
4361 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4362 }
4363 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004364}