blob: 26ef42f2b1e7e2317ebbec1073bf0767f1ff081d [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;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -0700175 private long mNextWakeUpSetAt;
176 private long mNextNonWakeUpSetAt;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700177 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800178 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800179 private long mLastTickSet;
180 private long mLastTickIssued; // elapsed
181 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800182 private long mLastTickAdded;
183 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800184 int mBroadcastRefCount = 0;
185 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700186 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700187 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
188 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800189 final AlarmHandler mHandler = new AlarmHandler();
190 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700191 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700193 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800194 PendingIntent mTimeTickSender;
195 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700196 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700197 boolean mInteractive = true;
198 long mNonInteractiveStartTime;
199 long mNonInteractiveTime;
200 long mLastAlarmDeliveryTime;
201 long mStartCurrentDelayTime;
202 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700203 long mLastTimeChangeClockTime;
204 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700205 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800206
Christopher Tatebb9cce52017-04-18 14:19:43 -0700207 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
208
209 /**
210 * This permission must be defined by the canonical System UI package,
211 * with protection level "signature".
212 */
213 private static final String SYSTEM_UI_SELF_PERMISSION =
214 "android.permission.systemui.IDENTITY";
215
216 /**
217 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
218 */
219 int mSystemUiUid;
220
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700221 /**
222 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700223 * used to determine the earliest we can dispatch the next such alarm. Times are in the
224 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700225 */
226 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
227
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800228 /**
229 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
230 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
231 */
232 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
233
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700234 final static class IdleDispatchEntry {
235 int uid;
236 String pkg;
237 String tag;
238 String op;
239 long elapsedRealtime;
240 long argRealtime;
241 }
242 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
243
Suprabh Shukla75edab12018-01-29 14:09:06 -0800244 interface Stats {
245 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800246 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800247 }
248
249 private final StatLogger mStatLogger = new StatLogger(new String[] {
250 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800251 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800252 });
253
Dianne Hackborna750a632015-06-16 17:18:23 -0700254 /**
255 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
256 */
257 Bundle mIdleOptions;
258
Jose Lima235510e2014-08-13 12:50:01 -0700259 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
260 new SparseArray<>();
261 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
262 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200263 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
264 new SparseBooleanArray();
265 private boolean mNextAlarmClockMayChange;
266
267 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700268 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
269 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200270
Makoto Onukie4918212018-02-06 11:30:15 -0800271 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800272 private boolean mAppStandbyParole;
273 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800274
Dianne Hackborna750a632015-06-16 17:18:23 -0700275 /**
276 * All times are in milliseconds. These constants are kept synchronized with the system
277 * global Settings. Any access to this class or its fields should be done while
278 * holding the AlarmManagerService.mLock lock.
279 */
280 private final class Constants extends ContentObserver {
281 // Key names stored in the settings value.
282 private static final String KEY_MIN_FUTURITY = "min_futurity";
283 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800284 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700285 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
286 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
287 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
288 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700289 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700290
Suprabh Shukla75edab12018-01-29 14:09:06 -0800291 // Keys for specifying throttling delay based on app standby bucketing
292 private final String[] KEYS_APP_STANDBY_DELAY = {
293 "standby_active_delay",
294 "standby_working_delay",
295 "standby_frequent_delay",
296 "standby_rare_delay",
297 "standby_never_delay",
298 };
299
Dianne Hackborna750a632015-06-16 17:18:23 -0700300 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
301 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800302 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700303 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700304 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700305 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700306 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800307 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
308 0, // Active
309 6 * 60_000, // Working
310 30 * 60_000, // Frequent
311 2 * 60 * 60_000, // Rare
312 10 * 24 * 60 * 60_000 // Never
313 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700314
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 // Minimum futurity of a new alarm
316 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
317
318 // Minimum alarm recurrence interval
319 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
320
Christopher Tate22e919d2018-02-16 16:16:50 -0800321 // Maximum alarm recurrence interval
322 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
323
Dianne Hackborna750a632015-06-16 17:18:23 -0700324 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
325 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
326
327 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
328 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
329
330 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
331 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
332 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
333
Christopher Tate14a7bb02015-10-01 10:24:31 -0700334 // Direct alarm listener callback timeout
335 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
336
Suprabh Shukla75edab12018-01-29 14:09:06 -0800337 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
338
Dianne Hackborna750a632015-06-16 17:18:23 -0700339 private ContentResolver mResolver;
340 private final KeyValueListParser mParser = new KeyValueListParser(',');
341 private long mLastAllowWhileIdleWhitelistDuration = -1;
342
343 public Constants(Handler handler) {
344 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700345 updateAllowWhileIdleWhitelistDurationLocked();
346 }
347
348 public void start(ContentResolver resolver) {
349 mResolver = resolver;
350 mResolver.registerContentObserver(Settings.Global.getUriFor(
351 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
352 updateConstants();
353 }
354
Dianne Hackborna750a632015-06-16 17:18:23 -0700355 public void updateAllowWhileIdleWhitelistDurationLocked() {
356 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
357 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
358 BroadcastOptions opts = BroadcastOptions.makeBasic();
359 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
360 mIdleOptions = opts.toBundle();
361 }
362 }
363
364 @Override
365 public void onChange(boolean selfChange, Uri uri) {
366 updateConstants();
367 }
368
369 private void updateConstants() {
370 synchronized (mLock) {
371 try {
372 mParser.setString(Settings.Global.getString(mResolver,
373 Settings.Global.ALARM_MANAGER_CONSTANTS));
374 } catch (IllegalArgumentException e) {
375 // Failed to parse the settings string, log this and move on
376 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800377 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700378 }
379
380 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
381 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800382 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700383 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
384 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
385 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
386 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
387 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
388 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
389 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700390 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
391 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700392 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
393 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
394 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
395 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800396 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
397 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
398 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700399 updateAllowWhileIdleWhitelistDurationLocked();
400 }
401 }
402
403 void dump(PrintWriter pw) {
404 pw.println(" Settings:");
405
406 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
407 TimeUtils.formatDuration(MIN_FUTURITY, pw);
408 pw.println();
409
410 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
411 TimeUtils.formatDuration(MIN_INTERVAL, pw);
412 pw.println();
413
Christopher Tate22e919d2018-02-16 16:16:50 -0800414 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
415 TimeUtils.formatDuration(MAX_INTERVAL, pw);
416 pw.println();
417
Christopher Tate14a7bb02015-10-01 10:24:31 -0700418 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
419 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
420 pw.println();
421
Dianne Hackborna750a632015-06-16 17:18:23 -0700422 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
423 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
424 pw.println();
425
426 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
427 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
428 pw.println();
429
430 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
431 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
432 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800433
434 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
435 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
436 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
437 pw.println();
438 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700439 }
Kweku Adams61e03292017-10-19 14:27:12 -0700440
441 void dumpProto(ProtoOutputStream proto, long fieldId) {
442 final long token = proto.start(fieldId);
443
444 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
445 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800446 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700447 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
448 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
449 ALLOW_WHILE_IDLE_SHORT_TIME);
450 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
451 ALLOW_WHILE_IDLE_LONG_TIME);
452 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
453 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
454
455 proto.end(token);
456 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700457 }
458
459 final Constants mConstants;
460
Christopher Tate1590f1e2014-10-02 17:27:57 -0700461 // Alarm delivery ordering bookkeeping
462 static final int PRIO_TICK = 0;
463 static final int PRIO_WAKEUP = 1;
464 static final int PRIO_NORMAL = 2;
465
Dianne Hackborna750a632015-06-16 17:18:23 -0700466 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700467 int seq;
468 int priority;
469
470 PriorityClass() {
471 seq = mCurrentSeq - 1;
472 priority = PRIO_NORMAL;
473 }
474 }
475
Dianne Hackborna750a632015-06-16 17:18:23 -0700476 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700477 int mCurrentSeq = 0;
478
Dianne Hackborna750a632015-06-16 17:18:23 -0700479 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700480 public long when;
481 public int uid;
482 public String action;
483
484 public WakeupEvent(long theTime, int theUid, String theAction) {
485 when = theTime;
486 uid = theUid;
487 action = theAction;
488 }
489 }
490
Adam Lesinski182f73f2013-12-05 16:48:06 -0800491 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
492 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700493
Adrian Roosc42a1e12014-07-07 23:35:53 +0200494 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 long start; // These endpoints are always in ELAPSED
496 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700497 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498
499 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
500
501 Batch() {
502 start = 0;
503 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700504 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700505 }
506
507 Batch(Alarm seed) {
508 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800509 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700510 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800512 if (seed.operation == mTimeTickSender) {
513 mLastTickAdded = System.currentTimeMillis();
514 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700515 }
516
517 int size() {
518 return alarms.size();
519 }
520
521 Alarm get(int index) {
522 return alarms.get(index);
523 }
524
525 boolean canHold(long whenElapsed, long maxWhen) {
526 return (end >= whenElapsed) && (start <= maxWhen);
527 }
528
529 boolean add(Alarm alarm) {
530 boolean newStart = false;
531 // narrows the batch if necessary; presumes that canHold(alarm) is true
532 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
533 if (index < 0) {
534 index = 0 - index - 1;
535 }
536 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800537 if (alarm.operation == mTimeTickSender) {
538 mLastTickAdded = System.currentTimeMillis();
539 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 if (DEBUG_BATCH) {
541 Slog.v(TAG, "Adding " + alarm + " to " + this);
542 }
543 if (alarm.whenElapsed > start) {
544 start = alarm.whenElapsed;
545 newStart = true;
546 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700547 if (alarm.maxWhenElapsed < end) {
548 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700550 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551
552 if (DEBUG_BATCH) {
553 Slog.v(TAG, " => now " + this);
554 }
555 return newStart;
556 }
557
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800558 boolean remove(Alarm alarm) {
559 return remove(a -> (a == alarm));
560 }
561
Christopher Tate1d99c392017-12-07 16:54:04 -0800562 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700563 boolean didRemove = false;
564 long newStart = 0; // recalculate endpoints as we go
565 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700566 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700567 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800569 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700570 alarms.remove(i);
571 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200572 if (alarm.alarmClock != null) {
573 mNextAlarmClockMayChange = true;
574 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800575 if (alarm.operation == mTimeTickSender) {
576 mLastTickRemoved = System.currentTimeMillis();
577 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700578 } else {
579 if (alarm.whenElapsed > newStart) {
580 newStart = alarm.whenElapsed;
581 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700582 if (alarm.maxWhenElapsed < newEnd) {
583 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700584 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700585 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700586 i++;
587 }
588 }
589 if (didRemove) {
590 // commit the new batch bounds
591 start = newStart;
592 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700593 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700594 }
595 return didRemove;
596 }
597
Christopher Tatee0a22b32013-07-11 14:43:13 -0700598 boolean hasPackage(final String packageName) {
599 final int N = alarms.size();
600 for (int i = 0; i < N; i++) {
601 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700602 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700603 return true;
604 }
605 }
606 return false;
607 }
608
609 boolean hasWakeups() {
610 final int N = alarms.size();
611 for (int i = 0; i < N; i++) {
612 Alarm a = alarms.get(i);
613 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
614 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
615 return true;
616 }
617 }
618 return false;
619 }
620
621 @Override
622 public String toString() {
623 StringBuilder b = new StringBuilder(40);
624 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
625 b.append(" num="); b.append(size());
626 b.append(" start="); b.append(start);
627 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700628 if (flags != 0) {
629 b.append(" flgs=0x");
630 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700631 }
632 b.append('}');
633 return b.toString();
634 }
Kweku Adams61e03292017-10-19 14:27:12 -0700635
636 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
637 long nowRTC) {
638 final long token = proto.start(fieldId);
639
640 proto.write(BatchProto.START_REALTIME, start);
641 proto.write(BatchProto.END_REALTIME, end);
642 proto.write(BatchProto.FLAGS, flags);
643 for (Alarm a : alarms) {
644 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
645 }
646
647 proto.end(token);
648 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700649 }
650
651 static class BatchTimeOrder implements Comparator<Batch> {
652 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800653 long when1 = b1.start;
654 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800655 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700656 return 1;
657 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800658 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700659 return -1;
660 }
661 return 0;
662 }
663 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800664
665 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
666 @Override
667 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700668 // priority class trumps everything. TICK < WAKEUP < NORMAL
669 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
670 return -1;
671 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
672 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800673 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700674
675 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800676 if (lhs.whenElapsed < rhs.whenElapsed) {
677 return -1;
678 } else if (lhs.whenElapsed > rhs.whenElapsed) {
679 return 1;
680 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700681
682 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800683 return 0;
684 }
685 };
686
Christopher Tate1590f1e2014-10-02 17:27:57 -0700687 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
688 final int N = alarms.size();
689 for (int i = 0; i < N; i++) {
690 Alarm a = alarms.get(i);
691
692 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700693 if (a.operation != null
694 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700695 alarmPrio = PRIO_TICK;
696 } else if (a.wakeup) {
697 alarmPrio = PRIO_WAKEUP;
698 } else {
699 alarmPrio = PRIO_NORMAL;
700 }
701
702 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800703 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700704 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700705 if (packagePrio == null) {
706 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700707 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700708 }
709 a.priorityClass = packagePrio;
710
711 if (packagePrio.seq != mCurrentSeq) {
712 // first alarm we've seen in the current delivery generation from this package
713 packagePrio.priority = alarmPrio;
714 packagePrio.seq = mCurrentSeq;
715 } else {
716 // Multiple alarms from this package being delivered in this generation;
717 // bump the package's delivery class if it's warranted.
718 // TICK < WAKEUP < NORMAL
719 if (alarmPrio < packagePrio.priority) {
720 packagePrio.priority = alarmPrio;
721 }
722 }
723 }
724 }
725
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800727 static final long MIN_FUZZABLE_INTERVAL = 10000;
728 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700729 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
730
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700731 // 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 -0700732 // to run during this time are placed in mPendingWhileIdleAlarms
733 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700734 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700735 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736
Jeff Brownb880d882014-02-10 19:47:07 -0800737 public AlarmManagerService(Context context) {
738 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700739 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800740
Christopher Tate1d99c392017-12-07 16:54:04 -0800741 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800742 }
743
Christopher Tatee0a22b32013-07-11 14:43:13 -0700744 static long convertToElapsed(long when, int type) {
745 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
746 if (isRtc) {
747 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
748 }
749 return when;
750 }
751
752 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
753 // calculate the end of our nominal delivery window for the alarm.
754 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
755 // Current heuristic: batchable window is 75% of either the recurrence interval
756 // [for a periodic alarm] or of the time from now to the desired delivery time,
757 // with a minimum delay/interval of 10 seconds, under which we will simply not
758 // defer the alarm.
759 long futurity = (interval == 0)
760 ? (triggerAtTime - now)
761 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700762 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 futurity = 0;
764 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800765 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700766 }
767
768 // returns true if the batch was added at the head
769 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
770 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
771 if (index < 0) {
772 index = 0 - index - 1;
773 }
774 list.add(index, newBatch);
775 return (index == 0);
776 }
777
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800778 private void insertAndBatchAlarmLocked(Alarm alarm) {
779 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
780 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
781
782 if (whichBatch < 0) {
783 addBatchLocked(mAlarmBatches, new Batch(alarm));
784 } else {
785 final Batch batch = mAlarmBatches.get(whichBatch);
786 if (batch.add(alarm)) {
787 // The start time of this batch advanced, so batch ordering may
788 // have just been broken. Move it to where it now belongs.
789 mAlarmBatches.remove(whichBatch);
790 addBatchLocked(mAlarmBatches, batch);
791 }
792 }
793 }
794
Christopher Tate385e4982013-07-23 18:22:29 -0700795 // Return the index of the matching batch, or -1 if none found.
796 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700797 final int N = mAlarmBatches.size();
798 for (int i = 0; i < N; i++) {
799 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700800 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700801 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700802 }
803 }
Christopher Tate385e4982013-07-23 18:22:29 -0700804 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700805 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800806 /** @return total count of the alarms in a set of alarm batches. */
807 static int getAlarmCount(ArrayList<Batch> batches) {
808 int ret = 0;
809
810 final int size = batches.size();
811 for (int i = 0; i < size; i++) {
812 ret += batches.get(i).size();
813 }
814 return ret;
815 }
816
817 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
818 if (alarms.size() == 0) {
819 return false;
820 }
821 final int batchSize = alarms.size();
822 for (int j = 0; j < batchSize; j++) {
823 if (alarms.get(j).operation == mTimeTickSender) {
824 return true;
825 }
826 }
827 return false;
828 }
829
830 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
831 final int numBatches = batches.size();
832 for (int i = 0; i < numBatches; i++) {
833 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
834 return true;
835 }
836 }
837 return false;
838 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700839
840 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
841 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700842 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700843 rebatchAllAlarmsLocked(true);
844 }
845 }
846
847 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800848 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800849 final int oldCount =
850 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
851 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
852 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
853
Christopher Tate4cb338d2013-07-26 13:11:31 -0700854 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
855 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700856 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700857 final long nowElapsed = SystemClock.elapsedRealtime();
858 final int oldBatches = oldSet.size();
859 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
860 Batch batch = oldSet.get(batchNum);
861 final int N = batch.size();
862 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700863 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700864 }
865 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700866 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
867 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
868 + " to " + mPendingIdleUntil);
869 if (mPendingIdleUntil == null) {
870 // Somehow we lost this... we need to restore all of the pending alarms.
871 restorePendingWhileIdleAlarmsLocked();
872 }
873 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800874 final int newCount =
875 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
876 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
877 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
878
879 if (oldCount != newCount) {
880 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
881 }
882 if (oldHasTick != newHasTick) {
883 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
884 }
885
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700886 rescheduleKernelAlarmsLocked();
887 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800888 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700889 }
890
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800891 /**
892 * Re-orders the alarm batches based on newly evaluated send times based on the current
893 * app-standby buckets
894 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
895 * null indicates all
896 * @return True if there was any reordering done to the current list.
897 */
898 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
899 final long start = mStatLogger.getTime();
900 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
901
902 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
903 final Batch batch = mAlarmBatches.get(batchIndex);
904 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
905 final Alarm alarm = batch.get(alarmIndex);
906 final Pair<String, Integer> packageUser =
907 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
908 if (targetPackages != null && !targetPackages.contains(packageUser)) {
909 continue;
910 }
911 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
912 batch.remove(alarm);
913 rescheduledAlarms.add(alarm);
914 }
915 }
916 if (batch.size() == 0) {
917 mAlarmBatches.remove(batchIndex);
918 }
919 }
920 for (int i = 0; i < rescheduledAlarms.size(); i++) {
921 final Alarm a = rescheduledAlarms.get(i);
922 insertAndBatchAlarmLocked(a);
923 }
924
925 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
926 return rescheduledAlarms.size() > 0;
927 }
928
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700929 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
930 a.when = a.origWhen;
931 long whenElapsed = convertToElapsed(a.when, a.type);
932 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700933 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700934 // Exact
935 maxElapsed = whenElapsed;
936 } else {
937 // Not exact. Preserve any explicit window, otherwise recalculate
938 // the window based on the alarm's new futurity. Note that this
939 // reflects a policy of preferring timely to deferred delivery.
940 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800941 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700942 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
943 }
944 a.whenElapsed = whenElapsed;
945 a.maxWhenElapsed = maxElapsed;
946 setImplLocked(a, true, doValidate);
947 }
948
Christopher Tate22e919d2018-02-16 16:16:50 -0800949 static long clampPositive(long val) {
950 return (val >= 0) ? val : Long.MAX_VALUE;
951 }
952
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700953 /**
954 * Sends alarms that were blocked due to user applied background restrictions - either because
955 * the user lifted those or the uid came to foreground.
956 *
957 * @param uid uid to filter on
958 * @param packageName package to filter on, or null for all packages in uid
959 */
960 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
961 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
962 if (alarmsForUid == null || alarmsForUid.size() == 0) {
963 return;
964 }
965 final ArrayList<Alarm> alarmsToDeliver;
966 if (packageName != null) {
967 if (DEBUG_BG_LIMIT) {
968 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
969 }
970 alarmsToDeliver = new ArrayList<>();
971 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
972 final Alarm a = alarmsForUid.get(i);
973 if (a.matches(packageName)) {
974 alarmsToDeliver.add(alarmsForUid.remove(i));
975 }
976 }
977 if (alarmsForUid.size() == 0) {
978 mPendingBackgroundAlarms.remove(uid);
979 }
980 } else {
981 if (DEBUG_BG_LIMIT) {
982 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
983 }
984 alarmsToDeliver = alarmsForUid;
985 mPendingBackgroundAlarms.remove(uid);
986 }
987 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
988 }
989
Makoto Onuki2206af32017-11-21 16:25:35 -0800990 /**
991 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
992 * restricted.
993 *
994 * This is only called when the global "force all apps-standby" flag changes or when the
995 * power save whitelist changes, so it's okay to be slow.
996 */
997 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700998 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800999
1000 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1001 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1002
1003 if (alarmsToDeliver.size() > 0) {
1004 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
1005 }
1006 }
1007
1008 @VisibleForTesting
1009 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1010 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1011 Predicate<Alarm> isBackgroundRestricted) {
1012
1013 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1014 final int uid = pendingAlarms.keyAt(uidIndex);
1015 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1016
1017 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1018 final Alarm alarm = alarmsForUid.get(alarmIndex);
1019
1020 if (isBackgroundRestricted.test(alarm)) {
1021 continue;
1022 }
1023
1024 unrestrictedAlarms.add(alarm);
1025 alarmsForUid.remove(alarmIndex);
1026 }
1027
1028 if (alarmsForUid.size() == 0) {
1029 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001030 }
1031 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001032 }
1033
1034 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1035 final int N = alarms.size();
1036 boolean hasWakeup = false;
1037 for (int i = 0; i < N; i++) {
1038 final Alarm alarm = alarms.get(i);
1039 if (alarm.wakeup) {
1040 hasWakeup = true;
1041 }
1042 alarm.count = 1;
1043 // Recurring alarms may have passed several alarm intervals while the
1044 // alarm was kept pending. Send the appropriate trigger count.
1045 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001046 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001047 // Also schedule its next recurrence
1048 final long delta = alarm.count * alarm.repeatInterval;
1049 final long nextElapsed = alarm.whenElapsed + delta;
1050 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1051 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1052 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1053 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1054 // Kernel alarms will be rescheduled as needed in setImplLocked
1055 }
1056 }
1057 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1058 // No need to wakeup for non wakeup alarms
1059 if (mPendingNonWakeupAlarms.size() == 0) {
1060 mStartCurrentDelayTime = nowELAPSED;
1061 mNextNonWakeupDeliveryTime = nowELAPSED
1062 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1063 }
1064 mPendingNonWakeupAlarms.addAll(alarms);
1065 mNumDelayedAlarms += alarms.size();
1066 } else {
1067 if (DEBUG_BG_LIMIT) {
1068 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1069 }
1070 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1071 if (mPendingNonWakeupAlarms.size() > 0) {
1072 alarms.addAll(mPendingNonWakeupAlarms);
1073 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1074 mTotalDelayTime += thisDelayTime;
1075 if (mMaxDelayTime < thisDelayTime) {
1076 mMaxDelayTime = thisDelayTime;
1077 }
1078 mPendingNonWakeupAlarms.clear();
1079 }
1080 calculateDeliveryPriorities(alarms);
1081 Collections.sort(alarms, mAlarmDispatchComparator);
1082 deliverAlarmsLocked(alarms, nowELAPSED);
1083 }
1084 }
1085
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001086 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001087 if (RECORD_DEVICE_IDLE_ALARMS) {
1088 IdleDispatchEntry ent = new IdleDispatchEntry();
1089 ent.uid = 0;
1090 ent.pkg = "FINISH IDLE";
1091 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1092 mAllowWhileIdleDispatches.add(ent);
1093 }
1094
Dianne Hackborn35d54032015-04-23 10:30:43 -07001095 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001096 if (mPendingWhileIdleAlarms.size() > 0) {
1097 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1098 mPendingWhileIdleAlarms = new ArrayList<>();
1099 final long nowElapsed = SystemClock.elapsedRealtime();
1100 for (int i=alarms.size() - 1; i >= 0; i--) {
1101 Alarm a = alarms.get(i);
1102 reAddAlarmLocked(a, nowElapsed, false);
1103 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001104 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001105
1106 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 rescheduleKernelAlarmsLocked();
1108 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001109
1110 // And send a TIME_TICK right now, since it is important to get the UI updated.
1111 try {
1112 mTimeTickSender.send();
1113 } catch (PendingIntent.CanceledException e) {
1114 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001115 }
1116
Christopher Tate14a7bb02015-10-01 10:24:31 -07001117 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001118 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001119 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001120 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001121 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001122 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001123 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001124 final BroadcastStats mBroadcastStats;
1125 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001126 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001127
Christopher Tate14a7bb02015-10-01 10:24:31 -07001128 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1129 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1130 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001131 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001132 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001133 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001134 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001135 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001136 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001137 mBroadcastStats = (pendingIntent != null)
1138 ? service.getStatsLocked(pendingIntent)
1139 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001140 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001141 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001142 fs = new FilterStats(mBroadcastStats, mTag);
1143 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001144 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001145 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001146 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001147 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001148 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001149
1150 @Override
1151 public String toString() {
1152 return "InFlight{"
1153 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001154 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001155 + ", workSource=" + mWorkSource
1156 + ", uid=" + mUid
1157 + ", tag=" + mTag
1158 + ", broadcastStats=" + mBroadcastStats
1159 + ", filterStats=" + mFilterStats
1160 + ", alarmType=" + mAlarmType
1161 + "}";
1162 }
Kweku Adams61e03292017-10-19 14:27:12 -07001163
1164 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1165 final long token = proto.start(fieldId);
1166
1167 proto.write(InFlightProto.UID, mUid);
1168 proto.write(InFlightProto.TAG, mTag);
1169 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1170 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1171 if (mPendingIntent != null) {
1172 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1173 }
1174 if (mBroadcastStats != null) {
1175 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1176 }
1177 if (mFilterStats != null) {
1178 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1179 }
1180 if (mWorkSource != null) {
1181 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1182 }
1183
1184 proto.end(token);
1185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001187
Adam Lesinski182f73f2013-12-05 16:48:06 -08001188 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001189 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001190 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001191
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001192 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001194 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 int numWakeup;
1196 long startTime;
1197 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001198
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001199 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001200 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001201 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001202 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001203
1204 @Override
1205 public String toString() {
1206 return "FilterStats{"
1207 + "tag=" + mTag
1208 + ", lastTime=" + lastTime
1209 + ", aggregateTime=" + aggregateTime
1210 + ", count=" + count
1211 + ", numWakeup=" + numWakeup
1212 + ", startTime=" + startTime
1213 + ", nesting=" + nesting
1214 + "}";
1215 }
Kweku Adams61e03292017-10-19 14:27:12 -07001216
1217 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1218 final long token = proto.start(fieldId);
1219
1220 proto.write(FilterStatsProto.TAG, mTag);
1221 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1222 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1223 proto.write(FilterStatsProto.COUNT, count);
1224 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1225 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1226 proto.write(FilterStatsProto.NESTING, nesting);
1227
1228 proto.end(token);
1229 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001230 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001231
Adam Lesinski182f73f2013-12-05 16:48:06 -08001232 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001233 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001234 final String mPackageName;
1235
1236 long aggregateTime;
1237 int count;
1238 int numWakeup;
1239 long startTime;
1240 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001241 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001242
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001243 BroadcastStats(int uid, String packageName) {
1244 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001245 mPackageName = packageName;
1246 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001247
1248 @Override
1249 public String toString() {
1250 return "BroadcastStats{"
1251 + "uid=" + mUid
1252 + ", packageName=" + mPackageName
1253 + ", aggregateTime=" + aggregateTime
1254 + ", count=" + count
1255 + ", numWakeup=" + numWakeup
1256 + ", startTime=" + startTime
1257 + ", nesting=" + nesting
1258 + "}";
1259 }
Kweku Adams61e03292017-10-19 14:27:12 -07001260
1261 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1262 final long token = proto.start(fieldId);
1263
1264 proto.write(BroadcastStatsProto.UID, mUid);
1265 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1266 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1267 proto.write(BroadcastStatsProto.COUNT, count);
1268 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1269 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1270 proto.write(BroadcastStatsProto.NESTING, nesting);
1271
1272 proto.end(token);
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001275
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001276 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1277 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001278
1279 int mNumDelayedAlarms = 0;
1280 long mTotalDelayTime = 0;
1281 long mMaxDelayTime = 0;
1282
Adam Lesinski182f73f2013-12-05 16:48:06 -08001283 @Override
1284 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001285 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001286 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001287
1288 // We have to set current TimeZone info to kernel
1289 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001291
Christopher Tate247571462017-04-10 11:45:05 -07001292 // Also sure that we're booting with a halfway sensible current time
1293 if (mNativeData != 0) {
1294 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1295 if (System.currentTimeMillis() < systemBuildTime) {
1296 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1297 + ", advancing to build time " + systemBuildTime);
1298 setKernelTime(mNativeData, systemBuildTime);
1299 }
1300 }
1301
Christopher Tatebb9cce52017-04-18 14:19:43 -07001302 // Determine SysUI's uid
1303 final PackageManager packMan = getContext().getPackageManager();
1304 try {
1305 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1306 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1307 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1308 mSystemUiUid = sysUi.uid;
1309 } else {
1310 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1311 + " defined by non-privileged app " + sysUi.packageName
1312 + " - ignoring");
1313 }
1314 } catch (NameNotFoundException e) {
1315 }
1316
1317 if (mSystemUiUid <= 0) {
1318 Slog.wtf(TAG, "SysUI package not found!");
1319 }
1320
Adam Lesinski182f73f2013-12-05 16:48:06 -08001321 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001322 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001323
Adam Lesinski182f73f2013-12-05 16:48:06 -08001324 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001326 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001327 | Intent.FLAG_RECEIVER_FOREGROUND
1328 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001329 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001330 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001331 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1332 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001333 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001334 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001335
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001337 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 mClockReceiver.scheduleTimeTickEvent();
1339 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001340 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001341 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001342
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001343 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001344 AlarmThread waitThread = new AlarmThread();
1345 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001347 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001349
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001350 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001351 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001352 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1353 | ActivityManager.UID_OBSERVER_ACTIVE,
1354 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001355 } catch (RemoteException e) {
1356 // ignored; both services live in system_server
1357 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001358 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001359 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001360
1361 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001362 public void onBootPhase(int phase) {
1363 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1364 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001365 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001366 mLocalDeviceIdleController
1367 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001368 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1369 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001370
1371 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1372 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001373 }
1374 }
1375
1376 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 protected void finalize() throws Throwable {
1378 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001379 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 } finally {
1381 super.finalize();
1382 }
1383 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001384
mswest463f4c99d2018-02-01 10:13:10 -08001385 boolean setTimeImpl(long millis) {
1386 if (mNativeData == 0) {
1387 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1388 return false;
1389 }
1390
1391 synchronized (mLock) {
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001392 final long currentTimeMillis = System.currentTimeMillis();
1393 setKernelTime(mNativeData, millis);
1394 final TimeZone timeZone = TimeZone.getDefault();
1395 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1396 final int newTzOffset = timeZone.getOffset(millis);
1397 if (currentTzOffset != newTzOffset) {
1398 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
1399 setKernelTimezone(mNativeData, -(newTzOffset / 60000));
1400 }
1401 // The native implementation of setKernelTime can return -1 even when the kernel
1402 // time was set correctly, so assume setting kernel time was successful and always
1403 // return true.
1404 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001405 }
1406 }
1407
Adam Lesinski182f73f2013-12-05 16:48:06 -08001408 void setTimeZoneImpl(String tz) {
1409 if (TextUtils.isEmpty(tz)) {
1410 return;
David Christieebe51fc2013-07-26 13:23:29 -07001411 }
1412
Adam Lesinski182f73f2013-12-05 16:48:06 -08001413 TimeZone zone = TimeZone.getTimeZone(tz);
1414 // Prevent reentrant calls from stepping on each other when writing
1415 // the time zone property
1416 boolean timeZoneWasChanged = false;
1417 synchronized (this) {
1418 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1419 if (current == null || !current.equals(zone.getID())) {
1420 if (localLOGV) {
1421 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1422 }
1423 timeZoneWasChanged = true;
1424 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1425 }
1426
1427 // Update the kernel timezone information
1428 // Kernel tracks time offsets as 'minutes west of GMT'
1429 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001430 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001431 }
1432
1433 TimeZone.setDefault(null);
1434
1435 if (timeZoneWasChanged) {
1436 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001437 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001438 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001439 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001440 intent.putExtra("time-zone", zone.getID());
1441 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001444
Adam Lesinski182f73f2013-12-05 16:48:06 -08001445 void removeImpl(PendingIntent operation) {
1446 if (operation == null) {
1447 return;
1448 }
1449 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001450 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001451 }
1452 }
1453
1454 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001455 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1456 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1457 int callingUid, String callingPackage) {
1458 // must be *either* PendingIntent or AlarmReceiver, but not both
1459 if ((operation == null && directReceiver == null)
1460 || (operation != null && directReceiver != null)) {
1461 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1462 // NB: previous releases failed silently here, so we are continuing to do the same
1463 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 return;
1465 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001466
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001467 // Sanity check the window length. This will catch people mistakenly
1468 // trying to pass an end-of-window timestamp rather than a duration.
1469 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1470 Slog.w(TAG, "Window length " + windowLength
1471 + "ms suspiciously long; limiting to 1 hour");
1472 windowLength = AlarmManager.INTERVAL_HOUR;
1473 }
1474
Christopher Tate498c6cb2014-11-17 16:09:27 -08001475 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001476 // seconds when the API expects milliseconds, or apps trying shenanigans
1477 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001478 final long minInterval = mConstants.MIN_INTERVAL;
1479 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001480 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001481 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001482 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001483 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001484 } else if (interval > mConstants.MAX_INTERVAL) {
1485 Slog.w(TAG, "Suspiciously long interval " + interval
1486 + " millis; clamping");
1487 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001488 }
1489
Christopher Tatee0a22b32013-07-11 14:43:13 -07001490 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1491 throw new IllegalArgumentException("Invalid alarm type " + type);
1492 }
1493
Christopher Tate5f221e82013-07-30 17:13:15 -07001494 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001495 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001496 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001497 + " pid=" + what);
1498 triggerAtTime = 0;
1499 }
1500
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001501 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001502 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1503 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001504 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001505 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1506
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001507 final long maxElapsed;
1508 if (windowLength == AlarmManager.WINDOW_EXACT) {
1509 maxElapsed = triggerElapsed;
1510 } else if (windowLength < 0) {
1511 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001512 // Fix this window in place, so that as time approaches we don't collapse it.
1513 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001514 } else {
1515 maxElapsed = triggerElapsed + windowLength;
1516 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001519 if (DEBUG_BATCH) {
1520 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001521 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001522 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001523 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001525 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001526 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1527 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001528 }
1529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530
Christopher Tate3e04b472013-10-21 17:51:31 -07001531 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001532 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1533 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1534 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001535 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001536 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1537 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001538 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001539 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001540 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1541 + " -- package not allowed to start");
1542 return;
1543 }
1544 } catch (RemoteException e) {
1545 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001546 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001547 setImplLocked(a, false, doValidate);
1548 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001549
Christopher Tatef2159712018-03-27 16:04:14 -07001550 /**
1551 * Return the minimum time that should elapse before an app in the specified bucket
1552 * can receive alarms again
1553 */
Suprabh Shukla75edab12018-01-29 14:09:06 -08001554 private long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001555 // UsageStats bucket values are treated as floors of their behavioral range.
1556 // In other words, a bucket value between WORKING and ACTIVE is treated as
1557 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1558 // values.
1559 final int index;
1560
1561 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1562 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1563 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1564 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1565 else index = ACTIVE_INDEX;
1566
1567 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001568 }
1569
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001570 /**
1571 * Adjusts the alarm delivery time based on the current app standby bucket.
1572 * @param alarm The alarm to adjust
1573 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001574 */
1575 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001576 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001577 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001578 }
1579 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001580 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001581 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001582 alarm.whenElapsed = alarm.expectedWhenElapsed;
1583 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1584 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001585 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001586 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001587 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001588 final long oldWhenElapsed = alarm.whenElapsed;
1589 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1590
Suprabh Shukla75edab12018-01-29 14:09:06 -08001591 final String sourcePackage = alarm.sourcePackage;
1592 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1593 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1594 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1595
1596 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1597 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1598 if (lastElapsed > 0) {
1599 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001600 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001601 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001602 } else {
1603 // app is now eligible to run alarms at the originally requested window.
1604 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001605 alarm.whenElapsed = alarm.expectedWhenElapsed;
1606 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001607 }
1608 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001609 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001610 }
1611
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001612 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1613 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001614 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001615 // The caller has given the time they want this to happen at, however we need
1616 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001617 // bring us out of idle at an earlier time.
1618 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001619 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001620 }
1621 // Add fuzz to make the alarm go off some time before the actual desired time.
1622 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001623 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001624 if (fuzz > 0) {
1625 if (mRandom == null) {
1626 mRandom = new Random();
1627 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001628 final int delta = mRandom.nextInt(fuzz);
1629 a.whenElapsed -= delta;
1630 if (false) {
1631 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1632 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1633 Slog.d(TAG, "Applied fuzz: " + fuzz);
1634 Slog.d(TAG, "Final delta: " + delta);
1635 Slog.d(TAG, "Final when: " + a.whenElapsed);
1636 }
1637 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001638 }
1639
1640 } else if (mPendingIdleUntil != null) {
1641 // We currently have an idle until alarm scheduled; if the new alarm has
1642 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001643 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1644 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1645 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001646 == 0) {
1647 mPendingWhileIdleAlarms.add(a);
1648 return;
1649 }
1650 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001651 if (RECORD_DEVICE_IDLE_ALARMS) {
1652 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1653 IdleDispatchEntry ent = new IdleDispatchEntry();
1654 ent.uid = a.uid;
1655 ent.pkg = a.operation.getCreatorPackage();
1656 ent.tag = a.operation.getTag("");
1657 ent.op = "SET";
1658 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1659 ent.argRealtime = a.whenElapsed;
1660 mAllowWhileIdleDispatches.add(ent);
1661 }
1662 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001663 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001664 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001666 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001667 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001668 }
1669
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001670 boolean needRebatch = false;
1671
1672 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001673 if (RECORD_DEVICE_IDLE_ALARMS) {
1674 if (mPendingIdleUntil == null) {
1675 IdleDispatchEntry ent = new IdleDispatchEntry();
1676 ent.uid = 0;
1677 ent.pkg = "START IDLE";
1678 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1679 mAllowWhileIdleDispatches.add(ent);
1680 }
1681 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001682 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1683 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1684 + " to " + a);
1685 }
1686
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001687 mPendingIdleUntil = a;
1688 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001689 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1690 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1691 mNextWakeFromIdle = a;
1692 // If this wake from idle is earlier than whatever was previously scheduled,
1693 // and we are currently idling, then we need to rebatch alarms in case the idle
1694 // until time needs to be updated.
1695 if (mPendingIdleUntil != null) {
1696 needRebatch = true;
1697 }
1698 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001699 }
1700
1701 if (!rebatching) {
1702 if (DEBUG_VALIDATE) {
1703 if (doValidate && !validateConsistencyLocked()) {
1704 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1705 + " when(hex)=" + Long.toHexString(a.when)
1706 + " whenElapsed=" + a.whenElapsed
1707 + " maxWhenElapsed=" + a.maxWhenElapsed
1708 + " interval=" + a.repeatInterval + " op=" + a.operation
1709 + " flags=0x" + Integer.toHexString(a.flags));
1710 rebatchAllAlarmsLocked(false);
1711 needRebatch = false;
1712 }
1713 }
1714
1715 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001716 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001717 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001718
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001719 rescheduleKernelAlarmsLocked();
1720 updateNextAlarmClockLocked();
1721 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001722 }
1723
Christopher Tate1d99c392017-12-07 16:54:04 -08001724 /**
1725 * System-process internal API
1726 */
1727 private final class LocalService implements AlarmManagerInternal {
1728 @Override
1729 public void removeAlarmsForUid(int uid) {
1730 synchronized (mLock) {
1731 removeLocked(uid);
1732 }
1733 }
1734 }
1735
1736 /**
1737 * Public-facing binder interface
1738 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001739 private final IBinder mService = new IAlarmManager.Stub() {
1740 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001741 public void set(String callingPackage,
1742 int type, long triggerAtTime, long windowLength, long interval, int flags,
1743 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1744 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001745 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001746
1747 // make sure the caller is not lying about which package should be blamed for
1748 // wakelock time spent in alarm delivery
1749 mAppOps.checkPackage(callingUid, callingPackage);
1750
1751 // Repeating alarms must use PendingIntent, not direct listener
1752 if (interval != 0) {
1753 if (directReceiver != null) {
1754 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1755 }
1756 }
1757
Adam Lesinski182f73f2013-12-05 16:48:06 -08001758 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001759 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001760 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001761 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001762 }
1763
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001764 // No incoming callers can request either WAKE_FROM_IDLE or
1765 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1766 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1767 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1768
1769 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1770 // manager when to come out of idle mode, which is only for DeviceIdleController.
1771 if (callingUid != Process.SYSTEM_UID) {
1772 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1773 }
1774
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001775 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001776 if (windowLength == AlarmManager.WINDOW_EXACT) {
1777 flags |= AlarmManager.FLAG_STANDALONE;
1778 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001779
1780 // If this alarm is for an alarm clock, then it must be standalone and we will
1781 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001782 if (alarmClock != null) {
1783 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001784
1785 // If the caller is a core system component or on the user's whitelist, and not calling
1786 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1787 // This means we will allow these alarms to go off as normal even while idle, with no
1788 // timing restrictions.
1789 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001790 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001791 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001792 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001793 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1794 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001795 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001796
Christopher Tate14a7bb02015-10-01 10:24:31 -07001797 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1798 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001799 }
Christopher Tate89779822012-08-31 14:40:03 -07001800
Adam Lesinski182f73f2013-12-05 16:48:06 -08001801 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001802 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001803 getContext().enforceCallingOrSelfPermission(
1804 "android.permission.SET_TIME",
1805 "setTime");
1806
mswest463f4c99d2018-02-01 10:13:10 -08001807 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001808 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001809
1810 @Override
1811 public void setTimeZone(String tz) {
1812 getContext().enforceCallingOrSelfPermission(
1813 "android.permission.SET_TIME_ZONE",
1814 "setTimeZone");
1815
1816 final long oldId = Binder.clearCallingIdentity();
1817 try {
1818 setTimeZoneImpl(tz);
1819 } finally {
1820 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001823
Adam Lesinski182f73f2013-12-05 16:48:06 -08001824 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001825 public void remove(PendingIntent operation, IAlarmListener listener) {
1826 if (operation == null && listener == null) {
1827 Slog.w(TAG, "remove() with no intent or listener");
1828 return;
1829 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001830
Christopher Tate14a7bb02015-10-01 10:24:31 -07001831 synchronized (mLock) {
1832 removeLocked(operation, listener);
1833 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001834 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001835
Adam Lesinski182f73f2013-12-05 16:48:06 -08001836 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001837 public long getNextWakeFromIdleTime() {
1838 return getNextWakeFromIdleTimeImpl();
1839 }
1840
1841 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001842 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001843 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1844 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1845 "getNextAlarmClock", null);
1846
1847 return getNextAlarmClockImpl(userId);
1848 }
1849
1850 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001851 public long currentNetworkTimeMillis() {
1852 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1853 if (time.hasCache()) {
1854 return time.currentTimeMillis();
1855 } else {
1856 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1857 }
1858 }
1859
1860 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001861 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001862 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001863
1864 if (args.length > 0 && "--proto".equals(args[0])) {
1865 dumpProto(fd);
1866 } else {
1867 dumpImpl(pw);
1868 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001869 }
mswest463f4c99d2018-02-01 10:13:10 -08001870
1871 @Override
1872 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1873 FileDescriptor err, String[] args, ShellCallback callback,
1874 ResultReceiver resultReceiver) {
1875 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1876 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001877 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001878
Adam Lesinski182f73f2013-12-05 16:48:06 -08001879 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001880 synchronized (mLock) {
1881 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001882 mConstants.dump(pw);
1883 pw.println();
1884
Makoto Onukie4918212018-02-06 11:30:15 -08001885 if (mAppStateTracker != null) {
1886 mAppStateTracker.dump(pw, " ");
1887 pw.println();
1888 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001889
Suprabh Shukla75edab12018-01-29 14:09:06 -08001890 pw.println(" App Standby Parole: " + mAppStandbyParole);
1891 pw.println();
1892
Christopher Tatee0a22b32013-07-11 14:43:13 -07001893 final long nowRTC = System.currentTimeMillis();
1894 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001895 final long nowUPTIME = SystemClock.uptimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001896 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001897
Dianne Hackborna750a632015-06-16 17:18:23 -07001898 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001899 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001900 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001901 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001902 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001903 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001904 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1905 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001906 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001907 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1908 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001909 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1910 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001911
1912 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1913 if (ssm != null) {
1914 pw.println();
1915 pw.print(" RuntimeStarted=");
1916 pw.print(sdf.format(
1917 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1918 if (ssm.isRuntimeRestarted()) {
1919 pw.print(" (Runtime restarted)");
1920 }
1921 pw.println();
1922 pw.print(" Runtime uptime (elapsed): ");
1923 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1924 pw.println();
1925 pw.print(" Runtime uptime (uptime): ");
1926 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1927 pw.println();
1928 }
1929
Dianne Hackbornc3527222015-05-13 14:03:20 -07001930 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001931 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001932 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001933 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1934 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001935 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001936 pw.print(" Max wakeup delay: ");
1937 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1938 pw.println();
1939 pw.print(" Time since last dispatch: ");
1940 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1941 pw.println();
1942 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001943 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001944 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001945
1946 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1947 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001948 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001949 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001950 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001951 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001952 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
1953 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08001954 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1955 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001956 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001957 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001958 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07001959
1960 pw.print(" Next kernel non-wakeup alarm: ");
1961 TimeUtils.formatDuration(getNextAlarm(mNativeData, ELAPSED_REALTIME), pw);
1962 pw.println();
1963 pw.print(" Next kernel wakeup alarm: ");
1964 TimeUtils.formatDuration(getNextAlarm(mNativeData, ELAPSED_REALTIME_WAKEUP), pw);
1965 pw.println();
1966
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001967 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001968 pw.print(" = "); pw.println(mLastWakeup);
1969 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1970 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001971 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001972
John Spurlock604a5ee2015-06-01 12:27:22 -04001973 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001974 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001975 final TreeSet<Integer> users = new TreeSet<>();
1976 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1977 users.add(mNextAlarmClockForUser.keyAt(i));
1978 }
1979 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1980 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1981 }
1982 for (int user : users) {
1983 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1984 final long time = next != null ? next.getTriggerTime() : 0;
1985 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001986 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001987 pw.print(" pendingSend:"); pw.print(pendingSend);
1988 pw.print(" time:"); pw.print(time);
1989 if (time > 0) {
1990 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1991 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1992 }
1993 pw.println();
1994 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001995 if (mAlarmBatches.size() > 0) {
1996 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001997 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001998 pw.println(mAlarmBatches.size());
1999 for (Batch b : mAlarmBatches) {
2000 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002001 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002002 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002004 pw.println();
2005 pw.println(" Pending user blocked background alarms: ");
2006 boolean blocked = false;
2007 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2008 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2009 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2010 blocked = true;
2011 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2012 }
2013 }
2014 if (!blocked) {
2015 pw.println(" none");
2016 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002017
Suprabh Shukla75edab12018-01-29 14:09:06 -08002018 pw.println(" mLastAlarmDeliveredForPackage:");
2019 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2020 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2021 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2022 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2023 pw.println();
2024 }
2025 pw.println();
2026
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002027 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002028 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002029 pw.println(" Idle mode state:");
2030 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002031 if (mPendingIdleUntil != null) {
2032 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002033 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002034 } else {
2035 pw.println("null");
2036 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002037 pw.println(" Pending alarms:");
2038 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002039 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002040 if (mNextWakeFromIdle != null) {
2041 pw.println();
2042 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002043 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002044 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002045
2046 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002047 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002048 if (mPendingNonWakeupAlarms.size() > 0) {
2049 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002050 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002051 } else {
2052 pw.println("(none)");
2053 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002054 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002055 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2056 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002057 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002058 pw.print(", max non-interactive time: ");
2059 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2060 pw.println();
2061
2062 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002063 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002064 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2065 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2066 pw.print(" Listener send count: "); pw.println(mListenerCount);
2067 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002068 pw.println();
2069
Christopher Tate7f2a0352015-12-08 10:24:33 -08002070 if (mInFlight.size() > 0) {
2071 pw.println("Outstanding deliveries:");
2072 for (int i = 0; i < mInFlight.size(); i++) {
2073 pw.print(" #"); pw.print(i); pw.print(": ");
2074 pw.println(mInFlight.get(i));
2075 }
2076 pw.println();
2077 }
2078
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002079 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002080 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002081 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002082 pw.print(" UID ");
2083 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2084 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002085 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002086 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2087 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2088
2089 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2090 pw.print(" Next allowed:");
2091 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2092 pw.print(" (");
2093 TimeUtils.formatDuration(minInterval, 0, pw);
2094 pw.print(")");
2095
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002096 pw.println();
2097 }
2098 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002099
2100 pw.print(" mUseAllowWhileIdleShortTime: [");
2101 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2102 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2103 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2104 pw.print(" ");
2105 }
2106 }
2107 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002108 pw.println();
2109
Dianne Hackborn81038902012-11-26 17:04:09 -08002110 if (mLog.dump(pw, " Recent problems", " ")) {
2111 pw.println();
2112 }
2113
2114 final FilterStats[] topFilters = new FilterStats[10];
2115 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2116 @Override
2117 public int compare(FilterStats lhs, FilterStats rhs) {
2118 if (lhs.aggregateTime < rhs.aggregateTime) {
2119 return 1;
2120 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2121 return -1;
2122 }
2123 return 0;
2124 }
2125 };
2126 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002127 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002128 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2129 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2130 for (int ip=0; ip<uidStats.size(); ip++) {
2131 BroadcastStats bs = uidStats.valueAt(ip);
2132 for (int is=0; is<bs.filterStats.size(); is++) {
2133 FilterStats fs = bs.filterStats.valueAt(is);
2134 int pos = len > 0
2135 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2136 if (pos < 0) {
2137 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002138 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002139 if (pos < topFilters.length) {
2140 int copylen = topFilters.length - pos - 1;
2141 if (copylen > 0) {
2142 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2143 }
2144 topFilters[pos] = fs;
2145 if (len < topFilters.length) {
2146 len++;
2147 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002148 }
2149 }
2150 }
2151 }
2152 if (len > 0) {
2153 pw.println(" Top Alarms:");
2154 for (int i=0; i<len; i++) {
2155 FilterStats fs = topFilters[i];
2156 pw.print(" ");
2157 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2158 TimeUtils.formatDuration(fs.aggregateTime, pw);
2159 pw.print(" running, "); pw.print(fs.numWakeup);
2160 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002161 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2162 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002163 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002164 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002165 pw.println();
2166 }
2167 }
2168
2169 pw.println(" ");
2170 pw.println(" Alarm Stats:");
2171 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002172 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2173 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2174 for (int ip=0; ip<uidStats.size(); ip++) {
2175 BroadcastStats bs = uidStats.valueAt(ip);
2176 pw.print(" ");
2177 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2178 UserHandle.formatUid(pw, bs.mUid);
2179 pw.print(":");
2180 pw.print(bs.mPackageName);
2181 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2182 pw.print(" running, "); pw.print(bs.numWakeup);
2183 pw.println(" wakeups:");
2184 tmpFilters.clear();
2185 for (int is=0; is<bs.filterStats.size(); is++) {
2186 tmpFilters.add(bs.filterStats.valueAt(is));
2187 }
2188 Collections.sort(tmpFilters, comparator);
2189 for (int i=0; i<tmpFilters.size(); i++) {
2190 FilterStats fs = tmpFilters.get(i);
2191 pw.print(" ");
2192 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2193 TimeUtils.formatDuration(fs.aggregateTime, pw);
2194 pw.print(" "); pw.print(fs.numWakeup);
2195 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002196 pw.print(" alarms, last ");
2197 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2198 pw.println(":");
2199 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002200 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002201 pw.println();
2202 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002203 }
2204 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002205 pw.println();
2206 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002207
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002208 if (RECORD_DEVICE_IDLE_ALARMS) {
2209 pw.println();
2210 pw.println(" Allow while idle dispatches:");
2211 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2212 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2213 pw.print(" ");
2214 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2215 pw.print(": ");
2216 UserHandle.formatUid(pw, ent.uid);
2217 pw.print(":");
2218 pw.println(ent.pkg);
2219 if (ent.op != null) {
2220 pw.print(" ");
2221 pw.print(ent.op);
2222 pw.print(" / ");
2223 pw.print(ent.tag);
2224 if (ent.argRealtime != 0) {
2225 pw.print(" (");
2226 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2227 pw.print(")");
2228 }
2229 pw.println();
2230 }
2231 }
2232 }
2233
Christopher Tate18a75f12013-07-01 18:18:59 -07002234 if (WAKEUP_STATS) {
2235 pw.println();
2236 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002237 long last = -1;
2238 for (WakeupEvent event : mRecentWakeups) {
2239 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2240 pw.print('|');
2241 if (last < 0) {
2242 pw.print('0');
2243 } else {
2244 pw.print(event.when - last);
2245 }
2246 last = event.when;
2247 pw.print('|'); pw.print(event.uid);
2248 pw.print('|'); pw.print(event.action);
2249 pw.println();
2250 }
2251 pw.println();
2252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 }
2254 }
2255
Kweku Adams61e03292017-10-19 14:27:12 -07002256 void dumpProto(FileDescriptor fd) {
2257 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2258
2259 synchronized (mLock) {
2260 final long nowRTC = System.currentTimeMillis();
2261 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002262 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2263 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2264 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002265 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002266 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002267 mLastTimeChangeRealtime);
2268
Yi Jin2b30f322018-02-20 15:41:47 -08002269 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002270
Makoto Onukie4918212018-02-06 11:30:15 -08002271 if (mAppStateTracker != null) {
2272 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002273 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002274 }
Kweku Adams61e03292017-10-19 14:27:12 -07002275
Yi Jin2b30f322018-02-20 15:41:47 -08002276 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002277 if (!mInteractive) {
2278 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002279 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002280 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002281 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002282 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002283 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002284 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002285 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002286 nowElapsed - mNextNonWakeupDeliveryTime);
2287 }
2288
Yi Jin2b30f322018-02-20 15:41:47 -08002289 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002290 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002291 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002292 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002293 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002294 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002295 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002296 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002297 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002298
2299 final TreeSet<Integer> users = new TreeSet<>();
2300 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2301 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2302 users.add(mNextAlarmClockForUser.keyAt(i));
2303 }
2304 final int pendingSendNextAlarmClockChangedForUserSize =
2305 mPendingSendNextAlarmClockChangedForUser.size();
2306 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2307 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2308 }
2309 for (int user : users) {
2310 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2311 final long time = next != null ? next.getTriggerTime() : 0;
2312 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002313 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002314 proto.write(AlarmClockMetadataProto.USER, user);
2315 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2316 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2317 proto.end(aToken);
2318 }
2319 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002320 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002321 nowElapsed, nowRTC);
2322 }
2323 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2324 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2325 if (blockedAlarms != null) {
2326 for (Alarm a : blockedAlarms) {
2327 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002328 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002329 nowElapsed, nowRTC);
2330 }
2331 }
2332 }
2333 if (mPendingIdleUntil != null) {
2334 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002335 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002336 }
2337 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002338 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002339 nowElapsed, nowRTC);
2340 }
2341 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002342 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002343 nowElapsed, nowRTC);
2344 }
2345
2346 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002347 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002348 nowElapsed, nowRTC);
2349 }
2350
Yi Jin2b30f322018-02-20 15:41:47 -08002351 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2352 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2353 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2354 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002355 mNonInteractiveTime);
2356
Yi Jin2b30f322018-02-20 15:41:47 -08002357 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2358 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2359 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2360 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2361 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002362
2363 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002364 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002365 }
2366
Kweku Adams61e03292017-10-19 14:27:12 -07002367 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2368 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002369 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002370 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2371 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2372
Yi Jin2b30f322018-02-20 15:41:47 -08002373 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2374 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2375 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002376 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002377 proto.end(token);
2378 }
2379
Makoto Onukiadb50d82018-01-29 16:20:30 -08002380 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2381 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002382 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002383 mUseAllowWhileIdleShortTime.keyAt(i));
2384 }
2385 }
2386
Yi Jin2b30f322018-02-20 15:41:47 -08002387 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002388
2389 final FilterStats[] topFilters = new FilterStats[10];
2390 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2391 @Override
2392 public int compare(FilterStats lhs, FilterStats rhs) {
2393 if (lhs.aggregateTime < rhs.aggregateTime) {
2394 return 1;
2395 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2396 return -1;
2397 }
2398 return 0;
2399 }
2400 };
2401 int len = 0;
2402 // Get the top 10 FilterStats, ordered by aggregateTime.
2403 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2404 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2405 for (int ip = 0; ip < uidStats.size(); ++ip) {
2406 BroadcastStats bs = uidStats.valueAt(ip);
2407 for (int is = 0; is < bs.filterStats.size(); ++is) {
2408 FilterStats fs = bs.filterStats.valueAt(is);
2409 int pos = len > 0
2410 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2411 if (pos < 0) {
2412 pos = -pos - 1;
2413 }
2414 if (pos < topFilters.length) {
2415 int copylen = topFilters.length - pos - 1;
2416 if (copylen > 0) {
2417 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2418 }
2419 topFilters[pos] = fs;
2420 if (len < topFilters.length) {
2421 len++;
2422 }
2423 }
2424 }
2425 }
2426 }
2427 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002428 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002429 FilterStats fs = topFilters[i];
2430
Yi Jin2b30f322018-02-20 15:41:47 -08002431 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2432 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002433 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002434 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002435
2436 proto.end(token);
2437 }
2438
2439 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2440 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2441 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2442 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002443 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002444
2445 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002446 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002447
2448 // uidStats is an ArrayMap, which we can't sort.
2449 tmpFilters.clear();
2450 for (int is = 0; is < bs.filterStats.size(); ++is) {
2451 tmpFilters.add(bs.filterStats.valueAt(is));
2452 }
2453 Collections.sort(tmpFilters, comparator);
2454 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002455 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002456 }
2457
2458 proto.end(token);
2459 }
2460 }
2461
2462 if (RECORD_DEVICE_IDLE_ALARMS) {
2463 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2464 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2465 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002466 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002467
2468 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2469 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2470 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2471 proto.write(IdleDispatchEntryProto.OP, ent.op);
2472 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2473 ent.elapsedRealtime);
2474 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2475
2476 proto.end(token);
2477 }
2478 }
2479
2480 if (WAKEUP_STATS) {
2481 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002482 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002483 proto.write(WakeupEventProto.UID, event.uid);
2484 proto.write(WakeupEventProto.ACTION, event.action);
2485 proto.write(WakeupEventProto.WHEN, event.when);
2486 proto.end(token);
2487 }
2488 }
2489 }
2490
2491 proto.flush();
2492 }
2493
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002494 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002495 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2496 PrintWriter pw = new PrintWriter(bs);
2497 final long nowRTC = System.currentTimeMillis();
2498 final long nowELAPSED = SystemClock.elapsedRealtime();
2499 final int NZ = mAlarmBatches.size();
2500 for (int iz = 0; iz < NZ; iz++) {
2501 Batch bz = mAlarmBatches.get(iz);
2502 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002503 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002504 pw.flush();
2505 Slog.v(TAG, bs.toString());
2506 bs.reset();
2507 }
2508 }
2509
2510 private boolean validateConsistencyLocked() {
2511 if (DEBUG_VALIDATE) {
2512 long lastTime = Long.MIN_VALUE;
2513 final int N = mAlarmBatches.size();
2514 for (int i = 0; i < N; i++) {
2515 Batch b = mAlarmBatches.get(i);
2516 if (b.start >= lastTime) {
2517 // duplicate start times are okay because of standalone batches
2518 lastTime = b.start;
2519 } else {
2520 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002521 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2522 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002523 return false;
2524 }
2525 }
2526 }
2527 return true;
2528 }
2529
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002530 private Batch findFirstWakeupBatchLocked() {
2531 final int N = mAlarmBatches.size();
2532 for (int i = 0; i < N; i++) {
2533 Batch b = mAlarmBatches.get(i);
2534 if (b.hasWakeups()) {
2535 return b;
2536 }
2537 }
2538 return null;
2539 }
2540
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002541 long getNextWakeFromIdleTimeImpl() {
2542 synchronized (mLock) {
2543 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2544 }
2545 }
2546
2547 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002548 synchronized (mLock) {
2549 return mNextAlarmClockForUser.get(userId);
2550 }
2551 }
2552
2553 /**
2554 * Recomputes the next alarm clock for all users.
2555 */
2556 private void updateNextAlarmClockLocked() {
2557 if (!mNextAlarmClockMayChange) {
2558 return;
2559 }
2560 mNextAlarmClockMayChange = false;
2561
Jose Lima235510e2014-08-13 12:50:01 -07002562 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002563 nextForUser.clear();
2564
2565 final int N = mAlarmBatches.size();
2566 for (int i = 0; i < N; i++) {
2567 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2568 final int M = alarms.size();
2569
2570 for (int j = 0; j < M; j++) {
2571 Alarm a = alarms.get(j);
2572 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002573 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002574 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002575
2576 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002577 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002578 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002579 " for user " + userId);
2580 }
2581
2582 // Alarms and batches are sorted by time, no need to compare times here.
2583 if (nextForUser.get(userId) == null) {
2584 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002585 } else if (a.alarmClock.equals(current)
2586 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2587 // same/earlier time and it's the one we cited before, so stick with it
2588 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002589 }
2590 }
2591 }
2592 }
2593
2594 // Update mNextAlarmForUser with new values.
2595 final int NN = nextForUser.size();
2596 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002597 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002598 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002599 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002600 if (!newAlarm.equals(currentAlarm)) {
2601 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2602 }
2603 }
2604
2605 // Remove users without any alarm clocks scheduled.
2606 final int NNN = mNextAlarmClockForUser.size();
2607 for (int i = NNN - 1; i >= 0; i--) {
2608 int userId = mNextAlarmClockForUser.keyAt(i);
2609 if (nextForUser.get(userId) == null) {
2610 updateNextAlarmInfoForUserLocked(userId, null);
2611 }
2612 }
2613 }
2614
Jose Lima235510e2014-08-13 12:50:01 -07002615 private void updateNextAlarmInfoForUserLocked(int userId,
2616 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002617 if (alarmClock != null) {
2618 if (DEBUG_ALARM_CLOCK) {
2619 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002620 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002621 }
2622 mNextAlarmClockForUser.put(userId, alarmClock);
2623 } else {
2624 if (DEBUG_ALARM_CLOCK) {
2625 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2626 }
2627 mNextAlarmClockForUser.remove(userId);
2628 }
2629
2630 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2631 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2632 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2633 }
2634
2635 /**
2636 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2637 * for which alarm clocks have changed since the last call to this.
2638 *
2639 * Do not call with a lock held. Only call from mHandler's thread.
2640 *
2641 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2642 */
2643 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002644 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002645 pendingUsers.clear();
2646
2647 synchronized (mLock) {
2648 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2649 for (int i = 0; i < N; i++) {
2650 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2651 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2652 }
2653 mPendingSendNextAlarmClockChangedForUser.clear();
2654 }
2655
2656 final int N = pendingUsers.size();
2657 for (int i = 0; i < N; i++) {
2658 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002659 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002660 Settings.System.putStringForUser(getContext().getContentResolver(),
2661 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002662 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002663 userId);
2664
2665 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2666 new UserHandle(userId));
2667 }
2668 }
2669
2670 /**
2671 * Formats an alarm like platform/packages/apps/DeskClock used to.
2672 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002673 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2674 int userId) {
2675 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002676 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2677 return (info == null) ? "" :
2678 DateFormat.format(pattern, info.getTriggerTime()).toString();
2679 }
2680
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002681 /**
2682 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2683 * by more than half a minute, log a wtf.
2684 */
2685 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2686 final StringBuilder errorMsg = new StringBuilder();
2687 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002688 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002689 stuck = true;
2690 errorMsg.append("[mNextNonWakeup=");
2691 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002692 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002693 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002694 errorMsg.append(", mLastWakeup=");
2695 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2696 errorMsg.append(", timerfd_gettime=" + getNextAlarm(mNativeData, ELAPSED_REALTIME));
2697 errorMsg.append("];");
2698 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002699 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002700 stuck = true;
2701 errorMsg.append("[mNextWakeup=");
2702 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002703 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002704 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002705 errorMsg.append(", mLastWakeup=");
2706 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2707 errorMsg.append(", timerfd_gettime="
2708 + getNextAlarm(mNativeData, ELAPSED_REALTIME_WAKEUP));
2709 errorMsg.append("];");
2710 }
2711 if (stuck) {
2712 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2713 }
2714 }
2715
Adam Lesinski182f73f2013-12-05 16:48:06 -08002716 void rescheduleKernelAlarmsLocked() {
2717 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2718 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002719 final long nowElapsed = SystemClock.elapsedRealtime();
2720 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002721 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002722 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002723 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002724 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002725 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002726 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002727 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002728 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002729 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002730 if (firstBatch != firstWakeup) {
2731 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002732 }
2733 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002734 if (mPendingNonWakeupAlarms.size() > 0) {
2735 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2736 nextNonWakeup = mNextNonWakeupDeliveryTime;
2737 }
2738 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002739 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002740 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002741 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002742 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2743 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002744 }
2745
Christopher Tate14a7bb02015-10-01 10:24:31 -07002746 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002747 if (operation == null && directReceiver == null) {
2748 if (localLOGV) {
2749 Slog.w(TAG, "requested remove() of null operation",
2750 new RuntimeException("here"));
2751 }
2752 return;
2753 }
2754
Adam Lesinski182f73f2013-12-05 16:48:06 -08002755 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002756 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002757 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2758 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002759 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002760 if (b.size() == 0) {
2761 mAlarmBatches.remove(i);
2762 }
2763 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002764 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002765 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002766 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2767 mPendingWhileIdleAlarms.remove(i);
2768 }
2769 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002770 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2771 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2772 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2773 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2774 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2775 alarmsForUid.remove(j);
2776 }
2777 }
2778 if (alarmsForUid.size() == 0) {
2779 mPendingBackgroundAlarms.removeAt(i);
2780 }
2781 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002782 if (didRemove) {
2783 if (DEBUG_BATCH) {
2784 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2785 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002786 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002787 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002788 mPendingIdleUntil = null;
2789 restorePending = true;
2790 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002791 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002792 mNextWakeFromIdle = null;
2793 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002795 if (restorePending) {
2796 restorePendingWhileIdleAlarmsLocked();
2797 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002798 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002799 }
2800 }
2801
Christopher Tate1d99c392017-12-07 16:54:04 -08002802 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002803 if (uid == Process.SYSTEM_UID) {
2804 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2805 return;
2806 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002807 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002808 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002809 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2810 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002811 didRemove |= b.remove(whichAlarms);
2812 if (b.size() == 0) {
2813 mAlarmBatches.remove(i);
2814 }
2815 }
2816 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2817 final Alarm a = mPendingWhileIdleAlarms.get(i);
2818 if (a.uid == uid) {
2819 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2820 mPendingWhileIdleAlarms.remove(i);
2821 }
2822 }
2823 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2824 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2825 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2826 if (alarmsForUid.get(j).uid == uid) {
2827 alarmsForUid.remove(j);
2828 }
2829 }
2830 if (alarmsForUid.size() == 0) {
2831 mPendingBackgroundAlarms.removeAt(i);
2832 }
2833 }
2834 if (didRemove) {
2835 if (DEBUG_BATCH) {
2836 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2837 }
2838 rebatchAllAlarmsLocked(true);
2839 rescheduleKernelAlarmsLocked();
2840 updateNextAlarmClockLocked();
2841 }
2842 }
2843
2844 void removeLocked(final String packageName) {
2845 if (packageName == null) {
2846 if (localLOGV) {
2847 Slog.w(TAG, "requested remove() of null packageName",
2848 new RuntimeException("here"));
2849 }
2850 return;
2851 }
2852
2853 boolean didRemove = false;
2854 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002855 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002856 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2857 Batch b = mAlarmBatches.get(i);
2858 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002859 if (b.size() == 0) {
2860 mAlarmBatches.remove(i);
2861 }
2862 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002863 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2864 if (oldHasTick != newHasTick) {
2865 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2866 }
2867
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002868 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002869 final Alarm a = mPendingWhileIdleAlarms.get(i);
2870 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002871 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2872 mPendingWhileIdleAlarms.remove(i);
2873 }
2874 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002875 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2876 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2877 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2878 if (alarmsForUid.get(j).matches(packageName)) {
2879 alarmsForUid.remove(j);
2880 }
2881 }
2882 if (alarmsForUid.size() == 0) {
2883 mPendingBackgroundAlarms.removeAt(i);
2884 }
2885 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002886 if (didRemove) {
2887 if (DEBUG_BATCH) {
2888 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2889 }
2890 rebatchAllAlarmsLocked(true);
2891 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002892 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002893 }
2894 }
2895
Christopher Tate1d99c392017-12-07 16:54:04 -08002896 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002897 if (uid == Process.SYSTEM_UID) {
2898 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2899 return;
2900 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002901 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002902 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2903 try {
2904 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2905 uid, a.packageName)) {
2906 return true;
2907 }
2908 } catch (RemoteException e) { /* fall through */}
2909 return false;
2910 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002911 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2912 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002913 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002914 if (b.size() == 0) {
2915 mAlarmBatches.remove(i);
2916 }
2917 }
2918 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2919 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002920 if (a.uid == uid) {
2921 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2922 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002923 }
2924 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002925 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2926 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2927 mPendingBackgroundAlarms.removeAt(i);
2928 }
2929 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002930 if (didRemove) {
2931 if (DEBUG_BATCH) {
2932 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2933 }
2934 rebatchAllAlarmsLocked(true);
2935 rescheduleKernelAlarmsLocked();
2936 updateNextAlarmClockLocked();
2937 }
2938 }
2939
Adam Lesinski182f73f2013-12-05 16:48:06 -08002940 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002941 if (userHandle == UserHandle.USER_SYSTEM) {
2942 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2943 return;
2944 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002945 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002946 final Predicate<Alarm> whichAlarms =
2947 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002948 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2949 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002950 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002951 if (b.size() == 0) {
2952 mAlarmBatches.remove(i);
2953 }
2954 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002955 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002956 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002957 == userHandle) {
2958 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2959 mPendingWhileIdleAlarms.remove(i);
2960 }
2961 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002962 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2963 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2964 mPendingBackgroundAlarms.removeAt(i);
2965 }
2966 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002967 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2968 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2969 mLastAllowWhileIdleDispatch.removeAt(i);
2970 }
2971 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002972
2973 if (didRemove) {
2974 if (DEBUG_BATCH) {
2975 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2976 }
2977 rebatchAllAlarmsLocked(true);
2978 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002979 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002980 }
2981 }
2982
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002983 void interactiveStateChangedLocked(boolean interactive) {
2984 if (mInteractive != interactive) {
2985 mInteractive = interactive;
2986 final long nowELAPSED = SystemClock.elapsedRealtime();
2987 if (interactive) {
2988 if (mPendingNonWakeupAlarms.size() > 0) {
2989 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2990 mTotalDelayTime += thisDelayTime;
2991 if (mMaxDelayTime < thisDelayTime) {
2992 mMaxDelayTime = thisDelayTime;
2993 }
2994 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2995 mPendingNonWakeupAlarms.clear();
2996 }
2997 if (mNonInteractiveStartTime > 0) {
2998 long dur = nowELAPSED - mNonInteractiveStartTime;
2999 if (dur > mNonInteractiveTime) {
3000 mNonInteractiveTime = dur;
3001 }
3002 }
3003 } else {
3004 mNonInteractiveStartTime = nowELAPSED;
3005 }
3006 }
3007 }
3008
Adam Lesinski182f73f2013-12-05 16:48:06 -08003009 boolean lookForPackageLocked(String packageName) {
3010 for (int i = 0; i < mAlarmBatches.size(); i++) {
3011 Batch b = mAlarmBatches.get(i);
3012 if (b.hasPackage(packageName)) {
3013 return true;
3014 }
3015 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003016 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003017 final Alarm a = mPendingWhileIdleAlarms.get(i);
3018 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003019 return true;
3020 }
3021 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003022 return false;
3023 }
3024
3025 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08003026 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08003027 // The kernel never triggers alarms with negative wakeup times
3028 // so we ensure they are positive.
3029 long alarmSeconds, alarmNanoseconds;
3030 if (when < 0) {
3031 alarmSeconds = 0;
3032 alarmNanoseconds = 0;
3033 } else {
3034 alarmSeconds = when / 1000;
3035 alarmNanoseconds = (when % 1000) * 1000 * 1000;
3036 }
Kweku Adams61e03292017-10-19 14:27:12 -07003037
Christopher Tate8b98ade2018-02-09 11:13:19 -08003038 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
3039 if (result != 0) {
3040 final long nowElapsed = SystemClock.elapsedRealtime();
3041 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3042 + " type=" + type + " when=" + when
3043 + " @ (" + alarmSeconds + "," + alarmNanoseconds
3044 + "), ret = " + result + " = " + Os.strerror(result));
3045 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003046 } else {
3047 Message msg = Message.obtain();
3048 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003049
Adam Lesinski182f73f2013-12-05 16:48:06 -08003050 mHandler.removeMessages(ALARM_EVENT);
3051 mHandler.sendMessageAtTime(msg, when);
3052 }
3053 }
3054
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003055 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003056 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 for (int i=list.size()-1; i>=0; i--) {
3058 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003059 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3060 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003061 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003062 }
3063 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003064
3065 private static final String labelForType(int type) {
3066 switch (type) {
3067 case RTC: return "RTC";
3068 case RTC_WAKEUP : return "RTC_WAKEUP";
3069 case ELAPSED_REALTIME : return "ELAPSED";
3070 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003071 }
3072 return "--unknown--";
3073 }
3074
3075 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003076 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003077 for (int i=list.size()-1; i>=0; i--) {
3078 Alarm a = list.get(i);
3079 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003080 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3081 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003082 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003083 }
3084 }
3085
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003086 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003087 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003088 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003089 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003090 return false;
3091 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003092 if (alarm.operation != null) {
3093 if (alarm.operation.isActivity()) {
3094 // Don't defer starting actual UI
3095 return false;
3096 }
3097 if (alarm.operation.isForegroundService()) {
3098 // FG service alarms are nearly as important; consult AST policy
3099 exemptOnBatterySaver = true;
3100 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003101 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003102 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003103 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003104 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003105 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3106 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003107 }
3108
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003109 private native long init();
3110 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003111 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003112 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003113 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003114 private native int setKernelTimezone(long nativeData, int minuteswest);
Suprabh Shukla2324e982018-06-05 21:06:22 -07003115 private native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116
Makoto Onukiadb50d82018-01-29 16:20:30 -08003117 private long getWhileIdleMinIntervalLocked(int uid) {
3118 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003119 final boolean ebs = (mAppStateTracker != null)
3120 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003121 if (!dozing && !ebs) {
3122 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3123 }
3124 if (dozing) {
3125 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3126 }
3127 if (mUseAllowWhileIdleShortTime.get(uid)) {
3128 // if the last allow-while-idle went off while uid was fg, or the uid
3129 // recently came into fg, don't block the alarm for long.
3130 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3131 }
3132 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3133 }
3134
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003135 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003136 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003137 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003138 // batches are temporally sorted, so we need only pull from the
3139 // start of the list until we either empty it or hit a batch
3140 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003141 while (mAlarmBatches.size() > 0) {
3142 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003143 if (batch.start > nowELAPSED) {
3144 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003145 break;
3146 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003147
Christopher Tatee0a22b32013-07-11 14:43:13 -07003148 // We will (re)schedule some alarms now; don't let that interfere
3149 // with delivery of this current batch
3150 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003151
Christopher Tatee0a22b32013-07-11 14:43:13 -07003152 final int N = batch.size();
3153 for (int i = 0; i < N; i++) {
3154 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003155
3156 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3157 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003158 // schedule such alarms. The first such alarm from an app is always delivered.
3159 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003160 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003161 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003162 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3163 // alarm went off for this app. Reschedule the alarm to be in the
3164 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003165 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003166 if (alarm.maxWhenElapsed < minTime) {
3167 alarm.maxWhenElapsed = minTime;
3168 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003169 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003170 if (RECORD_DEVICE_IDLE_ALARMS) {
3171 IdleDispatchEntry ent = new IdleDispatchEntry();
3172 ent.uid = alarm.uid;
3173 ent.pkg = alarm.operation.getCreatorPackage();
3174 ent.tag = alarm.operation.getTag("");
3175 ent.op = "RESCHEDULE";
3176 ent.elapsedRealtime = nowELAPSED;
3177 ent.argRealtime = lastTime;
3178 mAllowWhileIdleDispatches.add(ent);
3179 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003180 setImplLocked(alarm, true, false);
3181 continue;
3182 }
3183 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003184 if (isBackgroundRestricted(alarm)) {
3185 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3186 if (DEBUG_BG_LIMIT) {
3187 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3188 }
3189 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3190 if (alarmsForUid == null) {
3191 alarmsForUid = new ArrayList<>();
3192 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3193 }
3194 alarmsForUid.add(alarm);
3195 continue;
3196 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003197
Christopher Tatee0a22b32013-07-11 14:43:13 -07003198 alarm.count = 1;
3199 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003200 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3201 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003202 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003203 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003204 if (mPendingIdleUntil == alarm) {
3205 mPendingIdleUntil = null;
3206 rebatchAllAlarmsLocked(false);
3207 restorePendingWhileIdleAlarmsLocked();
3208 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003209 if (mNextWakeFromIdle == alarm) {
3210 mNextWakeFromIdle = null;
3211 rebatchAllAlarmsLocked(false);
3212 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003213
3214 // Recurring alarms may have passed several alarm intervals while the
3215 // phone was asleep or off, so pass a trigger count when sending them.
3216 if (alarm.repeatInterval > 0) {
3217 // this adjustment will be zero if we're late by
3218 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003219 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003220
3221 // Also schedule its next recurrence
3222 final long delta = alarm.count * alarm.repeatInterval;
3223 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003224 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003225 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003226 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3227 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003228 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003229
Christopher Tate864d42e2014-12-02 11:48:53 -08003230 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003231 hasWakeup = true;
3232 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003233
3234 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3235 if (alarm.alarmClock != null) {
3236 mNextAlarmClockMayChange = true;
3237 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003238 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003239 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003240
Christopher Tate1590f1e2014-10-02 17:27:57 -07003241 // This is a new alarm delivery set; bump the sequence number to indicate that
3242 // all apps' alarm delivery classes should be recalculated.
3243 mCurrentSeq++;
3244 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003245 Collections.sort(triggerList, mAlarmDispatchComparator);
3246
3247 if (localLOGV) {
3248 for (int i=0; i<triggerList.size(); i++) {
3249 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3250 }
3251 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003252
3253 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003254 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003255
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003256 /**
3257 * This Comparator sorts Alarms into increasing time order.
3258 */
3259 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3260 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003261 long when1 = a1.whenElapsed;
3262 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003263 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264 return 1;
3265 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003266 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003267 return -1;
3268 }
3269 return 0;
3270 }
3271 }
Kweku Adams61e03292017-10-19 14:27:12 -07003272
Makoto Onuki2206af32017-11-21 16:25:35 -08003273 @VisibleForTesting
3274 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003275 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003276 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003277 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003278 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003279 public final IAlarmListener listener;
3280 public final String listenerTag;
3281 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003282 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003283 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003284 public final AlarmManager.AlarmClockInfo alarmClock;
3285 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003286 public final int creatorUid;
3287 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003288 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 public int count;
3290 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003291 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003292 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003293 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003294 // Expected alarm expiry time before app standby deferring is applied.
3295 public long expectedWhenElapsed;
3296 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003298 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003299
Christopher Tate3e04b472013-10-21 17:51:31 -07003300 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003301 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3302 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3303 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003304 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003305 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003306 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3307 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003308 when = _when;
3309 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003310 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003311 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003312 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003313 repeatInterval = _interval;
3314 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003315 listener = _rec;
3316 listenerTag = _listenerTag;
3317 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003318 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003319 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003320 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003321 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003322 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003323 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003324 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003326
Christopher Tate14a7bb02015-10-01 10:24:31 -07003327 public static String makeTag(PendingIntent pi, String tag, int type) {
3328 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3329 ? "*walarm*:" : "*alarm*:";
3330 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3331 }
3332
3333 public WakeupEvent makeWakeupEvent(long nowRTC) {
3334 return new WakeupEvent(nowRTC, creatorUid,
3335 (operation != null)
3336 ? operation.getIntent().getAction()
3337 : ("<listener>:" + listenerTag));
3338 }
3339
3340 // Returns true if either matches
3341 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3342 return (operation != null)
3343 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003344 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003345 }
3346
3347 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003348 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003349 }
3350
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003351 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003352 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003353 StringBuilder sb = new StringBuilder(128);
3354 sb.append("Alarm{");
3355 sb.append(Integer.toHexString(System.identityHashCode(this)));
3356 sb.append(" type ");
3357 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003358 sb.append(" when ");
3359 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003360 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003361 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003362 sb.append('}');
3363 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003364 }
3365
Kweku Adams61e03292017-10-19 14:27:12 -07003366 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003367 SimpleDateFormat sdf) {
3368 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003369 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003370 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003371 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3372 expectedWhenElapsed, nowELAPSED, pw);
3373 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3374 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003375 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3376 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003377 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3378 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003379 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003380 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003381 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003382 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003383 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003384 }
3385 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003386 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003387 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003388 pw.print(" count="); pw.print(count);
3389 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003390 if (alarmClock != null) {
3391 pw.print(prefix); pw.println("Alarm clock:");
3392 pw.print(prefix); pw.print(" triggerTime=");
3393 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3394 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3395 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003396 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003397 if (listener != null) {
3398 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3399 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003400 }
Kweku Adams61e03292017-10-19 14:27:12 -07003401
3402 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3403 long nowRTC) {
3404 final long token = proto.start(fieldId);
3405
3406 proto.write(AlarmProto.TAG, statsTag);
3407 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003408 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003409 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3410 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3411 proto.write(AlarmProto.COUNT, count);
3412 proto.write(AlarmProto.FLAGS, flags);
3413 if (alarmClock != null) {
3414 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3415 }
3416 if (operation != null) {
3417 operation.writeToProto(proto, AlarmProto.OPERATION);
3418 }
3419 if (listener != null) {
3420 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3421 }
3422
3423 proto.end(token);
3424 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003425 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003426
Christopher Tatee0a22b32013-07-11 14:43:13 -07003427 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3428 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003429 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3430 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003431 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003432 break;
3433 }
3434
Christopher Tatee0a22b32013-07-11 14:43:13 -07003435 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003436 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3437 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003438 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003439 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003440 }
3441 }
3442
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003443 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3444 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3445 if (timeSinceOn < 5*60*1000) {
3446 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3447 return 2*60*1000;
3448 } else if (timeSinceOn < 30*60*1000) {
3449 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3450 return 15*60*1000;
3451 } else {
3452 // Otherwise, we will delay by at most an hour.
3453 return 60*60*1000;
3454 }
3455 }
3456
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003457 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003458 if (duration < 15*60*1000) {
3459 // If the duration until the time is less than 15 minutes, the maximum fuzz
3460 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003461 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003462 } else if (duration < 90*60*1000) {
3463 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3464 return 15*60*1000;
3465 } else {
3466 // Otherwise, we will fuzz by at most half an hour.
3467 return 30*60*1000;
3468 }
3469 }
3470
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003471 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3472 if (mInteractive) {
3473 return false;
3474 }
3475 if (mLastAlarmDeliveryTime <= 0) {
3476 return false;
3477 }
minho.choo649acab2014-12-12 16:13:55 +09003478 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003479 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3480 // and the next delivery time is in the past, then just deliver them all. This
3481 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3482 return false;
3483 }
3484 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3485 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3486 }
3487
3488 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3489 mLastAlarmDeliveryTime = nowELAPSED;
3490 for (int i=0; i<triggerList.size(); i++) {
3491 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003492 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003493 if (alarm.wakeup) {
3494 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3495 } else {
3496 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3497 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003498 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003499 if (localLOGV) {
3500 Slog.v(TAG, "sending alarm " + alarm);
3501 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003502 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003503 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3504 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003505 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003506 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003507 } catch (RuntimeException e) {
3508 Slog.w(TAG, "Failure sending alarm.", e);
3509 }
Tim Murray175c0f92017-11-28 15:01:04 -08003510 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003511 }
3512 }
3513
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003514 private boolean isExemptFromAppStandby(Alarm a) {
3515 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3516 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3517 }
3518
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003519 private class AlarmThread extends Thread
3520 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003521 private int mFalseWakeups;
3522 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 public AlarmThread()
3524 {
3525 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003526 mFalseWakeups = 0;
3527 mWtfThreshold = 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003528 }
Kweku Adams61e03292017-10-19 14:27:12 -07003529
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003530 public void run()
3531 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003532 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 while (true)
3535 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003536 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003537
Dianne Hackbornc3527222015-05-13 14:03:20 -07003538 final long nowRTC = System.currentTimeMillis();
3539 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003540 synchronized (mLock) {
3541 mLastWakeup = nowELAPSED;
3542 }
3543
3544 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003545
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003546 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003547 // The kernel can give us spurious time change notifications due to
3548 // small adjustments it makes internally; we want to filter those out.
3549 final long lastTimeChangeClockTime;
3550 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003551 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003552 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3553 expectedClockTime = lastTimeChangeClockTime
3554 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003555 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003556 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3557 || nowRTC > (expectedClockTime+1000)) {
3558 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003559 // let's do it!
3560 if (DEBUG_BATCH) {
3561 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3562 }
3563 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003564 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003565 rebatchAllAlarms();
3566 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003567 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003568 synchronized (mLock) {
3569 mNumTimeChanged++;
3570 mLastTimeChangeClockTime = nowRTC;
3571 mLastTimeChangeRealtime = nowELAPSED;
3572 }
3573 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3574 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003575 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003576 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3577 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003578 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3579
3580 // The world has changed on us, so we need to re-evaluate alarms
3581 // regardless of whether the kernel has told us one went off.
3582 result |= IS_WAKEUP_MASK;
3583 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003584 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003585
Dianne Hackbornc3527222015-05-13 14:03:20 -07003586 if (result != TIME_CHANGED_MASK) {
3587 // If this was anything besides just a time change, then figure what if
3588 // anything to do about alarms.
3589 synchronized (mLock) {
3590 if (localLOGV) Slog.v(
3591 TAG, "Checking for alarms... rtc=" + nowRTC
3592 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003593
Dianne Hackbornc3527222015-05-13 14:03:20 -07003594 if (WAKEUP_STATS) {
3595 if ((result & IS_WAKEUP_MASK) != 0) {
3596 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3597 int n = 0;
3598 for (WakeupEvent event : mRecentWakeups) {
3599 if (event.when > newEarliest) break;
3600 n++; // number of now-stale entries at the list head
3601 }
3602 for (int i = 0; i < n; i++) {
3603 mRecentWakeups.remove();
3604 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003605
Dianne Hackbornc3527222015-05-13 14:03:20 -07003606 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003607 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003608 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003609
Christopher Tate8b98ade2018-02-09 11:13:19 -08003610 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003611 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3612 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3613 // if there are no wakeup alarms and the screen is off, we can
3614 // delay what we have so far until the future.
3615 if (mPendingNonWakeupAlarms.size() == 0) {
3616 mStartCurrentDelayTime = nowELAPSED;
3617 mNextNonWakeupDeliveryTime = nowELAPSED
3618 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3619 }
3620 mPendingNonWakeupAlarms.addAll(triggerList);
3621 mNumDelayedAlarms += triggerList.size();
3622 rescheduleKernelAlarmsLocked();
3623 updateNextAlarmClockLocked();
3624 } else {
3625 // now deliver the alarm intents; if there are pending non-wakeup
3626 // alarms, we need to merge them in to the list. note we don't
3627 // just deliver them first because we generally want non-wakeup
3628 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003629 if (mPendingNonWakeupAlarms.size() > 0) {
3630 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3631 triggerList.addAll(mPendingNonWakeupAlarms);
3632 Collections.sort(triggerList, mAlarmDispatchComparator);
3633 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3634 mTotalDelayTime += thisDelayTime;
3635 if (mMaxDelayTime < thisDelayTime) {
3636 mMaxDelayTime = thisDelayTime;
3637 }
3638 mPendingNonWakeupAlarms.clear();
3639 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003640 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3641 if (++mFalseWakeups >= mWtfThreshold) {
3642 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3643 + ") false wakeups, nowElapsed=" + nowELAPSED);
3644 if (mWtfThreshold < 100_000) {
3645 mWtfThreshold *= 10;
3646 } else {
3647 mFalseWakeups = 0;
3648 }
3649 }
3650 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003651 final ArraySet<Pair<String, Integer>> triggerPackages =
3652 new ArraySet<>();
3653 for (int i = 0; i < triggerList.size(); i++) {
3654 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003655 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003656 triggerPackages.add(Pair.create(
3657 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003658 }
3659 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003660 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003661 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3662 rescheduleKernelAlarmsLocked();
3663 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003664 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003665 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003666
3667 } else {
3668 // Just in case -- even though no wakeup flag was set, make sure
3669 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003670 synchronized (mLock) {
3671 rescheduleKernelAlarmsLocked();
3672 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003673 }
3674 }
3675 }
3676 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003677
David Christieebe51fc2013-07-26 13:23:29 -07003678 /**
3679 * Attribute blame for a WakeLock.
3680 * @param pi PendingIntent to attribute blame to if ws is null.
3681 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003682 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003683 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003684 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003685 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003686 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003687 final boolean unimportant = pi == mTimeTickSender;
3688 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003689 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003690 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003691 } else {
3692 mWakeLock.setHistoryTag(null);
3693 }
3694 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003695 if (ws != null) {
3696 mWakeLock.setWorkSource(ws);
3697 return;
3698 }
3699
Christopher Tate14a7bb02015-10-01 10:24:31 -07003700 final int uid = (knownUid >= 0)
3701 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003702 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003703 if (uid >= 0) {
3704 mWakeLock.setWorkSource(new WorkSource(uid));
3705 return;
3706 }
3707 } catch (Exception e) {
3708 }
3709
3710 // Something went wrong; fall back to attributing the lock to the OS
3711 mWakeLock.setWorkSource(null);
3712 }
3713
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003714 private class AlarmHandler extends Handler {
3715 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003716 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3717 public static final int LISTENER_TIMEOUT = 3;
3718 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003719 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3720 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003721 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003722
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003723 public AlarmHandler() {
3724 }
Kweku Adams61e03292017-10-19 14:27:12 -07003725
Makoto Onuki4d298b52018-02-05 10:54:58 -08003726 public void postRemoveForStopped(int uid) {
3727 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3728 }
3729
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003730 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003731 switch (msg.what) {
3732 case ALARM_EVENT: {
3733 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3734 synchronized (mLock) {
3735 final long nowRTC = System.currentTimeMillis();
3736 final long nowELAPSED = SystemClock.elapsedRealtime();
3737 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3738 updateNextAlarmClockLocked();
3739 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003740
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 // now trigger the alarms without the lock held
3742 for (int i=0; i<triggerList.size(); i++) {
3743 Alarm alarm = triggerList.get(i);
3744 try {
3745 alarm.operation.send();
3746 } catch (PendingIntent.CanceledException e) {
3747 if (alarm.repeatInterval > 0) {
3748 // This IntentSender is no longer valid, but this
3749 // is a repeating alarm, so toss the hoser.
3750 removeImpl(alarm.operation);
3751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003752 }
3753 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003754 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003755 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003756
3757 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3758 sendNextAlarmClockChanged();
3759 break;
3760
3761 case LISTENER_TIMEOUT:
3762 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3763 break;
3764
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003765 case REPORT_ALARMS_ACTIVE:
3766 if (mLocalDeviceIdleController != null) {
3767 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3768 }
3769 break;
3770
Suprabh Shukla75edab12018-01-29 14:09:06 -08003771 case APP_STANDBY_PAROLE_CHANGED:
3772 synchronized (mLock) {
3773 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003774 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3775 rescheduleKernelAlarmsLocked();
3776 updateNextAlarmClockLocked();
3777 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003778 }
3779 break;
3780
3781 case APP_STANDBY_BUCKET_CHANGED:
3782 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003783 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3784 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3785 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3786 rescheduleKernelAlarmsLocked();
3787 updateNextAlarmClockLocked();
3788 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003789 }
3790 break;
3791
Makoto Onuki4d298b52018-02-05 10:54:58 -08003792 case REMOVE_FOR_STOPPED:
3793 synchronized (mLock) {
3794 removeForStoppedLocked(msg.arg1);
3795 }
3796 break;
3797
Christopher Tate14a7bb02015-10-01 10:24:31 -07003798 default:
3799 // nope, just ignore it
3800 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 }
3802 }
3803 }
Kweku Adams61e03292017-10-19 14:27:12 -07003804
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003805 class ClockReceiver extends BroadcastReceiver {
3806 public ClockReceiver() {
3807 IntentFilter filter = new IntentFilter();
3808 filter.addAction(Intent.ACTION_TIME_TICK);
3809 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003810 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003811 }
Kweku Adams61e03292017-10-19 14:27:12 -07003812
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003813 @Override
3814 public void onReceive(Context context, Intent intent) {
3815 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003816 if (DEBUG_BATCH) {
3817 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3818 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003819 synchronized (mLock) {
3820 mLastTickReceived = System.currentTimeMillis();
3821 }
Christopher Tate385e4982013-07-23 18:22:29 -07003822 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003823 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3824 // Since the kernel does not keep track of DST, we need to
3825 // reset the TZ information at the beginning of each day
3826 // based off of the current Zone gmt offset + userspace tracked
3827 // daylight savings information.
3828 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003829 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003830 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003831 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003832 }
3833 }
Kweku Adams61e03292017-10-19 14:27:12 -07003834
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003835 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003836 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003837 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003838
3839 // Schedule this event for the amount of time that it would take to get to
3840 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003841 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003842
David Christieebe51fc2013-07-26 13:23:29 -07003843 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003844 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003845 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3846 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003847
3848 // Finally, remember when we set the tick alarm
3849 synchronized (mLock) {
3850 mLastTickSet = currentTime;
3851 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003852 }
Christopher Tate385e4982013-07-23 18:22:29 -07003853
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003854 public void scheduleDateChangedEvent() {
3855 Calendar calendar = Calendar.getInstance();
3856 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003857 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003858 calendar.set(Calendar.MINUTE, 0);
3859 calendar.set(Calendar.SECOND, 0);
3860 calendar.set(Calendar.MILLISECOND, 0);
3861 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003862
3863 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003864 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3865 AlarmManager.FLAG_STANDALONE, workSource, null,
3866 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003867 }
3868 }
Kweku Adams61e03292017-10-19 14:27:12 -07003869
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003870 class InteractiveStateReceiver extends BroadcastReceiver {
3871 public InteractiveStateReceiver() {
3872 IntentFilter filter = new IntentFilter();
3873 filter.addAction(Intent.ACTION_SCREEN_OFF);
3874 filter.addAction(Intent.ACTION_SCREEN_ON);
3875 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3876 getContext().registerReceiver(this, filter);
3877 }
3878
3879 @Override
3880 public void onReceive(Context context, Intent intent) {
3881 synchronized (mLock) {
3882 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3883 }
3884 }
3885 }
3886
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 class UninstallReceiver extends BroadcastReceiver {
3888 public UninstallReceiver() {
3889 IntentFilter filter = new IntentFilter();
3890 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3891 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003892 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003893 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003894 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003895 // Register for events related to sdcard installation.
3896 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003897 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003898 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003899 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003900 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003901 }
Kweku Adams61e03292017-10-19 14:27:12 -07003902
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003903 @Override
3904 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003905 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003906 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003907 String action = intent.getAction();
3908 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003909 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3910 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3911 for (String packageName : pkgList) {
3912 if (lookForPackageLocked(packageName)) {
3913 setResultCode(Activity.RESULT_OK);
3914 return;
3915 }
3916 }
3917 return;
3918 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003919 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003920 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3921 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3922 if (userHandle >= 0) {
3923 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003924 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3925 final Pair<String, Integer> packageUser =
3926 mLastAlarmDeliveredForPackage.keyAt(i);
3927 if (packageUser.second == userHandle) {
3928 mLastAlarmDeliveredForPackage.removeAt(i);
3929 }
3930 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003931 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003932 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003933 if (uid >= 0) {
3934 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003935 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003936 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003937 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003938 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3939 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3940 // This package is being updated; don't kill its alarms.
3941 return;
3942 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003943 Uri data = intent.getData();
3944 if (data != null) {
3945 String pkg = data.getSchemeSpecificPart();
3946 if (pkg != null) {
3947 pkgList = new String[]{pkg};
3948 }
3949 }
3950 }
3951 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003952 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3953 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3954 if (ArrayUtils.contains(pkgList, packageUser.first)
3955 && packageUser.second == UserHandle.getUserId(uid)) {
3956 mLastAlarmDeliveredForPackage.removeAt(i);
3957 }
3958 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003959 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003960 if (uid >= 0) {
3961 // package-removed case
3962 removeLocked(uid);
3963 } else {
3964 // external-applications-unavailable etc case
3965 removeLocked(pkg);
3966 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003967 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003968 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3969 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3970 if (uidStats.remove(pkg) != null) {
3971 if (uidStats.size() <= 0) {
3972 mBroadcastStats.removeAt(i);
3973 }
3974 }
3975 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003976 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003977 }
3978 }
3979 }
3980 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003981
3982 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003983 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003984 }
3985
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003986 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003987 if (disabled) {
3988 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003989 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003990 }
3991
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003992 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003993 }
3994
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003995 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003996 if (disabled) {
3997 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003998 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003999 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004000
4001 @Override public void onUidCachedChanged(int uid, boolean cached) {
4002 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004003 };
4004
Suprabh Shukla75edab12018-01-29 14:09:06 -08004005 /**
4006 * Tracking of app assignments to standby buckets
4007 */
4008 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4009 @Override
4010 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004011 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004012 if (DEBUG_STANDBY) {
4013 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4014 bucket);
4015 }
4016 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004017 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4018 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004019 }
4020
4021 @Override
4022 public void onParoleStateChanged(boolean isParoleOn) {
4023 if (DEBUG_STANDBY) {
4024 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4025 }
4026 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4027 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4028 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4029 Boolean.valueOf(isParoleOn)).sendToTarget();
4030 }
4031 };
4032
Makoto Onuki2206af32017-11-21 16:25:35 -08004033 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004034 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004035 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004036 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004037 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004038 }
4039 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004040
4041 @Override
4042 public void unblockAlarmsForUid(int uid) {
4043 synchronized (mLock) {
4044 sendPendingBackgroundAlarmsLocked(uid, null);
4045 }
4046 }
4047
4048 @Override
4049 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4050 synchronized (mLock) {
4051 sendPendingBackgroundAlarmsLocked(uid, packageName);
4052 }
4053 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004054
4055 @Override
4056 public void onUidForeground(int uid, boolean foreground) {
4057 synchronized (mLock) {
4058 if (foreground) {
4059 mUseAllowWhileIdleShortTime.put(uid, true);
4060
4061 // Note we don't have to drain the pending while-idle alarms here, because
4062 // this event should coincide with unblockAlarmsForUid().
4063 }
4064 }
4065 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004066 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004068 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004069 String pkg = pi.getCreatorPackage();
4070 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004071 return getStatsLocked(uid, pkg);
4072 }
4073
4074 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004075 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4076 if (uidStats == null) {
4077 uidStats = new ArrayMap<String, BroadcastStats>();
4078 mBroadcastStats.put(uid, uidStats);
4079 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004080 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004081 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004082 bs = new BroadcastStats(uid, pkgName);
4083 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004084 }
4085 return bs;
4086 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004087
Christopher Tate21e9f192017-08-08 13:49:11 -07004088 /**
4089 * Canonical count of (operation.send() - onSendFinished()) and
4090 * listener send/complete/timeout invocations.
4091 * Guarded by the usual lock.
4092 */
4093 @GuardedBy("mLock")
4094 private int mSendCount = 0;
4095 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004096 private int mSendFinishCount = 0;
4097 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004098 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004099 @GuardedBy("mLock")
4100 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004101
Christopher Tate14a7bb02015-10-01 10:24:31 -07004102 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004103
Christopher Tate14a7bb02015-10-01 10:24:31 -07004104 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4105 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004106 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004107 return mInFlight.remove(i);
4108 }
4109 }
4110 mLog.w("No in-flight alarm for " + pi + " " + intent);
4111 return null;
4112 }
4113
4114 private InFlight removeLocked(IBinder listener) {
4115 for (int i = 0; i < mInFlight.size(); i++) {
4116 if (mInFlight.get(i).mListener == listener) {
4117 return mInFlight.remove(i);
4118 }
4119 }
4120 mLog.w("No in-flight alarm for listener " + listener);
4121 return null;
4122 }
4123
4124 private void updateStatsLocked(InFlight inflight) {
4125 final long nowELAPSED = SystemClock.elapsedRealtime();
4126 BroadcastStats bs = inflight.mBroadcastStats;
4127 bs.nesting--;
4128 if (bs.nesting <= 0) {
4129 bs.nesting = 0;
4130 bs.aggregateTime += nowELAPSED - bs.startTime;
4131 }
4132 FilterStats fs = inflight.mFilterStats;
4133 fs.nesting--;
4134 if (fs.nesting <= 0) {
4135 fs.nesting = 0;
4136 fs.aggregateTime += nowELAPSED - fs.startTime;
4137 }
4138 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004139 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4140 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004141 }
4142 }
4143
4144 private void updateTrackingLocked(InFlight inflight) {
4145 if (inflight != null) {
4146 updateStatsLocked(inflight);
4147 }
4148 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004149 if (DEBUG_WAKELOCK) {
4150 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4151 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004152 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004153 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004154 mWakeLock.release();
4155 if (mInFlight.size() > 0) {
4156 mLog.w("Finished all dispatches with " + mInFlight.size()
4157 + " remaining inflights");
4158 for (int i=0; i<mInFlight.size(); i++) {
4159 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4160 }
4161 mInFlight.clear();
4162 }
4163 } else {
4164 // the next of our alarms is now in flight. reattribute the wakelock.
4165 if (mInFlight.size() > 0) {
4166 InFlight inFlight = mInFlight.get(0);
4167 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4168 inFlight.mAlarmType, inFlight.mTag, -1, false);
4169 } else {
4170 // should never happen
4171 mLog.w("Alarm wakelock still held but sent queue empty");
4172 mWakeLock.setWorkSource(null);
4173 }
4174 }
4175 }
4176
4177 /**
4178 * Callback that arrives when a direct-call alarm reports that delivery has finished
4179 */
4180 @Override
4181 public void alarmComplete(IBinder who) {
4182 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004183 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004184 + " pid=" + Binder.getCallingPid());
4185 return;
4186 }
4187
4188 final long ident = Binder.clearCallingIdentity();
4189 try {
4190 synchronized (mLock) {
4191 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4192 InFlight inflight = removeLocked(who);
4193 if (inflight != null) {
4194 if (DEBUG_LISTENER_CALLBACK) {
4195 Slog.i(TAG, "alarmComplete() from " + who);
4196 }
4197 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004198 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004199 } else {
4200 // Delivery timed out, and the timeout handling already took care of
4201 // updating our tracking here, so we needn't do anything further.
4202 if (DEBUG_LISTENER_CALLBACK) {
4203 Slog.i(TAG, "Late alarmComplete() from " + who);
4204 }
4205 }
4206 }
4207 } finally {
4208 Binder.restoreCallingIdentity(ident);
4209 }
4210 }
4211
4212 /**
4213 * Callback that arrives when a PendingIntent alarm has finished delivery
4214 */
4215 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004216 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4217 String resultData, Bundle resultExtras) {
4218 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004219 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004220 updateTrackingLocked(removeLocked(pi, intent));
4221 }
4222 }
4223
4224 /**
4225 * Timeout of a direct-call alarm delivery
4226 */
4227 public void alarmTimedOut(IBinder who) {
4228 synchronized (mLock) {
4229 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004230 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004231 // TODO: implement ANR policy for the target
4232 if (DEBUG_LISTENER_CALLBACK) {
4233 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004234 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004235 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004236 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004237 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004238 if (DEBUG_LISTENER_CALLBACK) {
4239 Slog.i(TAG, "Spurious timeout of listener " + who);
4240 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004241 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004242 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004243 }
4244 }
4245
4246 /**
4247 * Deliver an alarm and set up the post-delivery handling appropriately
4248 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004249 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004250 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4251 if (alarm.operation != null) {
4252 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004253 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004254
4255 if (alarm.priorityClass.priority == PRIO_TICK) {
4256 mLastTickIssued = nowELAPSED;
4257 }
4258
Christopher Tate14a7bb02015-10-01 10:24:31 -07004259 try {
4260 alarm.operation.send(getContext(), 0,
4261 mBackgroundIntent.putExtra(
4262 Intent.EXTRA_ALARM_COUNT, alarm.count),
4263 mDeliveryTracker, mHandler, null,
4264 allowWhileIdle ? mIdleOptions : null);
4265 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004266 if (alarm.operation == mTimeTickSender) {
4267 Slog.wtf(TAG, "mTimeTickSender canceled");
4268 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004269 if (alarm.repeatInterval > 0) {
4270 // This IntentSender is no longer valid, but this
4271 // is a repeating alarm, so toss it
4272 removeImpl(alarm.operation);
4273 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004274 // No actual delivery was possible, so the delivery tracker's
4275 // 'finished' callback won't be invoked. We also don't need
4276 // to do any wakelock or stats tracking, so we have nothing
4277 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004278 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004279 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004280 }
4281 } else {
4282 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004283 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004284 try {
4285 if (DEBUG_LISTENER_CALLBACK) {
4286 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4287 + " listener=" + alarm.listener.asBinder());
4288 }
4289 alarm.listener.doAlarm(this);
4290 mHandler.sendMessageDelayed(
4291 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4292 alarm.listener.asBinder()),
4293 mConstants.LISTENER_TIMEOUT);
4294 } catch (Exception e) {
4295 if (DEBUG_LISTENER_CALLBACK) {
4296 Slog.i(TAG, "Alarm undeliverable to listener "
4297 + alarm.listener.asBinder(), e);
4298 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004299 // As in the PendingIntent.CanceledException case, delivery of the
4300 // alarm was not possible, so we have no wakelock or timeout or
4301 // stats management to do. It threw before we posted the delayed
4302 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004303 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004304 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004305 }
4306 }
4307
4308 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004309 if (DEBUG_WAKELOCK) {
4310 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4311 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004312 if (mBroadcastRefCount == 0) {
4313 setWakelockWorkSource(alarm.operation, alarm.workSource,
4314 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4315 true);
4316 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004317 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004318 }
4319 final InFlight inflight = new InFlight(AlarmManagerService.this,
4320 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4321 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4322 mInFlight.add(inflight);
4323 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004324 if (allowWhileIdle) {
4325 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004326 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004327 if ((mAppStateTracker == null)
4328 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004329 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4330 } else {
4331 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4332 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004333 if (RECORD_DEVICE_IDLE_ALARMS) {
4334 IdleDispatchEntry ent = new IdleDispatchEntry();
4335 ent.uid = alarm.uid;
4336 ent.pkg = alarm.packageName;
4337 ent.tag = alarm.statsTag;
4338 ent.op = "DELIVER";
4339 ent.elapsedRealtime = nowELAPSED;
4340 mAllowWhileIdleDispatches.add(ent);
4341 }
4342 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004343 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004344 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4345 UserHandle.getUserId(alarm.creatorUid));
4346 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4347 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004348
4349 final BroadcastStats bs = inflight.mBroadcastStats;
4350 bs.count++;
4351 if (bs.nesting == 0) {
4352 bs.nesting = 1;
4353 bs.startTime = nowELAPSED;
4354 } else {
4355 bs.nesting++;
4356 }
4357 final FilterStats fs = inflight.mFilterStats;
4358 fs.count++;
4359 if (fs.nesting == 0) {
4360 fs.nesting = 1;
4361 fs.startTime = nowELAPSED;
4362 } else {
4363 fs.nesting++;
4364 }
4365 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4366 || alarm.type == RTC_WAKEUP) {
4367 bs.numWakeup++;
4368 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004369 ActivityManager.noteWakeupAlarm(
4370 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4371 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004372 }
4373 }
4374 }
mswest463f4c99d2018-02-01 10:13:10 -08004375
4376 private class ShellCmd extends ShellCommand {
4377
4378 IAlarmManager getBinderService() {
4379 return IAlarmManager.Stub.asInterface(mService);
4380 }
4381
4382 @Override
4383 public int onCommand(String cmd) {
4384 if (cmd == null) {
4385 return handleDefaultCommands(cmd);
4386 }
4387
4388 final PrintWriter pw = getOutPrintWriter();
4389 try {
4390 switch (cmd) {
4391 case "set-time":
4392 final long millis = Long.parseLong(getNextArgRequired());
4393 return (getBinderService().setTime(millis)) ? 0 : -1;
4394 case "set-timezone":
4395 final String tz = getNextArgRequired();
4396 getBinderService().setTimeZone(tz);
4397 return 0;
4398 default:
4399 return handleDefaultCommands(cmd);
4400 }
4401 } catch (Exception e) {
4402 pw.println(e);
4403 }
4404 return -1;
4405 }
4406
4407 @Override
4408 public void onHelp() {
4409 PrintWriter pw = getOutPrintWriter();
4410 pw.println("Alarm manager service (alarm) commands:");
4411 pw.println(" help");
4412 pw.println(" Print this help text.");
4413 pw.println(" set-time TIME");
4414 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4415 pw.println(" since the Epoch.");
4416 pw.println(" set-timezone TZ");
4417 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4418 }
4419 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004420}