blob: d066056145da558851692a710e26218d41e7b293 [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;
91import com.android.server.AppStateTracker.Listener;
92
Christopher Tate4cb338d2013-07-26 13:11:31 -070093import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import java.io.FileDescriptor;
95import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070096import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -070097import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080099import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.Calendar;
101import java.util.Collections;
102import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500103import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700104import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700105import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200106import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700107import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400109import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800110import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Makoto Onuki2206af32017-11-21 16:25:35 -0800112/**
113 * Alarm manager implementaion.
114 *
115 * Unit test:
116 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
117 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700119 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
120 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800121 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700122 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final int TIME_CHANGED_MASK = 1 << 16;
124 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800125
Christopher Tatee0a22b32013-07-11 14:43:13 -0700126 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800128
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800130 static final boolean localLOGV = false;
131 static final boolean DEBUG_BATCH = localLOGV || false;
132 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200133 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700134 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800135 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700136 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800137 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700138 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700139 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800140 static final int ALARM_EVENT = 1;
141 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200142
Christopher Tate14a7bb02015-10-01 10:24:31 -0700143 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800145 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700146
Adam Lesinski182f73f2013-12-05 16:48:06 -0800147 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700148
Christopher Tate24cd46f2016-02-02 14:28:01 -0800149 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
150 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700151 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
152 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200153
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800155
Christopher Tate14a7bb02015-10-01 10:24:31 -0700156 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800157 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800158 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700159
Adam Lesinski182f73f2013-12-05 16:48:06 -0800160 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800161
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700162 // List of alarms per uid deferred due to user applied background restrictions on the source app
163 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800164 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800165 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700166 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700167 private long mLastWakeupSet;
168 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800169 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800170 private long mLastTickSet;
171 private long mLastTickIssued; // elapsed
172 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800173 private long mLastTickAdded;
174 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800175 int mBroadcastRefCount = 0;
176 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700177 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700178 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
179 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800180 final AlarmHandler mHandler = new AlarmHandler();
181 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700182 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700184 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800185 PendingIntent mTimeTickSender;
186 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700187 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700188 boolean mInteractive = true;
189 long mNonInteractiveStartTime;
190 long mNonInteractiveTime;
191 long mLastAlarmDeliveryTime;
192 long mStartCurrentDelayTime;
193 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700194 long mLastTimeChangeClockTime;
195 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700196 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800197
Christopher Tatebb9cce52017-04-18 14:19:43 -0700198 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
199
200 /**
201 * This permission must be defined by the canonical System UI package,
202 * with protection level "signature".
203 */
204 private static final String SYSTEM_UI_SELF_PERMISSION =
205 "android.permission.systemui.IDENTITY";
206
207 /**
208 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
209 */
210 int mSystemUiUid;
211
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700212 /**
213 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700214 * used to determine the earliest we can dispatch the next such alarm. Times are in the
215 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700216 */
217 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
218
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800219 /**
220 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
221 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
222 */
223 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
224
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700225 final static class IdleDispatchEntry {
226 int uid;
227 String pkg;
228 String tag;
229 String op;
230 long elapsedRealtime;
231 long argRealtime;
232 }
233 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
234
Suprabh Shukla75edab12018-01-29 14:09:06 -0800235 interface Stats {
236 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800237 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800238 }
239
240 private final StatLogger mStatLogger = new StatLogger(new String[] {
241 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800242 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800243 });
244
Dianne Hackborna750a632015-06-16 17:18:23 -0700245 /**
246 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
247 */
248 Bundle mIdleOptions;
249
Jose Lima235510e2014-08-13 12:50:01 -0700250 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
251 new SparseArray<>();
252 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
253 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200254 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
255 new SparseBooleanArray();
256 private boolean mNextAlarmClockMayChange;
257
258 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700259 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
260 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200261
Makoto Onukie4918212018-02-06 11:30:15 -0800262 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800263 private boolean mAppStandbyParole;
264 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800265
Dianne Hackborna750a632015-06-16 17:18:23 -0700266 /**
267 * All times are in milliseconds. These constants are kept synchronized with the system
268 * global Settings. Any access to this class or its fields should be done while
269 * holding the AlarmManagerService.mLock lock.
270 */
271 private final class Constants extends ContentObserver {
272 // Key names stored in the settings value.
273 private static final String KEY_MIN_FUTURITY = "min_futurity";
274 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800275 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700276 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
277 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
278 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
279 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700280 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700281
Suprabh Shukla75edab12018-01-29 14:09:06 -0800282 // Keys for specifying throttling delay based on app standby bucketing
283 private final String[] KEYS_APP_STANDBY_DELAY = {
284 "standby_active_delay",
285 "standby_working_delay",
286 "standby_frequent_delay",
287 "standby_rare_delay",
288 "standby_never_delay",
289 };
290
Dianne Hackborna750a632015-06-16 17:18:23 -0700291 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
292 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800293 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700294 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700295 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700296 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700297 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800298 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
299 0, // Active
300 6 * 60_000, // Working
301 30 * 60_000, // Frequent
302 2 * 60 * 60_000, // Rare
303 10 * 24 * 60 * 60_000 // Never
304 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700305
Dianne Hackborna750a632015-06-16 17:18:23 -0700306 // Minimum futurity of a new alarm
307 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
308
309 // Minimum alarm recurrence interval
310 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
311
Christopher Tate22e919d2018-02-16 16:16:50 -0800312 // Maximum alarm recurrence interval
313 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
314
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
316 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
317
318 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
319 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
320
321 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
322 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
323 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
324
Christopher Tate14a7bb02015-10-01 10:24:31 -0700325 // Direct alarm listener callback timeout
326 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
327
Suprabh Shukla75edab12018-01-29 14:09:06 -0800328 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
329
Dianne Hackborna750a632015-06-16 17:18:23 -0700330 private ContentResolver mResolver;
331 private final KeyValueListParser mParser = new KeyValueListParser(',');
332 private long mLastAllowWhileIdleWhitelistDuration = -1;
333
334 public Constants(Handler handler) {
335 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700336 updateAllowWhileIdleWhitelistDurationLocked();
337 }
338
339 public void start(ContentResolver resolver) {
340 mResolver = resolver;
341 mResolver.registerContentObserver(Settings.Global.getUriFor(
342 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
343 updateConstants();
344 }
345
Dianne Hackborna750a632015-06-16 17:18:23 -0700346 public void updateAllowWhileIdleWhitelistDurationLocked() {
347 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
348 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
349 BroadcastOptions opts = BroadcastOptions.makeBasic();
350 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
351 mIdleOptions = opts.toBundle();
352 }
353 }
354
355 @Override
356 public void onChange(boolean selfChange, Uri uri) {
357 updateConstants();
358 }
359
360 private void updateConstants() {
361 synchronized (mLock) {
362 try {
363 mParser.setString(Settings.Global.getString(mResolver,
364 Settings.Global.ALARM_MANAGER_CONSTANTS));
365 } catch (IllegalArgumentException e) {
366 // Failed to parse the settings string, log this and move on
367 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800368 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700369 }
370
371 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
372 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800373 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700374 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
375 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
376 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
377 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
378 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
379 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
380 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700381 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
382 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800383 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
384 DEFAULT_APP_STANDBY_DELAYS[0]);
385 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
386 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
387 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
388 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700389 updateAllowWhileIdleWhitelistDurationLocked();
390 }
391 }
392
393 void dump(PrintWriter pw) {
394 pw.println(" Settings:");
395
396 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
397 TimeUtils.formatDuration(MIN_FUTURITY, pw);
398 pw.println();
399
400 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
401 TimeUtils.formatDuration(MIN_INTERVAL, pw);
402 pw.println();
403
Christopher Tate22e919d2018-02-16 16:16:50 -0800404 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
405 TimeUtils.formatDuration(MAX_INTERVAL, pw);
406 pw.println();
407
Christopher Tate14a7bb02015-10-01 10:24:31 -0700408 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
409 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
410 pw.println();
411
Dianne Hackborna750a632015-06-16 17:18:23 -0700412 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
413 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
414 pw.println();
415
416 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
417 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
418 pw.println();
419
420 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
421 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
422 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800423
424 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
425 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
426 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
427 pw.println();
428 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700429 }
Kweku Adams61e03292017-10-19 14:27:12 -0700430
431 void dumpProto(ProtoOutputStream proto, long fieldId) {
432 final long token = proto.start(fieldId);
433
434 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
435 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800436 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700437 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
438 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
439 ALLOW_WHILE_IDLE_SHORT_TIME);
440 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
441 ALLOW_WHILE_IDLE_LONG_TIME);
442 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
443 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
444
445 proto.end(token);
446 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700447 }
448
449 final Constants mConstants;
450
Christopher Tate1590f1e2014-10-02 17:27:57 -0700451 // Alarm delivery ordering bookkeeping
452 static final int PRIO_TICK = 0;
453 static final int PRIO_WAKEUP = 1;
454 static final int PRIO_NORMAL = 2;
455
Dianne Hackborna750a632015-06-16 17:18:23 -0700456 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700457 int seq;
458 int priority;
459
460 PriorityClass() {
461 seq = mCurrentSeq - 1;
462 priority = PRIO_NORMAL;
463 }
464 }
465
Dianne Hackborna750a632015-06-16 17:18:23 -0700466 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700467 int mCurrentSeq = 0;
468
Dianne Hackborna750a632015-06-16 17:18:23 -0700469 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700470 public long when;
471 public int uid;
472 public String action;
473
474 public WakeupEvent(long theTime, int theUid, String theAction) {
475 when = theTime;
476 uid = theUid;
477 action = theAction;
478 }
479 }
480
Adam Lesinski182f73f2013-12-05 16:48:06 -0800481 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
482 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700483
Adrian Roosc42a1e12014-07-07 23:35:53 +0200484 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485 long start; // These endpoints are always in ELAPSED
486 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700487 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700488
489 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
490
491 Batch() {
492 start = 0;
493 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700494 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 }
496
497 Batch(Alarm seed) {
498 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800499 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700500 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700501 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800502 if (seed.operation == mTimeTickSender) {
503 mLastTickAdded = System.currentTimeMillis();
504 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700505 }
506
507 int size() {
508 return alarms.size();
509 }
510
511 Alarm get(int index) {
512 return alarms.get(index);
513 }
514
515 boolean canHold(long whenElapsed, long maxWhen) {
516 return (end >= whenElapsed) && (start <= maxWhen);
517 }
518
519 boolean add(Alarm alarm) {
520 boolean newStart = false;
521 // narrows the batch if necessary; presumes that canHold(alarm) is true
522 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
523 if (index < 0) {
524 index = 0 - index - 1;
525 }
526 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800527 if (alarm.operation == mTimeTickSender) {
528 mLastTickAdded = System.currentTimeMillis();
529 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700530 if (DEBUG_BATCH) {
531 Slog.v(TAG, "Adding " + alarm + " to " + this);
532 }
533 if (alarm.whenElapsed > start) {
534 start = alarm.whenElapsed;
535 newStart = true;
536 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700537 if (alarm.maxWhenElapsed < end) {
538 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700539 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700540 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700541
542 if (DEBUG_BATCH) {
543 Slog.v(TAG, " => now " + this);
544 }
545 return newStart;
546 }
547
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800548 boolean remove(Alarm alarm) {
549 return remove(a -> (a == alarm));
550 }
551
Christopher Tate1d99c392017-12-07 16:54:04 -0800552 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700553 boolean didRemove = false;
554 long newStart = 0; // recalculate endpoints as we go
555 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700556 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700557 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700558 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800559 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700560 alarms.remove(i);
561 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200562 if (alarm.alarmClock != null) {
563 mNextAlarmClockMayChange = true;
564 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800565 if (alarm.operation == mTimeTickSender) {
566 mLastTickRemoved = System.currentTimeMillis();
567 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 } else {
569 if (alarm.whenElapsed > newStart) {
570 newStart = alarm.whenElapsed;
571 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700572 if (alarm.maxWhenElapsed < newEnd) {
573 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700574 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700575 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 i++;
577 }
578 }
579 if (didRemove) {
580 // commit the new batch bounds
581 start = newStart;
582 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700583 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700584 }
585 return didRemove;
586 }
587
Christopher Tatee0a22b32013-07-11 14:43:13 -0700588 boolean hasPackage(final String packageName) {
589 final int N = alarms.size();
590 for (int i = 0; i < N; i++) {
591 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700592 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700593 return true;
594 }
595 }
596 return false;
597 }
598
599 boolean hasWakeups() {
600 final int N = alarms.size();
601 for (int i = 0; i < N; i++) {
602 Alarm a = alarms.get(i);
603 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
604 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
605 return true;
606 }
607 }
608 return false;
609 }
610
611 @Override
612 public String toString() {
613 StringBuilder b = new StringBuilder(40);
614 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
615 b.append(" num="); b.append(size());
616 b.append(" start="); b.append(start);
617 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700618 if (flags != 0) {
619 b.append(" flgs=0x");
620 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700621 }
622 b.append('}');
623 return b.toString();
624 }
Kweku Adams61e03292017-10-19 14:27:12 -0700625
626 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
627 long nowRTC) {
628 final long token = proto.start(fieldId);
629
630 proto.write(BatchProto.START_REALTIME, start);
631 proto.write(BatchProto.END_REALTIME, end);
632 proto.write(BatchProto.FLAGS, flags);
633 for (Alarm a : alarms) {
634 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
635 }
636
637 proto.end(token);
638 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700639 }
640
641 static class BatchTimeOrder implements Comparator<Batch> {
642 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800643 long when1 = b1.start;
644 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800645 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700646 return 1;
647 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800648 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700649 return -1;
650 }
651 return 0;
652 }
653 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800654
655 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
656 @Override
657 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700658 // priority class trumps everything. TICK < WAKEUP < NORMAL
659 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
660 return -1;
661 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
662 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800663 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700664
665 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800666 if (lhs.whenElapsed < rhs.whenElapsed) {
667 return -1;
668 } else if (lhs.whenElapsed > rhs.whenElapsed) {
669 return 1;
670 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700671
672 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800673 return 0;
674 }
675 };
676
Christopher Tate1590f1e2014-10-02 17:27:57 -0700677 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
678 final int N = alarms.size();
679 for (int i = 0; i < N; i++) {
680 Alarm a = alarms.get(i);
681
682 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700683 if (a.operation != null
684 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700685 alarmPrio = PRIO_TICK;
686 } else if (a.wakeup) {
687 alarmPrio = PRIO_WAKEUP;
688 } else {
689 alarmPrio = PRIO_NORMAL;
690 }
691
692 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800693 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700694 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700695 if (packagePrio == null) {
696 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700697 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700698 }
699 a.priorityClass = packagePrio;
700
701 if (packagePrio.seq != mCurrentSeq) {
702 // first alarm we've seen in the current delivery generation from this package
703 packagePrio.priority = alarmPrio;
704 packagePrio.seq = mCurrentSeq;
705 } else {
706 // Multiple alarms from this package being delivered in this generation;
707 // bump the package's delivery class if it's warranted.
708 // TICK < WAKEUP < NORMAL
709 if (alarmPrio < packagePrio.priority) {
710 packagePrio.priority = alarmPrio;
711 }
712 }
713 }
714 }
715
Christopher Tatee0a22b32013-07-11 14:43:13 -0700716 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800717 static final long MIN_FUZZABLE_INTERVAL = 10000;
718 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700719 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
720
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700721 // 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 -0700722 // to run during this time are placed in mPendingWhileIdleAlarms
723 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700724 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700725 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726
Jeff Brownb880d882014-02-10 19:47:07 -0800727 public AlarmManagerService(Context context) {
728 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700729 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800730
Christopher Tate1d99c392017-12-07 16:54:04 -0800731 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800732 }
733
Christopher Tatee0a22b32013-07-11 14:43:13 -0700734 static long convertToElapsed(long when, int type) {
735 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
736 if (isRtc) {
737 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
738 }
739 return when;
740 }
741
742 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
743 // calculate the end of our nominal delivery window for the alarm.
744 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
745 // Current heuristic: batchable window is 75% of either the recurrence interval
746 // [for a periodic alarm] or of the time from now to the desired delivery time,
747 // with a minimum delay/interval of 10 seconds, under which we will simply not
748 // defer the alarm.
749 long futurity = (interval == 0)
750 ? (triggerAtTime - now)
751 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700752 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700753 futurity = 0;
754 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800755 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700756 }
757
758 // returns true if the batch was added at the head
759 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
760 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
761 if (index < 0) {
762 index = 0 - index - 1;
763 }
764 list.add(index, newBatch);
765 return (index == 0);
766 }
767
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800768 private void insertAndBatchAlarmLocked(Alarm alarm) {
769 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
770 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
771
772 if (whichBatch < 0) {
773 addBatchLocked(mAlarmBatches, new Batch(alarm));
774 } else {
775 final Batch batch = mAlarmBatches.get(whichBatch);
776 if (batch.add(alarm)) {
777 // The start time of this batch advanced, so batch ordering may
778 // have just been broken. Move it to where it now belongs.
779 mAlarmBatches.remove(whichBatch);
780 addBatchLocked(mAlarmBatches, batch);
781 }
782 }
783 }
784
Christopher Tate385e4982013-07-23 18:22:29 -0700785 // Return the index of the matching batch, or -1 if none found.
786 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700787 final int N = mAlarmBatches.size();
788 for (int i = 0; i < N; i++) {
789 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700790 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700791 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700792 }
793 }
Christopher Tate385e4982013-07-23 18:22:29 -0700794 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700795 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800796 /** @return total count of the alarms in a set of alarm batches. */
797 static int getAlarmCount(ArrayList<Batch> batches) {
798 int ret = 0;
799
800 final int size = batches.size();
801 for (int i = 0; i < size; i++) {
802 ret += batches.get(i).size();
803 }
804 return ret;
805 }
806
807 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
808 if (alarms.size() == 0) {
809 return false;
810 }
811 final int batchSize = alarms.size();
812 for (int j = 0; j < batchSize; j++) {
813 if (alarms.get(j).operation == mTimeTickSender) {
814 return true;
815 }
816 }
817 return false;
818 }
819
820 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
821 final int numBatches = batches.size();
822 for (int i = 0; i < numBatches; i++) {
823 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
824 return true;
825 }
826 }
827 return false;
828 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700829
830 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
831 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700832 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700833 rebatchAllAlarmsLocked(true);
834 }
835 }
836
837 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800838 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800839 final int oldCount =
840 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
841 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
842 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
843
Christopher Tate4cb338d2013-07-26 13:11:31 -0700844 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
845 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700846 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700847 final long nowElapsed = SystemClock.elapsedRealtime();
848 final int oldBatches = oldSet.size();
849 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
850 Batch batch = oldSet.get(batchNum);
851 final int N = batch.size();
852 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700853 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700854 }
855 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700856 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
857 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
858 + " to " + mPendingIdleUntil);
859 if (mPendingIdleUntil == null) {
860 // Somehow we lost this... we need to restore all of the pending alarms.
861 restorePendingWhileIdleAlarmsLocked();
862 }
863 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800864 final int newCount =
865 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
866 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
867 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
868
869 if (oldCount != newCount) {
870 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
871 }
872 if (oldHasTick != newHasTick) {
873 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
874 }
875
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700876 rescheduleKernelAlarmsLocked();
877 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800878 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700879 }
880
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800881 /**
882 * Re-orders the alarm batches based on newly evaluated send times based on the current
883 * app-standby buckets
884 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
885 * null indicates all
886 * @return True if there was any reordering done to the current list.
887 */
888 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
889 final long start = mStatLogger.getTime();
890 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
891
892 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
893 final Batch batch = mAlarmBatches.get(batchIndex);
894 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
895 final Alarm alarm = batch.get(alarmIndex);
896 final Pair<String, Integer> packageUser =
897 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
898 if (targetPackages != null && !targetPackages.contains(packageUser)) {
899 continue;
900 }
901 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
902 batch.remove(alarm);
903 rescheduledAlarms.add(alarm);
904 }
905 }
906 if (batch.size() == 0) {
907 mAlarmBatches.remove(batchIndex);
908 }
909 }
910 for (int i = 0; i < rescheduledAlarms.size(); i++) {
911 final Alarm a = rescheduledAlarms.get(i);
912 insertAndBatchAlarmLocked(a);
913 }
914
915 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
916 return rescheduledAlarms.size() > 0;
917 }
918
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700919 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
920 a.when = a.origWhen;
921 long whenElapsed = convertToElapsed(a.when, a.type);
922 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700923 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700924 // Exact
925 maxElapsed = whenElapsed;
926 } else {
927 // Not exact. Preserve any explicit window, otherwise recalculate
928 // the window based on the alarm's new futurity. Note that this
929 // reflects a policy of preferring timely to deferred delivery.
930 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800931 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700932 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
933 }
934 a.whenElapsed = whenElapsed;
935 a.maxWhenElapsed = maxElapsed;
936 setImplLocked(a, true, doValidate);
937 }
938
Christopher Tate22e919d2018-02-16 16:16:50 -0800939 static long clampPositive(long val) {
940 return (val >= 0) ? val : Long.MAX_VALUE;
941 }
942
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700943 /**
944 * Sends alarms that were blocked due to user applied background restrictions - either because
945 * the user lifted those or the uid came to foreground.
946 *
947 * @param uid uid to filter on
948 * @param packageName package to filter on, or null for all packages in uid
949 */
950 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
951 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
952 if (alarmsForUid == null || alarmsForUid.size() == 0) {
953 return;
954 }
955 final ArrayList<Alarm> alarmsToDeliver;
956 if (packageName != null) {
957 if (DEBUG_BG_LIMIT) {
958 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
959 }
960 alarmsToDeliver = new ArrayList<>();
961 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
962 final Alarm a = alarmsForUid.get(i);
963 if (a.matches(packageName)) {
964 alarmsToDeliver.add(alarmsForUid.remove(i));
965 }
966 }
967 if (alarmsForUid.size() == 0) {
968 mPendingBackgroundAlarms.remove(uid);
969 }
970 } else {
971 if (DEBUG_BG_LIMIT) {
972 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
973 }
974 alarmsToDeliver = alarmsForUid;
975 mPendingBackgroundAlarms.remove(uid);
976 }
977 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
978 }
979
Makoto Onuki2206af32017-11-21 16:25:35 -0800980 /**
981 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
982 * restricted.
983 *
984 * This is only called when the global "force all apps-standby" flag changes or when the
985 * power save whitelist changes, so it's okay to be slow.
986 */
987 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700988 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800989
990 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
991 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
992
993 if (alarmsToDeliver.size() > 0) {
994 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
995 }
996 }
997
998 @VisibleForTesting
999 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1000 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1001 Predicate<Alarm> isBackgroundRestricted) {
1002
1003 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1004 final int uid = pendingAlarms.keyAt(uidIndex);
1005 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1006
1007 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1008 final Alarm alarm = alarmsForUid.get(alarmIndex);
1009
1010 if (isBackgroundRestricted.test(alarm)) {
1011 continue;
1012 }
1013
1014 unrestrictedAlarms.add(alarm);
1015 alarmsForUid.remove(alarmIndex);
1016 }
1017
1018 if (alarmsForUid.size() == 0) {
1019 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001020 }
1021 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001022 }
1023
1024 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1025 final int N = alarms.size();
1026 boolean hasWakeup = false;
1027 for (int i = 0; i < N; i++) {
1028 final Alarm alarm = alarms.get(i);
1029 if (alarm.wakeup) {
1030 hasWakeup = true;
1031 }
1032 alarm.count = 1;
1033 // Recurring alarms may have passed several alarm intervals while the
1034 // alarm was kept pending. Send the appropriate trigger count.
1035 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001036 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001037 // Also schedule its next recurrence
1038 final long delta = alarm.count * alarm.repeatInterval;
1039 final long nextElapsed = alarm.whenElapsed + delta;
1040 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1041 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1042 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1043 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1044 // Kernel alarms will be rescheduled as needed in setImplLocked
1045 }
1046 }
1047 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1048 // No need to wakeup for non wakeup alarms
1049 if (mPendingNonWakeupAlarms.size() == 0) {
1050 mStartCurrentDelayTime = nowELAPSED;
1051 mNextNonWakeupDeliveryTime = nowELAPSED
1052 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1053 }
1054 mPendingNonWakeupAlarms.addAll(alarms);
1055 mNumDelayedAlarms += alarms.size();
1056 } else {
1057 if (DEBUG_BG_LIMIT) {
1058 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1059 }
1060 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1061 if (mPendingNonWakeupAlarms.size() > 0) {
1062 alarms.addAll(mPendingNonWakeupAlarms);
1063 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1064 mTotalDelayTime += thisDelayTime;
1065 if (mMaxDelayTime < thisDelayTime) {
1066 mMaxDelayTime = thisDelayTime;
1067 }
1068 mPendingNonWakeupAlarms.clear();
1069 }
1070 calculateDeliveryPriorities(alarms);
1071 Collections.sort(alarms, mAlarmDispatchComparator);
1072 deliverAlarmsLocked(alarms, nowELAPSED);
1073 }
1074 }
1075
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001076 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001077 if (RECORD_DEVICE_IDLE_ALARMS) {
1078 IdleDispatchEntry ent = new IdleDispatchEntry();
1079 ent.uid = 0;
1080 ent.pkg = "FINISH IDLE";
1081 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1082 mAllowWhileIdleDispatches.add(ent);
1083 }
1084
Dianne Hackborn35d54032015-04-23 10:30:43 -07001085 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001086 if (mPendingWhileIdleAlarms.size() > 0) {
1087 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1088 mPendingWhileIdleAlarms = new ArrayList<>();
1089 final long nowElapsed = SystemClock.elapsedRealtime();
1090 for (int i=alarms.size() - 1; i >= 0; i--) {
1091 Alarm a = alarms.get(i);
1092 reAddAlarmLocked(a, nowElapsed, false);
1093 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001094 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001095
1096 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001097 rescheduleKernelAlarmsLocked();
1098 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001099
1100 // And send a TIME_TICK right now, since it is important to get the UI updated.
1101 try {
1102 mTimeTickSender.send();
1103 } catch (PendingIntent.CanceledException e) {
1104 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001105 }
1106
Christopher Tate14a7bb02015-10-01 10:24:31 -07001107 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001108 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001109 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001110 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001111 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001112 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001113 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001114 final BroadcastStats mBroadcastStats;
1115 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001116 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001117
Christopher Tate14a7bb02015-10-01 10:24:31 -07001118 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1119 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1120 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001121 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001122 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001123 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001124 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001125 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001126 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001127 mBroadcastStats = (pendingIntent != null)
1128 ? service.getStatsLocked(pendingIntent)
1129 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001130 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001131 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001132 fs = new FilterStats(mBroadcastStats, mTag);
1133 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001134 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001135 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001136 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001137 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001138 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001139
1140 @Override
1141 public String toString() {
1142 return "InFlight{"
1143 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001144 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001145 + ", workSource=" + mWorkSource
1146 + ", uid=" + mUid
1147 + ", tag=" + mTag
1148 + ", broadcastStats=" + mBroadcastStats
1149 + ", filterStats=" + mFilterStats
1150 + ", alarmType=" + mAlarmType
1151 + "}";
1152 }
Kweku Adams61e03292017-10-19 14:27:12 -07001153
1154 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1155 final long token = proto.start(fieldId);
1156
1157 proto.write(InFlightProto.UID, mUid);
1158 proto.write(InFlightProto.TAG, mTag);
1159 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1160 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1161 if (mPendingIntent != null) {
1162 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1163 }
1164 if (mBroadcastStats != null) {
1165 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1166 }
1167 if (mFilterStats != null) {
1168 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1169 }
1170 if (mWorkSource != null) {
1171 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1172 }
1173
1174 proto.end(token);
1175 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001177
Adam Lesinski182f73f2013-12-05 16:48:06 -08001178 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001179 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001180 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001181
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001182 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001184 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 int numWakeup;
1186 long startTime;
1187 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001188
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001189 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001190 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001191 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001192 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001193
1194 @Override
1195 public String toString() {
1196 return "FilterStats{"
1197 + "tag=" + mTag
1198 + ", lastTime=" + lastTime
1199 + ", aggregateTime=" + aggregateTime
1200 + ", count=" + count
1201 + ", numWakeup=" + numWakeup
1202 + ", startTime=" + startTime
1203 + ", nesting=" + nesting
1204 + "}";
1205 }
Kweku Adams61e03292017-10-19 14:27:12 -07001206
1207 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1208 final long token = proto.start(fieldId);
1209
1210 proto.write(FilterStatsProto.TAG, mTag);
1211 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1212 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1213 proto.write(FilterStatsProto.COUNT, count);
1214 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1215 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1216 proto.write(FilterStatsProto.NESTING, nesting);
1217
1218 proto.end(token);
1219 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001220 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001221
Adam Lesinski182f73f2013-12-05 16:48:06 -08001222 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001223 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001224 final String mPackageName;
1225
1226 long aggregateTime;
1227 int count;
1228 int numWakeup;
1229 long startTime;
1230 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001231 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001232
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001233 BroadcastStats(int uid, String packageName) {
1234 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001235 mPackageName = packageName;
1236 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001237
1238 @Override
1239 public String toString() {
1240 return "BroadcastStats{"
1241 + "uid=" + mUid
1242 + ", packageName=" + mPackageName
1243 + ", aggregateTime=" + aggregateTime
1244 + ", count=" + count
1245 + ", numWakeup=" + numWakeup
1246 + ", startTime=" + startTime
1247 + ", nesting=" + nesting
1248 + "}";
1249 }
Kweku Adams61e03292017-10-19 14:27:12 -07001250
1251 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1252 final long token = proto.start(fieldId);
1253
1254 proto.write(BroadcastStatsProto.UID, mUid);
1255 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1256 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1257 proto.write(BroadcastStatsProto.COUNT, count);
1258 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1259 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1260 proto.write(BroadcastStatsProto.NESTING, nesting);
1261
1262 proto.end(token);
1263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001265
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001266 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1267 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001268
1269 int mNumDelayedAlarms = 0;
1270 long mTotalDelayTime = 0;
1271 long mMaxDelayTime = 0;
1272
Adam Lesinski182f73f2013-12-05 16:48:06 -08001273 @Override
1274 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001275 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001276 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001277
1278 // We have to set current TimeZone info to kernel
1279 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001280 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001281
Christopher Tate247571462017-04-10 11:45:05 -07001282 // Also sure that we're booting with a halfway sensible current time
1283 if (mNativeData != 0) {
1284 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1285 if (System.currentTimeMillis() < systemBuildTime) {
1286 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1287 + ", advancing to build time " + systemBuildTime);
1288 setKernelTime(mNativeData, systemBuildTime);
1289 }
1290 }
1291
Christopher Tatebb9cce52017-04-18 14:19:43 -07001292 // Determine SysUI's uid
1293 final PackageManager packMan = getContext().getPackageManager();
1294 try {
1295 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1296 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1297 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1298 mSystemUiUid = sysUi.uid;
1299 } else {
1300 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1301 + " defined by non-privileged app " + sysUi.packageName
1302 + " - ignoring");
1303 }
1304 } catch (NameNotFoundException e) {
1305 }
1306
1307 if (mSystemUiUid <= 0) {
1308 Slog.wtf(TAG, "SysUI package not found!");
1309 }
1310
Adam Lesinski182f73f2013-12-05 16:48:06 -08001311 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001312 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001313
Adam Lesinski182f73f2013-12-05 16:48:06 -08001314 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001316 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001317 | Intent.FLAG_RECEIVER_FOREGROUND
1318 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001319 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001320 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001321 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1322 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001323 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001324 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001325
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001327 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 mClockReceiver.scheduleTimeTickEvent();
1329 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001330 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001331 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001332
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001333 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001334 AlarmThread waitThread = new AlarmThread();
1335 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001336 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001337 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001338 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001339
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001340 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001341 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001342 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1343 | ActivityManager.UID_OBSERVER_ACTIVE,
1344 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001345 } catch (RemoteException e) {
1346 // ignored; both services live in system_server
1347 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001348 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001349 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001350
1351 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001352 public void onBootPhase(int phase) {
1353 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1354 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001355 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001356 mLocalDeviceIdleController
1357 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001358 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1359 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001360
1361 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1362 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001363 }
1364 }
1365
1366 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 protected void finalize() throws Throwable {
1368 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001369 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 } finally {
1371 super.finalize();
1372 }
1373 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001374
mswest463f4c99d2018-02-01 10:13:10 -08001375 boolean setTimeImpl(long millis) {
1376 if (mNativeData == 0) {
1377 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1378 return false;
1379 }
1380
1381 synchronized (mLock) {
1382 return setKernelTime(mNativeData, millis) == 0;
1383 }
1384 }
1385
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 void setTimeZoneImpl(String tz) {
1387 if (TextUtils.isEmpty(tz)) {
1388 return;
David Christieebe51fc2013-07-26 13:23:29 -07001389 }
1390
Adam Lesinski182f73f2013-12-05 16:48:06 -08001391 TimeZone zone = TimeZone.getTimeZone(tz);
1392 // Prevent reentrant calls from stepping on each other when writing
1393 // the time zone property
1394 boolean timeZoneWasChanged = false;
1395 synchronized (this) {
1396 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1397 if (current == null || !current.equals(zone.getID())) {
1398 if (localLOGV) {
1399 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1400 }
1401 timeZoneWasChanged = true;
1402 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1403 }
1404
1405 // Update the kernel timezone information
1406 // Kernel tracks time offsets as 'minutes west of GMT'
1407 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001408 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001409 }
1410
1411 TimeZone.setDefault(null);
1412
1413 if (timeZoneWasChanged) {
1414 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001415 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001416 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001417 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001418 intent.putExtra("time-zone", zone.getID());
1419 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1420 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001422
Adam Lesinski182f73f2013-12-05 16:48:06 -08001423 void removeImpl(PendingIntent operation) {
1424 if (operation == null) {
1425 return;
1426 }
1427 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001428 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001429 }
1430 }
1431
1432 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001433 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1434 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1435 int callingUid, String callingPackage) {
1436 // must be *either* PendingIntent or AlarmReceiver, but not both
1437 if ((operation == null && directReceiver == null)
1438 || (operation != null && directReceiver != null)) {
1439 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1440 // NB: previous releases failed silently here, so we are continuing to do the same
1441 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 return;
1443 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001444
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001445 // Sanity check the window length. This will catch people mistakenly
1446 // trying to pass an end-of-window timestamp rather than a duration.
1447 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1448 Slog.w(TAG, "Window length " + windowLength
1449 + "ms suspiciously long; limiting to 1 hour");
1450 windowLength = AlarmManager.INTERVAL_HOUR;
1451 }
1452
Christopher Tate498c6cb2014-11-17 16:09:27 -08001453 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001454 // seconds when the API expects milliseconds, or apps trying shenanigans
1455 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001456 final long minInterval = mConstants.MIN_INTERVAL;
1457 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001458 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001459 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001460 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001461 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001462 } else if (interval > mConstants.MAX_INTERVAL) {
1463 Slog.w(TAG, "Suspiciously long interval " + interval
1464 + " millis; clamping");
1465 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001466 }
1467
Christopher Tatee0a22b32013-07-11 14:43:13 -07001468 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1469 throw new IllegalArgumentException("Invalid alarm type " + type);
1470 }
1471
Christopher Tate5f221e82013-07-30 17:13:15 -07001472 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001473 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001474 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001475 + " pid=" + what);
1476 triggerAtTime = 0;
1477 }
1478
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001479 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001480 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1481 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001482 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001483 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1484
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001485 final long maxElapsed;
1486 if (windowLength == AlarmManager.WINDOW_EXACT) {
1487 maxElapsed = triggerElapsed;
1488 } else if (windowLength < 0) {
1489 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001490 // Fix this window in place, so that as time approaches we don't collapse it.
1491 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001492 } else {
1493 maxElapsed = triggerElapsed + windowLength;
1494 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001495
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001497 if (DEBUG_BATCH) {
1498 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001499 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001500 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001501 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001503 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001504 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1505 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508
Christopher Tate3e04b472013-10-21 17:51:31 -07001509 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001510 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1511 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1512 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001513 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001514 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1515 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001516 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001517 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001518 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1519 + " -- package not allowed to start");
1520 return;
1521 }
1522 } catch (RemoteException e) {
1523 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001524 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001525 setImplLocked(a, false, doValidate);
1526 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001527
Suprabh Shukla75edab12018-01-29 14:09:06 -08001528 private long getMinDelayForBucketLocked(int bucket) {
1529 // Return the minimum time that should elapse before an app in the specified bucket
1530 // can receive alarms again
1531 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
1532 return mConstants.APP_STANDBY_MIN_DELAYS[4];
1533 }
1534 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) {
1535 return mConstants.APP_STANDBY_MIN_DELAYS[3];
1536 }
1537 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1538 return mConstants.APP_STANDBY_MIN_DELAYS[2];
1539 }
1540 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1541 return mConstants.APP_STANDBY_MIN_DELAYS[1];
1542 }
1543 else return mConstants.APP_STANDBY_MIN_DELAYS[0];
1544 }
1545
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001546 /**
1547 * Adjusts the alarm delivery time based on the current app standby bucket.
1548 * @param alarm The alarm to adjust
1549 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001550 */
1551 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001552 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001553 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001554 }
1555 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001556 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001557 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001558 alarm.whenElapsed = alarm.expectedWhenElapsed;
1559 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1560 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001561 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001562 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001563 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001564 final long oldWhenElapsed = alarm.whenElapsed;
1565 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1566
Suprabh Shukla75edab12018-01-29 14:09:06 -08001567 final String sourcePackage = alarm.sourcePackage;
1568 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1569 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1570 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1571
1572 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1573 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1574 if (lastElapsed > 0) {
1575 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001576 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001577 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001578 } else {
1579 // app is now eligible to run alarms at the originally requested window.
1580 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001581 alarm.whenElapsed = alarm.expectedWhenElapsed;
1582 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001583 }
1584 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001585 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001586 }
1587
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001588 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1589 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001590 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001591 // The caller has given the time they want this to happen at, however we need
1592 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001593 // bring us out of idle at an earlier time.
1594 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001595 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001596 }
1597 // Add fuzz to make the alarm go off some time before the actual desired time.
1598 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001599 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001600 if (fuzz > 0) {
1601 if (mRandom == null) {
1602 mRandom = new Random();
1603 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001604 final int delta = mRandom.nextInt(fuzz);
1605 a.whenElapsed -= delta;
1606 if (false) {
1607 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1608 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1609 Slog.d(TAG, "Applied fuzz: " + fuzz);
1610 Slog.d(TAG, "Final delta: " + delta);
1611 Slog.d(TAG, "Final when: " + a.whenElapsed);
1612 }
1613 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001614 }
1615
1616 } else if (mPendingIdleUntil != null) {
1617 // We currently have an idle until alarm scheduled; if the new alarm has
1618 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001619 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1620 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1621 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001622 == 0) {
1623 mPendingWhileIdleAlarms.add(a);
1624 return;
1625 }
1626 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001627 if (RECORD_DEVICE_IDLE_ALARMS) {
1628 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1629 IdleDispatchEntry ent = new IdleDispatchEntry();
1630 ent.uid = a.uid;
1631 ent.pkg = a.operation.getCreatorPackage();
1632 ent.tag = a.operation.getTag("");
1633 ent.op = "SET";
1634 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1635 ent.argRealtime = a.whenElapsed;
1636 mAllowWhileIdleDispatches.add(ent);
1637 }
1638 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001639 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001640 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001641
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001642 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001643 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001644 }
1645
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001646 boolean needRebatch = false;
1647
1648 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001649 if (RECORD_DEVICE_IDLE_ALARMS) {
1650 if (mPendingIdleUntil == null) {
1651 IdleDispatchEntry ent = new IdleDispatchEntry();
1652 ent.uid = 0;
1653 ent.pkg = "START IDLE";
1654 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1655 mAllowWhileIdleDispatches.add(ent);
1656 }
1657 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001658 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1659 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1660 + " to " + a);
1661 }
1662
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001663 mPendingIdleUntil = a;
1664 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001665 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1666 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1667 mNextWakeFromIdle = a;
1668 // If this wake from idle is earlier than whatever was previously scheduled,
1669 // and we are currently idling, then we need to rebatch alarms in case the idle
1670 // until time needs to be updated.
1671 if (mPendingIdleUntil != null) {
1672 needRebatch = true;
1673 }
1674 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001675 }
1676
1677 if (!rebatching) {
1678 if (DEBUG_VALIDATE) {
1679 if (doValidate && !validateConsistencyLocked()) {
1680 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1681 + " when(hex)=" + Long.toHexString(a.when)
1682 + " whenElapsed=" + a.whenElapsed
1683 + " maxWhenElapsed=" + a.maxWhenElapsed
1684 + " interval=" + a.repeatInterval + " op=" + a.operation
1685 + " flags=0x" + Integer.toHexString(a.flags));
1686 rebatchAllAlarmsLocked(false);
1687 needRebatch = false;
1688 }
1689 }
1690
1691 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001692 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001693 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001694
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001695 rescheduleKernelAlarmsLocked();
1696 updateNextAlarmClockLocked();
1697 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001698 }
1699
Christopher Tate1d99c392017-12-07 16:54:04 -08001700 /**
1701 * System-process internal API
1702 */
1703 private final class LocalService implements AlarmManagerInternal {
1704 @Override
1705 public void removeAlarmsForUid(int uid) {
1706 synchronized (mLock) {
1707 removeLocked(uid);
1708 }
1709 }
1710 }
1711
1712 /**
1713 * Public-facing binder interface
1714 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001715 private final IBinder mService = new IAlarmManager.Stub() {
1716 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001717 public void set(String callingPackage,
1718 int type, long triggerAtTime, long windowLength, long interval, int flags,
1719 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1720 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001721 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001722
1723 // make sure the caller is not lying about which package should be blamed for
1724 // wakelock time spent in alarm delivery
1725 mAppOps.checkPackage(callingUid, callingPackage);
1726
1727 // Repeating alarms must use PendingIntent, not direct listener
1728 if (interval != 0) {
1729 if (directReceiver != null) {
1730 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1731 }
1732 }
1733
Adam Lesinski182f73f2013-12-05 16:48:06 -08001734 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001735 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001736 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001737 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001738 }
1739
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001740 // No incoming callers can request either WAKE_FROM_IDLE or
1741 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1742 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1743 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1744
1745 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1746 // manager when to come out of idle mode, which is only for DeviceIdleController.
1747 if (callingUid != Process.SYSTEM_UID) {
1748 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1749 }
1750
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001751 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001752 if (windowLength == AlarmManager.WINDOW_EXACT) {
1753 flags |= AlarmManager.FLAG_STANDALONE;
1754 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001755
1756 // If this alarm is for an alarm clock, then it must be standalone and we will
1757 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001758 if (alarmClock != null) {
1759 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001760
1761 // If the caller is a core system component or on the user's whitelist, and not calling
1762 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1763 // This means we will allow these alarms to go off as normal even while idle, with no
1764 // timing restrictions.
1765 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001766 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001767 || ((mAppStateTracker != null)
1768 && mAppStateTracker.isUidPowerSaveWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001769 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1770 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001771 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001772
Christopher Tate14a7bb02015-10-01 10:24:31 -07001773 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1774 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001775 }
Christopher Tate89779822012-08-31 14:40:03 -07001776
Adam Lesinski182f73f2013-12-05 16:48:06 -08001777 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001778 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001779 getContext().enforceCallingOrSelfPermission(
1780 "android.permission.SET_TIME",
1781 "setTime");
1782
mswest463f4c99d2018-02-01 10:13:10 -08001783 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001784 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001785
1786 @Override
1787 public void setTimeZone(String tz) {
1788 getContext().enforceCallingOrSelfPermission(
1789 "android.permission.SET_TIME_ZONE",
1790 "setTimeZone");
1791
1792 final long oldId = Binder.clearCallingIdentity();
1793 try {
1794 setTimeZoneImpl(tz);
1795 } finally {
1796 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001797 }
1798 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001799
Adam Lesinski182f73f2013-12-05 16:48:06 -08001800 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001801 public void remove(PendingIntent operation, IAlarmListener listener) {
1802 if (operation == null && listener == null) {
1803 Slog.w(TAG, "remove() with no intent or listener");
1804 return;
1805 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001806
Christopher Tate14a7bb02015-10-01 10:24:31 -07001807 synchronized (mLock) {
1808 removeLocked(operation, listener);
1809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001811
Adam Lesinski182f73f2013-12-05 16:48:06 -08001812 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001813 public long getNextWakeFromIdleTime() {
1814 return getNextWakeFromIdleTimeImpl();
1815 }
1816
1817 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001818 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001819 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1820 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1821 "getNextAlarmClock", null);
1822
1823 return getNextAlarmClockImpl(userId);
1824 }
1825
1826 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001827 public long currentNetworkTimeMillis() {
1828 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1829 if (time.hasCache()) {
1830 return time.currentTimeMillis();
1831 } else {
1832 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1833 }
1834 }
1835
1836 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001837 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001838 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001839
1840 if (args.length > 0 && "--proto".equals(args[0])) {
1841 dumpProto(fd);
1842 } else {
1843 dumpImpl(pw);
1844 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001845 }
mswest463f4c99d2018-02-01 10:13:10 -08001846
1847 @Override
1848 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1849 FileDescriptor err, String[] args, ShellCallback callback,
1850 ResultReceiver resultReceiver) {
1851 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1852 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001853 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001854
Adam Lesinski182f73f2013-12-05 16:48:06 -08001855 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 synchronized (mLock) {
1857 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001858 mConstants.dump(pw);
1859 pw.println();
1860
Makoto Onukie4918212018-02-06 11:30:15 -08001861 if (mAppStateTracker != null) {
1862 mAppStateTracker.dump(pw, " ");
1863 pw.println();
1864 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001865
Suprabh Shukla75edab12018-01-29 14:09:06 -08001866 pw.println(" App Standby Parole: " + mAppStandbyParole);
1867 pw.println();
1868
Christopher Tatee0a22b32013-07-11 14:43:13 -07001869 final long nowRTC = System.currentTimeMillis();
1870 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001871 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001872
Dianne Hackborna750a632015-06-16 17:18:23 -07001873 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001874 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001875 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001876 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001877 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001878 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001879 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1880 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001881 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001882 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1883 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001884 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1885 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001886 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001887 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001888 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001889 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1890 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001891 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001892 pw.print(" Max wakeup delay: ");
1893 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1894 pw.println();
1895 pw.print(" Time since last dispatch: ");
1896 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1897 pw.println();
1898 pw.print(" Next non-wakeup delivery time: ");
1899 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1900 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001901
1902 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1903 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001904 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001905 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001906 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001907 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001908 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1909 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001910 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001911 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1912 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001913 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001914 pw.print(" = "); pw.println(mLastWakeup);
1915 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1916 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001917 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001918
John Spurlock604a5ee2015-06-01 12:27:22 -04001919 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001920 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001921 final TreeSet<Integer> users = new TreeSet<>();
1922 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1923 users.add(mNextAlarmClockForUser.keyAt(i));
1924 }
1925 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1926 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1927 }
1928 for (int user : users) {
1929 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1930 final long time = next != null ? next.getTriggerTime() : 0;
1931 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001932 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001933 pw.print(" pendingSend:"); pw.print(pendingSend);
1934 pw.print(" time:"); pw.print(time);
1935 if (time > 0) {
1936 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1937 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1938 }
1939 pw.println();
1940 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001941 if (mAlarmBatches.size() > 0) {
1942 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001943 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001944 pw.println(mAlarmBatches.size());
1945 for (Batch b : mAlarmBatches) {
1946 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001947 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001950 pw.println();
1951 pw.println(" Pending user blocked background alarms: ");
1952 boolean blocked = false;
1953 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1954 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1955 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1956 blocked = true;
1957 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1958 }
1959 }
1960 if (!blocked) {
1961 pw.println(" none");
1962 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001963
Suprabh Shukla75edab12018-01-29 14:09:06 -08001964 pw.println(" mLastAlarmDeliveredForPackage:");
1965 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1966 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1967 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1968 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1969 pw.println();
1970 }
1971 pw.println();
1972
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001973 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001974 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001975 pw.println(" Idle mode state:");
1976 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001977 if (mPendingIdleUntil != null) {
1978 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001979 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001980 } else {
1981 pw.println("null");
1982 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001983 pw.println(" Pending alarms:");
1984 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001985 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001986 if (mNextWakeFromIdle != null) {
1987 pw.println();
1988 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001989 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001990 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001991
1992 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001993 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001994 if (mPendingNonWakeupAlarms.size() > 0) {
1995 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001996 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001997 } else {
1998 pw.println("(none)");
1999 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002000 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002001 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2002 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002003 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002004 pw.print(", max non-interactive time: ");
2005 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2006 pw.println();
2007
2008 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002009 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002010 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2011 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2012 pw.print(" Listener send count: "); pw.println(mListenerCount);
2013 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002014 pw.println();
2015
Christopher Tate7f2a0352015-12-08 10:24:33 -08002016 if (mInFlight.size() > 0) {
2017 pw.println("Outstanding deliveries:");
2018 for (int i = 0; i < mInFlight.size(); i++) {
2019 pw.print(" #"); pw.print(i); pw.print(": ");
2020 pw.println(mInFlight.get(i));
2021 }
2022 pw.println();
2023 }
2024
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002025 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002026 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002027 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002028 pw.print(" UID ");
2029 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2030 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002031 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002032 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2033 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2034
2035 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2036 pw.print(" Next allowed:");
2037 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2038 pw.print(" (");
2039 TimeUtils.formatDuration(minInterval, 0, pw);
2040 pw.print(")");
2041
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002042 pw.println();
2043 }
2044 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002045
2046 pw.print(" mUseAllowWhileIdleShortTime: [");
2047 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2048 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2049 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2050 pw.print(" ");
2051 }
2052 }
2053 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002054 pw.println();
2055
Dianne Hackborn81038902012-11-26 17:04:09 -08002056 if (mLog.dump(pw, " Recent problems", " ")) {
2057 pw.println();
2058 }
2059
2060 final FilterStats[] topFilters = new FilterStats[10];
2061 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2062 @Override
2063 public int compare(FilterStats lhs, FilterStats rhs) {
2064 if (lhs.aggregateTime < rhs.aggregateTime) {
2065 return 1;
2066 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2067 return -1;
2068 }
2069 return 0;
2070 }
2071 };
2072 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002073 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002074 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2075 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2076 for (int ip=0; ip<uidStats.size(); ip++) {
2077 BroadcastStats bs = uidStats.valueAt(ip);
2078 for (int is=0; is<bs.filterStats.size(); is++) {
2079 FilterStats fs = bs.filterStats.valueAt(is);
2080 int pos = len > 0
2081 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2082 if (pos < 0) {
2083 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002084 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002085 if (pos < topFilters.length) {
2086 int copylen = topFilters.length - pos - 1;
2087 if (copylen > 0) {
2088 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2089 }
2090 topFilters[pos] = fs;
2091 if (len < topFilters.length) {
2092 len++;
2093 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002094 }
2095 }
2096 }
2097 }
2098 if (len > 0) {
2099 pw.println(" Top Alarms:");
2100 for (int i=0; i<len; i++) {
2101 FilterStats fs = topFilters[i];
2102 pw.print(" ");
2103 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2104 TimeUtils.formatDuration(fs.aggregateTime, pw);
2105 pw.print(" running, "); pw.print(fs.numWakeup);
2106 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002107 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2108 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002109 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002110 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002111 pw.println();
2112 }
2113 }
2114
2115 pw.println(" ");
2116 pw.println(" Alarm Stats:");
2117 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002118 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2119 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2120 for (int ip=0; ip<uidStats.size(); ip++) {
2121 BroadcastStats bs = uidStats.valueAt(ip);
2122 pw.print(" ");
2123 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2124 UserHandle.formatUid(pw, bs.mUid);
2125 pw.print(":");
2126 pw.print(bs.mPackageName);
2127 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2128 pw.print(" running, "); pw.print(bs.numWakeup);
2129 pw.println(" wakeups:");
2130 tmpFilters.clear();
2131 for (int is=0; is<bs.filterStats.size(); is++) {
2132 tmpFilters.add(bs.filterStats.valueAt(is));
2133 }
2134 Collections.sort(tmpFilters, comparator);
2135 for (int i=0; i<tmpFilters.size(); i++) {
2136 FilterStats fs = tmpFilters.get(i);
2137 pw.print(" ");
2138 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2139 TimeUtils.formatDuration(fs.aggregateTime, pw);
2140 pw.print(" "); pw.print(fs.numWakeup);
2141 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002142 pw.print(" alarms, last ");
2143 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2144 pw.println(":");
2145 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002146 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002147 pw.println();
2148 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002149 }
2150 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002151 pw.println();
2152 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002153
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002154 if (RECORD_DEVICE_IDLE_ALARMS) {
2155 pw.println();
2156 pw.println(" Allow while idle dispatches:");
2157 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2158 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2159 pw.print(" ");
2160 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2161 pw.print(": ");
2162 UserHandle.formatUid(pw, ent.uid);
2163 pw.print(":");
2164 pw.println(ent.pkg);
2165 if (ent.op != null) {
2166 pw.print(" ");
2167 pw.print(ent.op);
2168 pw.print(" / ");
2169 pw.print(ent.tag);
2170 if (ent.argRealtime != 0) {
2171 pw.print(" (");
2172 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2173 pw.print(")");
2174 }
2175 pw.println();
2176 }
2177 }
2178 }
2179
Christopher Tate18a75f12013-07-01 18:18:59 -07002180 if (WAKEUP_STATS) {
2181 pw.println();
2182 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002183 long last = -1;
2184 for (WakeupEvent event : mRecentWakeups) {
2185 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2186 pw.print('|');
2187 if (last < 0) {
2188 pw.print('0');
2189 } else {
2190 pw.print(event.when - last);
2191 }
2192 last = event.when;
2193 pw.print('|'); pw.print(event.uid);
2194 pw.print('|'); pw.print(event.action);
2195 pw.println();
2196 }
2197 pw.println();
2198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002199 }
2200 }
2201
Kweku Adams61e03292017-10-19 14:27:12 -07002202 void dumpProto(FileDescriptor fd) {
2203 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2204
2205 synchronized (mLock) {
2206 final long nowRTC = System.currentTimeMillis();
2207 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002208 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2209 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2210 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002211 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002212 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002213 mLastTimeChangeRealtime);
2214
Yi Jin2b30f322018-02-20 15:41:47 -08002215 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002216
Makoto Onukie4918212018-02-06 11:30:15 -08002217 if (mAppStateTracker != null) {
2218 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002219 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002220 }
Kweku Adams61e03292017-10-19 14:27:12 -07002221
Yi Jin2b30f322018-02-20 15:41:47 -08002222 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002223 if (!mInteractive) {
2224 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002225 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002226 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002227 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002228 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002229 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002230 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002231 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002232 nowElapsed - mNextNonWakeupDeliveryTime);
2233 }
2234
Yi Jin2b30f322018-02-20 15:41:47 -08002235 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002236 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002237 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002238 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002239 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002240 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002241 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002242 nowElapsed - mLastWakeupSet);
Yi Jin2b30f322018-02-20 15:41:47 -08002243 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002244
2245 final TreeSet<Integer> users = new TreeSet<>();
2246 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2247 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2248 users.add(mNextAlarmClockForUser.keyAt(i));
2249 }
2250 final int pendingSendNextAlarmClockChangedForUserSize =
2251 mPendingSendNextAlarmClockChangedForUser.size();
2252 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2253 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2254 }
2255 for (int user : users) {
2256 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2257 final long time = next != null ? next.getTriggerTime() : 0;
2258 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002259 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002260 proto.write(AlarmClockMetadataProto.USER, user);
2261 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2262 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2263 proto.end(aToken);
2264 }
2265 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002266 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002267 nowElapsed, nowRTC);
2268 }
2269 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2270 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2271 if (blockedAlarms != null) {
2272 for (Alarm a : blockedAlarms) {
2273 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002274 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002275 nowElapsed, nowRTC);
2276 }
2277 }
2278 }
2279 if (mPendingIdleUntil != null) {
2280 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002281 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002282 }
2283 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002284 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002285 nowElapsed, nowRTC);
2286 }
2287 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002288 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002289 nowElapsed, nowRTC);
2290 }
2291
2292 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002293 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002294 nowElapsed, nowRTC);
2295 }
2296
Yi Jin2b30f322018-02-20 15:41:47 -08002297 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2298 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2299 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2300 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002301 mNonInteractiveTime);
2302
Yi Jin2b30f322018-02-20 15:41:47 -08002303 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2304 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2305 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2306 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2307 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002308
2309 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002310 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002311 }
2312
Kweku Adams61e03292017-10-19 14:27:12 -07002313 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2314 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002315 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002316 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2317 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2318
Yi Jin2b30f322018-02-20 15:41:47 -08002319 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2320 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2321 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002322 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002323 proto.end(token);
2324 }
2325
Makoto Onukiadb50d82018-01-29 16:20:30 -08002326 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2327 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002328 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002329 mUseAllowWhileIdleShortTime.keyAt(i));
2330 }
2331 }
2332
Yi Jin2b30f322018-02-20 15:41:47 -08002333 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002334
2335 final FilterStats[] topFilters = new FilterStats[10];
2336 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2337 @Override
2338 public int compare(FilterStats lhs, FilterStats rhs) {
2339 if (lhs.aggregateTime < rhs.aggregateTime) {
2340 return 1;
2341 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2342 return -1;
2343 }
2344 return 0;
2345 }
2346 };
2347 int len = 0;
2348 // Get the top 10 FilterStats, ordered by aggregateTime.
2349 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2350 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2351 for (int ip = 0; ip < uidStats.size(); ++ip) {
2352 BroadcastStats bs = uidStats.valueAt(ip);
2353 for (int is = 0; is < bs.filterStats.size(); ++is) {
2354 FilterStats fs = bs.filterStats.valueAt(is);
2355 int pos = len > 0
2356 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2357 if (pos < 0) {
2358 pos = -pos - 1;
2359 }
2360 if (pos < topFilters.length) {
2361 int copylen = topFilters.length - pos - 1;
2362 if (copylen > 0) {
2363 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2364 }
2365 topFilters[pos] = fs;
2366 if (len < topFilters.length) {
2367 len++;
2368 }
2369 }
2370 }
2371 }
2372 }
2373 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002374 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002375 FilterStats fs = topFilters[i];
2376
Yi Jin2b30f322018-02-20 15:41:47 -08002377 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2378 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002379 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002380 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002381
2382 proto.end(token);
2383 }
2384
2385 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2386 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2387 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2388 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002389 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002390
2391 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002392 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002393
2394 // uidStats is an ArrayMap, which we can't sort.
2395 tmpFilters.clear();
2396 for (int is = 0; is < bs.filterStats.size(); ++is) {
2397 tmpFilters.add(bs.filterStats.valueAt(is));
2398 }
2399 Collections.sort(tmpFilters, comparator);
2400 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002401 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002402 }
2403
2404 proto.end(token);
2405 }
2406 }
2407
2408 if (RECORD_DEVICE_IDLE_ALARMS) {
2409 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2410 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2411 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002412 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002413
2414 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2415 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2416 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2417 proto.write(IdleDispatchEntryProto.OP, ent.op);
2418 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2419 ent.elapsedRealtime);
2420 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2421
2422 proto.end(token);
2423 }
2424 }
2425
2426 if (WAKEUP_STATS) {
2427 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002428 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002429 proto.write(WakeupEventProto.UID, event.uid);
2430 proto.write(WakeupEventProto.ACTION, event.action);
2431 proto.write(WakeupEventProto.WHEN, event.when);
2432 proto.end(token);
2433 }
2434 }
2435 }
2436
2437 proto.flush();
2438 }
2439
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002440 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002441 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2442 PrintWriter pw = new PrintWriter(bs);
2443 final long nowRTC = System.currentTimeMillis();
2444 final long nowELAPSED = SystemClock.elapsedRealtime();
2445 final int NZ = mAlarmBatches.size();
2446 for (int iz = 0; iz < NZ; iz++) {
2447 Batch bz = mAlarmBatches.get(iz);
2448 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002449 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002450 pw.flush();
2451 Slog.v(TAG, bs.toString());
2452 bs.reset();
2453 }
2454 }
2455
2456 private boolean validateConsistencyLocked() {
2457 if (DEBUG_VALIDATE) {
2458 long lastTime = Long.MIN_VALUE;
2459 final int N = mAlarmBatches.size();
2460 for (int i = 0; i < N; i++) {
2461 Batch b = mAlarmBatches.get(i);
2462 if (b.start >= lastTime) {
2463 // duplicate start times are okay because of standalone batches
2464 lastTime = b.start;
2465 } else {
2466 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002467 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2468 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002469 return false;
2470 }
2471 }
2472 }
2473 return true;
2474 }
2475
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002476 private Batch findFirstWakeupBatchLocked() {
2477 final int N = mAlarmBatches.size();
2478 for (int i = 0; i < N; i++) {
2479 Batch b = mAlarmBatches.get(i);
2480 if (b.hasWakeups()) {
2481 return b;
2482 }
2483 }
2484 return null;
2485 }
2486
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002487 long getNextWakeFromIdleTimeImpl() {
2488 synchronized (mLock) {
2489 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2490 }
2491 }
2492
2493 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002494 synchronized (mLock) {
2495 return mNextAlarmClockForUser.get(userId);
2496 }
2497 }
2498
2499 /**
2500 * Recomputes the next alarm clock for all users.
2501 */
2502 private void updateNextAlarmClockLocked() {
2503 if (!mNextAlarmClockMayChange) {
2504 return;
2505 }
2506 mNextAlarmClockMayChange = false;
2507
Jose Lima235510e2014-08-13 12:50:01 -07002508 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002509 nextForUser.clear();
2510
2511 final int N = mAlarmBatches.size();
2512 for (int i = 0; i < N; i++) {
2513 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2514 final int M = alarms.size();
2515
2516 for (int j = 0; j < M; j++) {
2517 Alarm a = alarms.get(j);
2518 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002519 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002520 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002521
2522 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002523 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002524 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002525 " for user " + userId);
2526 }
2527
2528 // Alarms and batches are sorted by time, no need to compare times here.
2529 if (nextForUser.get(userId) == null) {
2530 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002531 } else if (a.alarmClock.equals(current)
2532 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2533 // same/earlier time and it's the one we cited before, so stick with it
2534 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002535 }
2536 }
2537 }
2538 }
2539
2540 // Update mNextAlarmForUser with new values.
2541 final int NN = nextForUser.size();
2542 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002543 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002544 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002545 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002546 if (!newAlarm.equals(currentAlarm)) {
2547 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2548 }
2549 }
2550
2551 // Remove users without any alarm clocks scheduled.
2552 final int NNN = mNextAlarmClockForUser.size();
2553 for (int i = NNN - 1; i >= 0; i--) {
2554 int userId = mNextAlarmClockForUser.keyAt(i);
2555 if (nextForUser.get(userId) == null) {
2556 updateNextAlarmInfoForUserLocked(userId, null);
2557 }
2558 }
2559 }
2560
Jose Lima235510e2014-08-13 12:50:01 -07002561 private void updateNextAlarmInfoForUserLocked(int userId,
2562 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002563 if (alarmClock != null) {
2564 if (DEBUG_ALARM_CLOCK) {
2565 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002566 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002567 }
2568 mNextAlarmClockForUser.put(userId, alarmClock);
2569 } else {
2570 if (DEBUG_ALARM_CLOCK) {
2571 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2572 }
2573 mNextAlarmClockForUser.remove(userId);
2574 }
2575
2576 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2577 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2578 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2579 }
2580
2581 /**
2582 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2583 * for which alarm clocks have changed since the last call to this.
2584 *
2585 * Do not call with a lock held. Only call from mHandler's thread.
2586 *
2587 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2588 */
2589 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002590 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002591 pendingUsers.clear();
2592
2593 synchronized (mLock) {
2594 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2595 for (int i = 0; i < N; i++) {
2596 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2597 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2598 }
2599 mPendingSendNextAlarmClockChangedForUser.clear();
2600 }
2601
2602 final int N = pendingUsers.size();
2603 for (int i = 0; i < N; i++) {
2604 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002605 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002606 Settings.System.putStringForUser(getContext().getContentResolver(),
2607 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002608 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002609 userId);
2610
2611 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2612 new UserHandle(userId));
2613 }
2614 }
2615
2616 /**
2617 * Formats an alarm like platform/packages/apps/DeskClock used to.
2618 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002619 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2620 int userId) {
2621 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002622 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2623 return (info == null) ? "" :
2624 DateFormat.format(pattern, info.getTriggerTime()).toString();
2625 }
2626
Adam Lesinski182f73f2013-12-05 16:48:06 -08002627 void rescheduleKernelAlarmsLocked() {
2628 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2629 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002630 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002631 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002632 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002633 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002634 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002635 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002636 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002637 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002638 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002639 if (firstBatch != firstWakeup) {
2640 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002641 }
2642 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002643 if (mPendingNonWakeupAlarms.size() > 0) {
2644 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2645 nextNonWakeup = mNextNonWakeupDeliveryTime;
2646 }
2647 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002648 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002649 mNextNonWakeup = nextNonWakeup;
2650 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2651 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002652 }
2653
Christopher Tate14a7bb02015-10-01 10:24:31 -07002654 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002655 if (operation == null && directReceiver == null) {
2656 if (localLOGV) {
2657 Slog.w(TAG, "requested remove() of null operation",
2658 new RuntimeException("here"));
2659 }
2660 return;
2661 }
2662
Adam Lesinski182f73f2013-12-05 16:48:06 -08002663 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002664 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002665 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2666 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002667 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002668 if (b.size() == 0) {
2669 mAlarmBatches.remove(i);
2670 }
2671 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002672 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002673 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002674 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2675 mPendingWhileIdleAlarms.remove(i);
2676 }
2677 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002678 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2679 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2680 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2681 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2682 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2683 alarmsForUid.remove(j);
2684 }
2685 }
2686 if (alarmsForUid.size() == 0) {
2687 mPendingBackgroundAlarms.removeAt(i);
2688 }
2689 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002690 if (didRemove) {
2691 if (DEBUG_BATCH) {
2692 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2693 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002694 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002695 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002696 mPendingIdleUntil = null;
2697 restorePending = true;
2698 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002699 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002700 mNextWakeFromIdle = null;
2701 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002702 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002703 if (restorePending) {
2704 restorePendingWhileIdleAlarmsLocked();
2705 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002706 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002707 }
2708 }
2709
Christopher Tate1d99c392017-12-07 16:54:04 -08002710 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002711 if (uid == Process.SYSTEM_UID) {
2712 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2713 return;
2714 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002715 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002716 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002717 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2718 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002719 didRemove |= b.remove(whichAlarms);
2720 if (b.size() == 0) {
2721 mAlarmBatches.remove(i);
2722 }
2723 }
2724 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2725 final Alarm a = mPendingWhileIdleAlarms.get(i);
2726 if (a.uid == uid) {
2727 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2728 mPendingWhileIdleAlarms.remove(i);
2729 }
2730 }
2731 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2732 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2733 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2734 if (alarmsForUid.get(j).uid == uid) {
2735 alarmsForUid.remove(j);
2736 }
2737 }
2738 if (alarmsForUid.size() == 0) {
2739 mPendingBackgroundAlarms.removeAt(i);
2740 }
2741 }
2742 if (didRemove) {
2743 if (DEBUG_BATCH) {
2744 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2745 }
2746 rebatchAllAlarmsLocked(true);
2747 rescheduleKernelAlarmsLocked();
2748 updateNextAlarmClockLocked();
2749 }
2750 }
2751
2752 void removeLocked(final String packageName) {
2753 if (packageName == null) {
2754 if (localLOGV) {
2755 Slog.w(TAG, "requested remove() of null packageName",
2756 new RuntimeException("here"));
2757 }
2758 return;
2759 }
2760
2761 boolean didRemove = false;
2762 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002763 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002764 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2765 Batch b = mAlarmBatches.get(i);
2766 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002767 if (b.size() == 0) {
2768 mAlarmBatches.remove(i);
2769 }
2770 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002771 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2772 if (oldHasTick != newHasTick) {
2773 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2774 }
2775
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002776 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002777 final Alarm a = mPendingWhileIdleAlarms.get(i);
2778 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002779 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2780 mPendingWhileIdleAlarms.remove(i);
2781 }
2782 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002783 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2784 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2785 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2786 if (alarmsForUid.get(j).matches(packageName)) {
2787 alarmsForUid.remove(j);
2788 }
2789 }
2790 if (alarmsForUid.size() == 0) {
2791 mPendingBackgroundAlarms.removeAt(i);
2792 }
2793 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 if (didRemove) {
2795 if (DEBUG_BATCH) {
2796 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2797 }
2798 rebatchAllAlarmsLocked(true);
2799 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002800 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002801 }
2802 }
2803
Christopher Tate1d99c392017-12-07 16:54:04 -08002804 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002805 if (uid == Process.SYSTEM_UID) {
2806 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2807 return;
2808 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002809 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002810 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2811 try {
2812 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2813 uid, a.packageName)) {
2814 return true;
2815 }
2816 } catch (RemoteException e) { /* fall through */}
2817 return false;
2818 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002819 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2820 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002821 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002822 if (b.size() == 0) {
2823 mAlarmBatches.remove(i);
2824 }
2825 }
2826 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2827 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002828 if (a.uid == uid) {
2829 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2830 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002831 }
2832 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002833 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2834 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2835 mPendingBackgroundAlarms.removeAt(i);
2836 }
2837 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002838 if (didRemove) {
2839 if (DEBUG_BATCH) {
2840 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2841 }
2842 rebatchAllAlarmsLocked(true);
2843 rescheduleKernelAlarmsLocked();
2844 updateNextAlarmClockLocked();
2845 }
2846 }
2847
Adam Lesinski182f73f2013-12-05 16:48:06 -08002848 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002849 if (userHandle == UserHandle.USER_SYSTEM) {
2850 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2851 return;
2852 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002853 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002854 final Predicate<Alarm> whichAlarms =
2855 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002856 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2857 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002858 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002859 if (b.size() == 0) {
2860 mAlarmBatches.remove(i);
2861 }
2862 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002863 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002864 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002865 == userHandle) {
2866 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2867 mPendingWhileIdleAlarms.remove(i);
2868 }
2869 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002870 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2871 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2872 mPendingBackgroundAlarms.removeAt(i);
2873 }
2874 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002875 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2876 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2877 mLastAllowWhileIdleDispatch.removeAt(i);
2878 }
2879 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002880
2881 if (didRemove) {
2882 if (DEBUG_BATCH) {
2883 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2884 }
2885 rebatchAllAlarmsLocked(true);
2886 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002887 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002888 }
2889 }
2890
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002891 void interactiveStateChangedLocked(boolean interactive) {
2892 if (mInteractive != interactive) {
2893 mInteractive = interactive;
2894 final long nowELAPSED = SystemClock.elapsedRealtime();
2895 if (interactive) {
2896 if (mPendingNonWakeupAlarms.size() > 0) {
2897 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2898 mTotalDelayTime += thisDelayTime;
2899 if (mMaxDelayTime < thisDelayTime) {
2900 mMaxDelayTime = thisDelayTime;
2901 }
2902 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2903 mPendingNonWakeupAlarms.clear();
2904 }
2905 if (mNonInteractiveStartTime > 0) {
2906 long dur = nowELAPSED - mNonInteractiveStartTime;
2907 if (dur > mNonInteractiveTime) {
2908 mNonInteractiveTime = dur;
2909 }
2910 }
2911 } else {
2912 mNonInteractiveStartTime = nowELAPSED;
2913 }
2914 }
2915 }
2916
Adam Lesinski182f73f2013-12-05 16:48:06 -08002917 boolean lookForPackageLocked(String packageName) {
2918 for (int i = 0; i < mAlarmBatches.size(); i++) {
2919 Batch b = mAlarmBatches.get(i);
2920 if (b.hasPackage(packageName)) {
2921 return true;
2922 }
2923 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002924 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002925 final Alarm a = mPendingWhileIdleAlarms.get(i);
2926 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002927 return true;
2928 }
2929 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002930 return false;
2931 }
2932
2933 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002934 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002935 // The kernel never triggers alarms with negative wakeup times
2936 // so we ensure they are positive.
2937 long alarmSeconds, alarmNanoseconds;
2938 if (when < 0) {
2939 alarmSeconds = 0;
2940 alarmNanoseconds = 0;
2941 } else {
2942 alarmSeconds = when / 1000;
2943 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2944 }
Kweku Adams61e03292017-10-19 14:27:12 -07002945
Christopher Tate8b98ade2018-02-09 11:13:19 -08002946 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2947 if (result != 0) {
2948 final long nowElapsed = SystemClock.elapsedRealtime();
2949 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2950 + " type=" + type + " when=" + when
2951 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2952 + "), ret = " + result + " = " + Os.strerror(result));
2953 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002954 } else {
2955 Message msg = Message.obtain();
2956 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002957
Adam Lesinski182f73f2013-12-05 16:48:06 -08002958 mHandler.removeMessages(ALARM_EVENT);
2959 mHandler.sendMessageAtTime(msg, when);
2960 }
2961 }
2962
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002963 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002964 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002965 for (int i=list.size()-1; i>=0; i--) {
2966 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002967 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2968 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002969 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002970 }
2971 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002972
2973 private static final String labelForType(int type) {
2974 switch (type) {
2975 case RTC: return "RTC";
2976 case RTC_WAKEUP : return "RTC_WAKEUP";
2977 case ELAPSED_REALTIME : return "ELAPSED";
2978 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002979 }
2980 return "--unknown--";
2981 }
2982
2983 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002984 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002985 for (int i=list.size()-1; i>=0; i--) {
2986 Alarm a = list.get(i);
2987 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002988 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2989 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002990 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002991 }
2992 }
2993
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002994 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002995 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002996 if (alarm.alarmClock != null) {
2997 // Don't block alarm clocks
2998 return false;
2999 }
3000 if (alarm.operation != null
3001 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
3002 // Don't block starting foreground components
3003 return false;
3004 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003005 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003006 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003007 return (mAppStateTracker != null) &&
3008 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage, allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003009 }
3010
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003011 private native long init();
3012 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003013 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003014 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003015 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003016 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003017
Makoto Onukiadb50d82018-01-29 16:20:30 -08003018 private long getWhileIdleMinIntervalLocked(int uid) {
3019 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003020 final boolean ebs = (mAppStateTracker != null)
3021 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003022 if (!dozing && !ebs) {
3023 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3024 }
3025 if (dozing) {
3026 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3027 }
3028 if (mUseAllowWhileIdleShortTime.get(uid)) {
3029 // if the last allow-while-idle went off while uid was fg, or the uid
3030 // recently came into fg, don't block the alarm for long.
3031 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3032 }
3033 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3034 }
3035
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003036 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003037 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003038 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003039 // batches are temporally sorted, so we need only pull from the
3040 // start of the list until we either empty it or hit a batch
3041 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003042 while (mAlarmBatches.size() > 0) {
3043 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003044 if (batch.start > nowELAPSED) {
3045 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003046 break;
3047 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003048
Christopher Tatee0a22b32013-07-11 14:43:13 -07003049 // We will (re)schedule some alarms now; don't let that interfere
3050 // with delivery of this current batch
3051 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003052
Christopher Tatee0a22b32013-07-11 14:43:13 -07003053 final int N = batch.size();
3054 for (int i = 0; i < N; i++) {
3055 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003056
3057 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3058 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
3059 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003060 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003061 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003062 if (nowELAPSED < minTime) {
3063 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3064 // alarm went off for this app. Reschedule the alarm to be in the
3065 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003066 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003067 if (alarm.maxWhenElapsed < minTime) {
3068 alarm.maxWhenElapsed = minTime;
3069 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003070 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003071 if (RECORD_DEVICE_IDLE_ALARMS) {
3072 IdleDispatchEntry ent = new IdleDispatchEntry();
3073 ent.uid = alarm.uid;
3074 ent.pkg = alarm.operation.getCreatorPackage();
3075 ent.tag = alarm.operation.getTag("");
3076 ent.op = "RESCHEDULE";
3077 ent.elapsedRealtime = nowELAPSED;
3078 ent.argRealtime = lastTime;
3079 mAllowWhileIdleDispatches.add(ent);
3080 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003081 setImplLocked(alarm, true, false);
3082 continue;
3083 }
3084 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003085 if (isBackgroundRestricted(alarm)) {
3086 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3087 if (DEBUG_BG_LIMIT) {
3088 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3089 }
3090 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3091 if (alarmsForUid == null) {
3092 alarmsForUid = new ArrayList<>();
3093 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3094 }
3095 alarmsForUid.add(alarm);
3096 continue;
3097 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003098
Christopher Tatee0a22b32013-07-11 14:43:13 -07003099 alarm.count = 1;
3100 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003101 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3102 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003103 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003104 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003105 if (mPendingIdleUntil == alarm) {
3106 mPendingIdleUntil = null;
3107 rebatchAllAlarmsLocked(false);
3108 restorePendingWhileIdleAlarmsLocked();
3109 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003110 if (mNextWakeFromIdle == alarm) {
3111 mNextWakeFromIdle = null;
3112 rebatchAllAlarmsLocked(false);
3113 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003114
3115 // Recurring alarms may have passed several alarm intervals while the
3116 // phone was asleep or off, so pass a trigger count when sending them.
3117 if (alarm.repeatInterval > 0) {
3118 // this adjustment will be zero if we're late by
3119 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003120 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003121
3122 // Also schedule its next recurrence
3123 final long delta = alarm.count * alarm.repeatInterval;
3124 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003125 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003126 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003127 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3128 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003129 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003130
Christopher Tate864d42e2014-12-02 11:48:53 -08003131 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003132 hasWakeup = true;
3133 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003134
3135 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3136 if (alarm.alarmClock != null) {
3137 mNextAlarmClockMayChange = true;
3138 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003139 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003140 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003141
Christopher Tate1590f1e2014-10-02 17:27:57 -07003142 // This is a new alarm delivery set; bump the sequence number to indicate that
3143 // all apps' alarm delivery classes should be recalculated.
3144 mCurrentSeq++;
3145 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003146 Collections.sort(triggerList, mAlarmDispatchComparator);
3147
3148 if (localLOGV) {
3149 for (int i=0; i<triggerList.size(); i++) {
3150 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3151 }
3152 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003153
3154 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003155 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003156
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 /**
3158 * This Comparator sorts Alarms into increasing time order.
3159 */
3160 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3161 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003162 long when1 = a1.whenElapsed;
3163 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003164 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165 return 1;
3166 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003167 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003168 return -1;
3169 }
3170 return 0;
3171 }
3172 }
Kweku Adams61e03292017-10-19 14:27:12 -07003173
Makoto Onuki2206af32017-11-21 16:25:35 -08003174 @VisibleForTesting
3175 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003176 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003177 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003178 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003179 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003180 public final IAlarmListener listener;
3181 public final String listenerTag;
3182 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003183 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003184 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003185 public final AlarmManager.AlarmClockInfo alarmClock;
3186 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003187 public final int creatorUid;
3188 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003189 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003190 public int count;
3191 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003192 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003193 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003194 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003195 // Expected alarm expiry time before app standby deferring is applied.
3196 public long expectedWhenElapsed;
3197 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003198 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003199 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003200
Christopher Tate3e04b472013-10-21 17:51:31 -07003201 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003202 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3203 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3204 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003205 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003206 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003207 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3208 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003209 when = _when;
3210 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003211 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003212 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003213 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003214 repeatInterval = _interval;
3215 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003216 listener = _rec;
3217 listenerTag = _listenerTag;
3218 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003219 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003220 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003221 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003222 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003223 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003224 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003225 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003226 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003227
Christopher Tate14a7bb02015-10-01 10:24:31 -07003228 public static String makeTag(PendingIntent pi, String tag, int type) {
3229 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3230 ? "*walarm*:" : "*alarm*:";
3231 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3232 }
3233
3234 public WakeupEvent makeWakeupEvent(long nowRTC) {
3235 return new WakeupEvent(nowRTC, creatorUid,
3236 (operation != null)
3237 ? operation.getIntent().getAction()
3238 : ("<listener>:" + listenerTag));
3239 }
3240
3241 // Returns true if either matches
3242 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3243 return (operation != null)
3244 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003245 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003246 }
3247
3248 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003249 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003250 }
3251
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003252 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003253 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003254 StringBuilder sb = new StringBuilder(128);
3255 sb.append("Alarm{");
3256 sb.append(Integer.toHexString(System.identityHashCode(this)));
3257 sb.append(" type ");
3258 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003259 sb.append(" when ");
3260 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003261 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003262 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003263 sb.append('}');
3264 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 }
3266
Kweku Adams61e03292017-10-19 14:27:12 -07003267 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003268 SimpleDateFormat sdf) {
3269 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003270 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003271 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003272 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3273 expectedWhenElapsed, nowELAPSED, pw);
3274 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3275 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003276 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3277 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003278 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3279 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003280 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003281 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003282 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003283 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003284 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003285 }
3286 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003287 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003288 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003289 pw.print(" count="); pw.print(count);
3290 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003291 if (alarmClock != null) {
3292 pw.print(prefix); pw.println("Alarm clock:");
3293 pw.print(prefix); pw.print(" triggerTime=");
3294 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3295 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3296 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003297 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003298 if (listener != null) {
3299 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003301 }
Kweku Adams61e03292017-10-19 14:27:12 -07003302
3303 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3304 long nowRTC) {
3305 final long token = proto.start(fieldId);
3306
3307 proto.write(AlarmProto.TAG, statsTag);
3308 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003309 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003310 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3311 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3312 proto.write(AlarmProto.COUNT, count);
3313 proto.write(AlarmProto.FLAGS, flags);
3314 if (alarmClock != null) {
3315 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3316 }
3317 if (operation != null) {
3318 operation.writeToProto(proto, AlarmProto.OPERATION);
3319 }
3320 if (listener != null) {
3321 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3322 }
3323
3324 proto.end(token);
3325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003326 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003327
Christopher Tatee0a22b32013-07-11 14:43:13 -07003328 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3329 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003330 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3331 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003332 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003333 break;
3334 }
3335
Christopher Tatee0a22b32013-07-11 14:43:13 -07003336 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003337 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3338 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003339 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003340 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003341 }
3342 }
3343
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003344 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3345 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3346 if (timeSinceOn < 5*60*1000) {
3347 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3348 return 2*60*1000;
3349 } else if (timeSinceOn < 30*60*1000) {
3350 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3351 return 15*60*1000;
3352 } else {
3353 // Otherwise, we will delay by at most an hour.
3354 return 60*60*1000;
3355 }
3356 }
3357
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003358 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003359 if (duration < 15*60*1000) {
3360 // If the duration until the time is less than 15 minutes, the maximum fuzz
3361 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003362 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003363 } else if (duration < 90*60*1000) {
3364 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3365 return 15*60*1000;
3366 } else {
3367 // Otherwise, we will fuzz by at most half an hour.
3368 return 30*60*1000;
3369 }
3370 }
3371
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003372 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3373 if (mInteractive) {
3374 return false;
3375 }
3376 if (mLastAlarmDeliveryTime <= 0) {
3377 return false;
3378 }
minho.choo649acab2014-12-12 16:13:55 +09003379 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003380 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3381 // and the next delivery time is in the past, then just deliver them all. This
3382 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3383 return false;
3384 }
3385 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3386 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3387 }
3388
3389 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3390 mLastAlarmDeliveryTime = nowELAPSED;
3391 for (int i=0; i<triggerList.size(); i++) {
3392 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003393 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003394 if (alarm.wakeup) {
3395 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3396 } else {
3397 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3398 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003399 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003400 if (localLOGV) {
3401 Slog.v(TAG, "sending alarm " + alarm);
3402 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003403 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003404 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3405 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003406 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003407 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003408 } catch (RuntimeException e) {
3409 Slog.w(TAG, "Failure sending alarm.", e);
3410 }
Tim Murray175c0f92017-11-28 15:01:04 -08003411 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003412 }
3413 }
3414
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003415 private boolean isExemptFromAppStandby(Alarm a) {
3416 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3417 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3418 }
3419
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003420 private class AlarmThread extends Thread
3421 {
3422 public AlarmThread()
3423 {
3424 super("AlarmManager");
3425 }
Kweku Adams61e03292017-10-19 14:27:12 -07003426
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003427 public void run()
3428 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003429 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3430
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003431 while (true)
3432 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003433 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003434
Dianne Hackbornc3527222015-05-13 14:03:20 -07003435 final long nowRTC = System.currentTimeMillis();
3436 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003437 synchronized (mLock) {
3438 mLastWakeup = nowELAPSED;
3439 }
3440
3441 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003443 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003444 // The kernel can give us spurious time change notifications due to
3445 // small adjustments it makes internally; we want to filter those out.
3446 final long lastTimeChangeClockTime;
3447 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003448 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003449 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3450 expectedClockTime = lastTimeChangeClockTime
3451 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003452 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003453 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3454 || nowRTC > (expectedClockTime+1000)) {
3455 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003456 // let's do it!
3457 if (DEBUG_BATCH) {
3458 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3459 }
3460 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003461 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003462 rebatchAllAlarms();
3463 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003464 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003465 synchronized (mLock) {
3466 mNumTimeChanged++;
3467 mLastTimeChangeClockTime = nowRTC;
3468 mLastTimeChangeRealtime = nowELAPSED;
3469 }
3470 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3471 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003472 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003473 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3474 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003475 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3476
3477 // The world has changed on us, so we need to re-evaluate alarms
3478 // regardless of whether the kernel has told us one went off.
3479 result |= IS_WAKEUP_MASK;
3480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003481 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003482
Dianne Hackbornc3527222015-05-13 14:03:20 -07003483 if (result != TIME_CHANGED_MASK) {
3484 // If this was anything besides just a time change, then figure what if
3485 // anything to do about alarms.
3486 synchronized (mLock) {
3487 if (localLOGV) Slog.v(
3488 TAG, "Checking for alarms... rtc=" + nowRTC
3489 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003490
Dianne Hackbornc3527222015-05-13 14:03:20 -07003491 if (WAKEUP_STATS) {
3492 if ((result & IS_WAKEUP_MASK) != 0) {
3493 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3494 int n = 0;
3495 for (WakeupEvent event : mRecentWakeups) {
3496 if (event.when > newEarliest) break;
3497 n++; // number of now-stale entries at the list head
3498 }
3499 for (int i = 0; i < n; i++) {
3500 mRecentWakeups.remove();
3501 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003502
Dianne Hackbornc3527222015-05-13 14:03:20 -07003503 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003504 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003505 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003506
Christopher Tate8b98ade2018-02-09 11:13:19 -08003507 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003508 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3509 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3510 // if there are no wakeup alarms and the screen is off, we can
3511 // delay what we have so far until the future.
3512 if (mPendingNonWakeupAlarms.size() == 0) {
3513 mStartCurrentDelayTime = nowELAPSED;
3514 mNextNonWakeupDeliveryTime = nowELAPSED
3515 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3516 }
3517 mPendingNonWakeupAlarms.addAll(triggerList);
3518 mNumDelayedAlarms += triggerList.size();
3519 rescheduleKernelAlarmsLocked();
3520 updateNextAlarmClockLocked();
3521 } else {
3522 // now deliver the alarm intents; if there are pending non-wakeup
3523 // alarms, we need to merge them in to the list. note we don't
3524 // just deliver them first because we generally want non-wakeup
3525 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003526 if (mPendingNonWakeupAlarms.size() > 0) {
3527 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3528 triggerList.addAll(mPendingNonWakeupAlarms);
3529 Collections.sort(triggerList, mAlarmDispatchComparator);
3530 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3531 mTotalDelayTime += thisDelayTime;
3532 if (mMaxDelayTime < thisDelayTime) {
3533 mMaxDelayTime = thisDelayTime;
3534 }
3535 mPendingNonWakeupAlarms.clear();
3536 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003537 final ArraySet<Pair<String, Integer>> triggerPackages =
3538 new ArraySet<>();
3539 for (int i = 0; i < triggerList.size(); i++) {
3540 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003541 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003542 triggerPackages.add(Pair.create(
3543 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003544 }
3545 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003546 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003547 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3548 rescheduleKernelAlarmsLocked();
3549 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003551 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003552
3553 } else {
3554 // Just in case -- even though no wakeup flag was set, make sure
3555 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003556 synchronized (mLock) {
3557 rescheduleKernelAlarmsLocked();
3558 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003559 }
3560 }
3561 }
3562 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003563
David Christieebe51fc2013-07-26 13:23:29 -07003564 /**
3565 * Attribute blame for a WakeLock.
3566 * @param pi PendingIntent to attribute blame to if ws is null.
3567 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003568 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003569 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003570 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003571 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003572 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003573 final boolean unimportant = pi == mTimeTickSender;
3574 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003575 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003576 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003577 } else {
3578 mWakeLock.setHistoryTag(null);
3579 }
3580 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003581 if (ws != null) {
3582 mWakeLock.setWorkSource(ws);
3583 return;
3584 }
3585
Christopher Tate14a7bb02015-10-01 10:24:31 -07003586 final int uid = (knownUid >= 0)
3587 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003588 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003589 if (uid >= 0) {
3590 mWakeLock.setWorkSource(new WorkSource(uid));
3591 return;
3592 }
3593 } catch (Exception e) {
3594 }
3595
3596 // Something went wrong; fall back to attributing the lock to the OS
3597 mWakeLock.setWorkSource(null);
3598 }
3599
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003600 private class AlarmHandler extends Handler {
3601 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003602 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3603 public static final int LISTENER_TIMEOUT = 3;
3604 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003605 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3606 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003607 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003608
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003609 public AlarmHandler() {
3610 }
Kweku Adams61e03292017-10-19 14:27:12 -07003611
Makoto Onuki4d298b52018-02-05 10:54:58 -08003612 public void postRemoveForStopped(int uid) {
3613 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3614 }
3615
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003616 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003617 switch (msg.what) {
3618 case ALARM_EVENT: {
3619 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3620 synchronized (mLock) {
3621 final long nowRTC = System.currentTimeMillis();
3622 final long nowELAPSED = SystemClock.elapsedRealtime();
3623 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3624 updateNextAlarmClockLocked();
3625 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003626
Christopher Tate14a7bb02015-10-01 10:24:31 -07003627 // now trigger the alarms without the lock held
3628 for (int i=0; i<triggerList.size(); i++) {
3629 Alarm alarm = triggerList.get(i);
3630 try {
3631 alarm.operation.send();
3632 } catch (PendingIntent.CanceledException e) {
3633 if (alarm.repeatInterval > 0) {
3634 // This IntentSender is no longer valid, but this
3635 // is a repeating alarm, so toss the hoser.
3636 removeImpl(alarm.operation);
3637 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003638 }
3639 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003640 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003641 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003642
3643 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3644 sendNextAlarmClockChanged();
3645 break;
3646
3647 case LISTENER_TIMEOUT:
3648 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3649 break;
3650
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003651 case REPORT_ALARMS_ACTIVE:
3652 if (mLocalDeviceIdleController != null) {
3653 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3654 }
3655 break;
3656
Suprabh Shukla75edab12018-01-29 14:09:06 -08003657 case APP_STANDBY_PAROLE_CHANGED:
3658 synchronized (mLock) {
3659 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003660 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3661 rescheduleKernelAlarmsLocked();
3662 updateNextAlarmClockLocked();
3663 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003664 }
3665 break;
3666
3667 case APP_STANDBY_BUCKET_CHANGED:
3668 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003669 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3670 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3671 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3672 rescheduleKernelAlarmsLocked();
3673 updateNextAlarmClockLocked();
3674 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003675 }
3676 break;
3677
Makoto Onuki4d298b52018-02-05 10:54:58 -08003678 case REMOVE_FOR_STOPPED:
3679 synchronized (mLock) {
3680 removeForStoppedLocked(msg.arg1);
3681 }
3682 break;
3683
Christopher Tate14a7bb02015-10-01 10:24:31 -07003684 default:
3685 // nope, just ignore it
3686 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003687 }
3688 }
3689 }
Kweku Adams61e03292017-10-19 14:27:12 -07003690
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003691 class ClockReceiver extends BroadcastReceiver {
3692 public ClockReceiver() {
3693 IntentFilter filter = new IntentFilter();
3694 filter.addAction(Intent.ACTION_TIME_TICK);
3695 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003696 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 }
Kweku Adams61e03292017-10-19 14:27:12 -07003698
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003699 @Override
3700 public void onReceive(Context context, Intent intent) {
3701 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003702 if (DEBUG_BATCH) {
3703 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3704 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003705 synchronized (mLock) {
3706 mLastTickReceived = System.currentTimeMillis();
3707 }
Christopher Tate385e4982013-07-23 18:22:29 -07003708 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003709 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3710 // Since the kernel does not keep track of DST, we need to
3711 // reset the TZ information at the beginning of each day
3712 // based off of the current Zone gmt offset + userspace tracked
3713 // daylight savings information.
3714 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003715 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003716 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003717 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003718 }
3719 }
Kweku Adams61e03292017-10-19 14:27:12 -07003720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003722 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003723 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003724
3725 // Schedule this event for the amount of time that it would take to get to
3726 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003727 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003728
David Christieebe51fc2013-07-26 13:23:29 -07003729 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003730 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003731 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3732 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003733
3734 // Finally, remember when we set the tick alarm
3735 synchronized (mLock) {
3736 mLastTickSet = currentTime;
3737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
Christopher Tate385e4982013-07-23 18:22:29 -07003739
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003740 public void scheduleDateChangedEvent() {
3741 Calendar calendar = Calendar.getInstance();
3742 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003743 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 calendar.set(Calendar.MINUTE, 0);
3745 calendar.set(Calendar.SECOND, 0);
3746 calendar.set(Calendar.MILLISECOND, 0);
3747 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003748
3749 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003750 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3751 AlarmManager.FLAG_STANDALONE, workSource, null,
3752 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003753 }
3754 }
Kweku Adams61e03292017-10-19 14:27:12 -07003755
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003756 class InteractiveStateReceiver extends BroadcastReceiver {
3757 public InteractiveStateReceiver() {
3758 IntentFilter filter = new IntentFilter();
3759 filter.addAction(Intent.ACTION_SCREEN_OFF);
3760 filter.addAction(Intent.ACTION_SCREEN_ON);
3761 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3762 getContext().registerReceiver(this, filter);
3763 }
3764
3765 @Override
3766 public void onReceive(Context context, Intent intent) {
3767 synchronized (mLock) {
3768 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3769 }
3770 }
3771 }
3772
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 class UninstallReceiver extends BroadcastReceiver {
3774 public UninstallReceiver() {
3775 IntentFilter filter = new IntentFilter();
3776 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3777 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003778 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003780 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003781 // Register for events related to sdcard installation.
3782 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003783 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003784 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003785 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003786 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003787 }
Kweku Adams61e03292017-10-19 14:27:12 -07003788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003789 @Override
3790 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003791 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003792 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003793 String action = intent.getAction();
3794 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003795 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3796 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3797 for (String packageName : pkgList) {
3798 if (lookForPackageLocked(packageName)) {
3799 setResultCode(Activity.RESULT_OK);
3800 return;
3801 }
3802 }
3803 return;
3804 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003805 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003806 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3807 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3808 if (userHandle >= 0) {
3809 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003810 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3811 final Pair<String, Integer> packageUser =
3812 mLastAlarmDeliveredForPackage.keyAt(i);
3813 if (packageUser.second == userHandle) {
3814 mLastAlarmDeliveredForPackage.removeAt(i);
3815 }
3816 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003817 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003818 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003819 if (uid >= 0) {
3820 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003821 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003822 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003823 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003824 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3825 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3826 // This package is being updated; don't kill its alarms.
3827 return;
3828 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003829 Uri data = intent.getData();
3830 if (data != null) {
3831 String pkg = data.getSchemeSpecificPart();
3832 if (pkg != null) {
3833 pkgList = new String[]{pkg};
3834 }
3835 }
3836 }
3837 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003838 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3839 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3840 if (ArrayUtils.contains(pkgList, packageUser.first)
3841 && packageUser.second == UserHandle.getUserId(uid)) {
3842 mLastAlarmDeliveredForPackage.removeAt(i);
3843 }
3844 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003845 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003846 if (uid >= 0) {
3847 // package-removed case
3848 removeLocked(uid);
3849 } else {
3850 // external-applications-unavailable etc case
3851 removeLocked(pkg);
3852 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003853 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003854 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3855 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3856 if (uidStats.remove(pkg) != null) {
3857 if (uidStats.size() <= 0) {
3858 mBroadcastStats.removeAt(i);
3859 }
3860 }
3861 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003862 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003863 }
3864 }
3865 }
3866 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003867
3868 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003869 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003870 }
3871
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003872 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003873 if (disabled) {
3874 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003875 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003876 }
3877
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003878 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003879 }
3880
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003881 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003882 if (disabled) {
3883 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003884 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003885 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003886
3887 @Override public void onUidCachedChanged(int uid, boolean cached) {
3888 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003889 };
3890
Suprabh Shukla75edab12018-01-29 14:09:06 -08003891 /**
3892 * Tracking of app assignments to standby buckets
3893 */
3894 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3895 @Override
3896 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08003897 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003898 if (DEBUG_STANDBY) {
3899 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3900 bucket);
3901 }
3902 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003903 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3904 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003905 }
3906
3907 @Override
3908 public void onParoleStateChanged(boolean isParoleOn) {
3909 if (DEBUG_STANDBY) {
3910 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3911 }
3912 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3913 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3914 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3915 Boolean.valueOf(isParoleOn)).sendToTarget();
3916 }
3917 };
3918
Makoto Onuki2206af32017-11-21 16:25:35 -08003919 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003920 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003921 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003922 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003923 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003924 }
3925 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003926
3927 @Override
3928 public void unblockAlarmsForUid(int uid) {
3929 synchronized (mLock) {
3930 sendPendingBackgroundAlarmsLocked(uid, null);
3931 }
3932 }
3933
3934 @Override
3935 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3936 synchronized (mLock) {
3937 sendPendingBackgroundAlarmsLocked(uid, packageName);
3938 }
3939 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003940
3941 @Override
3942 public void onUidForeground(int uid, boolean foreground) {
3943 synchronized (mLock) {
3944 if (foreground) {
3945 mUseAllowWhileIdleShortTime.put(uid, true);
3946
3947 // Note we don't have to drain the pending while-idle alarms here, because
3948 // this event should coincide with unblockAlarmsForUid().
3949 }
3950 }
3951 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003952 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003953
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003954 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003955 String pkg = pi.getCreatorPackage();
3956 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003957 return getStatsLocked(uid, pkg);
3958 }
3959
3960 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003961 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3962 if (uidStats == null) {
3963 uidStats = new ArrayMap<String, BroadcastStats>();
3964 mBroadcastStats.put(uid, uidStats);
3965 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003966 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003967 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003968 bs = new BroadcastStats(uid, pkgName);
3969 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003970 }
3971 return bs;
3972 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003973
Christopher Tate21e9f192017-08-08 13:49:11 -07003974 /**
3975 * Canonical count of (operation.send() - onSendFinished()) and
3976 * listener send/complete/timeout invocations.
3977 * Guarded by the usual lock.
3978 */
3979 @GuardedBy("mLock")
3980 private int mSendCount = 0;
3981 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003982 private int mSendFinishCount = 0;
3983 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003984 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003985 @GuardedBy("mLock")
3986 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003987
Christopher Tate14a7bb02015-10-01 10:24:31 -07003988 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003989
Christopher Tate14a7bb02015-10-01 10:24:31 -07003990 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3991 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003992 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003993 return mInFlight.remove(i);
3994 }
3995 }
3996 mLog.w("No in-flight alarm for " + pi + " " + intent);
3997 return null;
3998 }
3999
4000 private InFlight removeLocked(IBinder listener) {
4001 for (int i = 0; i < mInFlight.size(); i++) {
4002 if (mInFlight.get(i).mListener == listener) {
4003 return mInFlight.remove(i);
4004 }
4005 }
4006 mLog.w("No in-flight alarm for listener " + listener);
4007 return null;
4008 }
4009
4010 private void updateStatsLocked(InFlight inflight) {
4011 final long nowELAPSED = SystemClock.elapsedRealtime();
4012 BroadcastStats bs = inflight.mBroadcastStats;
4013 bs.nesting--;
4014 if (bs.nesting <= 0) {
4015 bs.nesting = 0;
4016 bs.aggregateTime += nowELAPSED - bs.startTime;
4017 }
4018 FilterStats fs = inflight.mFilterStats;
4019 fs.nesting--;
4020 if (fs.nesting <= 0) {
4021 fs.nesting = 0;
4022 fs.aggregateTime += nowELAPSED - fs.startTime;
4023 }
4024 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004025 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4026 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004027 }
4028 }
4029
4030 private void updateTrackingLocked(InFlight inflight) {
4031 if (inflight != null) {
4032 updateStatsLocked(inflight);
4033 }
4034 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004035 if (DEBUG_WAKELOCK) {
4036 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4037 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004038 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004039 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004040 mWakeLock.release();
4041 if (mInFlight.size() > 0) {
4042 mLog.w("Finished all dispatches with " + mInFlight.size()
4043 + " remaining inflights");
4044 for (int i=0; i<mInFlight.size(); i++) {
4045 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4046 }
4047 mInFlight.clear();
4048 }
4049 } else {
4050 // the next of our alarms is now in flight. reattribute the wakelock.
4051 if (mInFlight.size() > 0) {
4052 InFlight inFlight = mInFlight.get(0);
4053 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4054 inFlight.mAlarmType, inFlight.mTag, -1, false);
4055 } else {
4056 // should never happen
4057 mLog.w("Alarm wakelock still held but sent queue empty");
4058 mWakeLock.setWorkSource(null);
4059 }
4060 }
4061 }
4062
4063 /**
4064 * Callback that arrives when a direct-call alarm reports that delivery has finished
4065 */
4066 @Override
4067 public void alarmComplete(IBinder who) {
4068 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004069 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004070 + " pid=" + Binder.getCallingPid());
4071 return;
4072 }
4073
4074 final long ident = Binder.clearCallingIdentity();
4075 try {
4076 synchronized (mLock) {
4077 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4078 InFlight inflight = removeLocked(who);
4079 if (inflight != null) {
4080 if (DEBUG_LISTENER_CALLBACK) {
4081 Slog.i(TAG, "alarmComplete() from " + who);
4082 }
4083 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004084 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004085 } else {
4086 // Delivery timed out, and the timeout handling already took care of
4087 // updating our tracking here, so we needn't do anything further.
4088 if (DEBUG_LISTENER_CALLBACK) {
4089 Slog.i(TAG, "Late alarmComplete() from " + who);
4090 }
4091 }
4092 }
4093 } finally {
4094 Binder.restoreCallingIdentity(ident);
4095 }
4096 }
4097
4098 /**
4099 * Callback that arrives when a PendingIntent alarm has finished delivery
4100 */
4101 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004102 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4103 String resultData, Bundle resultExtras) {
4104 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004105 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004106 updateTrackingLocked(removeLocked(pi, intent));
4107 }
4108 }
4109
4110 /**
4111 * Timeout of a direct-call alarm delivery
4112 */
4113 public void alarmTimedOut(IBinder who) {
4114 synchronized (mLock) {
4115 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004116 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004117 // TODO: implement ANR policy for the target
4118 if (DEBUG_LISTENER_CALLBACK) {
4119 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004120 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004121 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004122 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004123 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004124 if (DEBUG_LISTENER_CALLBACK) {
4125 Slog.i(TAG, "Spurious timeout of listener " + who);
4126 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004127 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004128 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004129 }
4130 }
4131
4132 /**
4133 * Deliver an alarm and set up the post-delivery handling appropriately
4134 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004135 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004136 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4137 if (alarm.operation != null) {
4138 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004139 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004140
4141 if (alarm.priorityClass.priority == PRIO_TICK) {
4142 mLastTickIssued = nowELAPSED;
4143 }
4144
Christopher Tate14a7bb02015-10-01 10:24:31 -07004145 try {
4146 alarm.operation.send(getContext(), 0,
4147 mBackgroundIntent.putExtra(
4148 Intent.EXTRA_ALARM_COUNT, alarm.count),
4149 mDeliveryTracker, mHandler, null,
4150 allowWhileIdle ? mIdleOptions : null);
4151 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004152 if (alarm.operation == mTimeTickSender) {
4153 Slog.wtf(TAG, "mTimeTickSender canceled");
4154 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004155 if (alarm.repeatInterval > 0) {
4156 // This IntentSender is no longer valid, but this
4157 // is a repeating alarm, so toss it
4158 removeImpl(alarm.operation);
4159 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004160 // No actual delivery was possible, so the delivery tracker's
4161 // 'finished' callback won't be invoked. We also don't need
4162 // to do any wakelock or stats tracking, so we have nothing
4163 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004164 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004165 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004166 }
4167 } else {
4168 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004169 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004170 try {
4171 if (DEBUG_LISTENER_CALLBACK) {
4172 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4173 + " listener=" + alarm.listener.asBinder());
4174 }
4175 alarm.listener.doAlarm(this);
4176 mHandler.sendMessageDelayed(
4177 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4178 alarm.listener.asBinder()),
4179 mConstants.LISTENER_TIMEOUT);
4180 } catch (Exception e) {
4181 if (DEBUG_LISTENER_CALLBACK) {
4182 Slog.i(TAG, "Alarm undeliverable to listener "
4183 + alarm.listener.asBinder(), e);
4184 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004185 // As in the PendingIntent.CanceledException case, delivery of the
4186 // alarm was not possible, so we have no wakelock or timeout or
4187 // stats management to do. It threw before we posted the delayed
4188 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004189 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004190 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004191 }
4192 }
4193
4194 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004195 if (DEBUG_WAKELOCK) {
4196 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4197 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004198 if (mBroadcastRefCount == 0) {
4199 setWakelockWorkSource(alarm.operation, alarm.workSource,
4200 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4201 true);
4202 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004203 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004204 }
4205 final InFlight inflight = new InFlight(AlarmManagerService.this,
4206 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4207 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4208 mInFlight.add(inflight);
4209 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004210 if (allowWhileIdle) {
4211 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004212 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004213 if ((mAppStateTracker == null)
4214 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004215 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4216 } else {
4217 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4218 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004219 if (RECORD_DEVICE_IDLE_ALARMS) {
4220 IdleDispatchEntry ent = new IdleDispatchEntry();
4221 ent.uid = alarm.uid;
4222 ent.pkg = alarm.packageName;
4223 ent.tag = alarm.statsTag;
4224 ent.op = "DELIVER";
4225 ent.elapsedRealtime = nowELAPSED;
4226 mAllowWhileIdleDispatches.add(ent);
4227 }
4228 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004229 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004230 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4231 UserHandle.getUserId(alarm.creatorUid));
4232 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4233 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004234
4235 final BroadcastStats bs = inflight.mBroadcastStats;
4236 bs.count++;
4237 if (bs.nesting == 0) {
4238 bs.nesting = 1;
4239 bs.startTime = nowELAPSED;
4240 } else {
4241 bs.nesting++;
4242 }
4243 final FilterStats fs = inflight.mFilterStats;
4244 fs.count++;
4245 if (fs.nesting == 0) {
4246 fs.nesting = 1;
4247 fs.startTime = nowELAPSED;
4248 } else {
4249 fs.nesting++;
4250 }
4251 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4252 || alarm.type == RTC_WAKEUP) {
4253 bs.numWakeup++;
4254 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004255 ActivityManager.noteWakeupAlarm(
4256 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4257 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004258 }
4259 }
4260 }
mswest463f4c99d2018-02-01 10:13:10 -08004261
4262 private class ShellCmd extends ShellCommand {
4263
4264 IAlarmManager getBinderService() {
4265 return IAlarmManager.Stub.asInterface(mService);
4266 }
4267
4268 @Override
4269 public int onCommand(String cmd) {
4270 if (cmd == null) {
4271 return handleDefaultCommands(cmd);
4272 }
4273
4274 final PrintWriter pw = getOutPrintWriter();
4275 try {
4276 switch (cmd) {
4277 case "set-time":
4278 final long millis = Long.parseLong(getNextArgRequired());
4279 return (getBinderService().setTime(millis)) ? 0 : -1;
4280 case "set-timezone":
4281 final String tz = getNextArgRequired();
4282 getBinderService().setTimeZone(tz);
4283 return 0;
4284 default:
4285 return handleDefaultCommands(cmd);
4286 }
4287 } catch (Exception e) {
4288 pw.println(e);
4289 }
4290 return -1;
4291 }
4292
4293 @Override
4294 public void onHelp() {
4295 PrintWriter pw = getOutPrintWriter();
4296 pw.println("Alarm manager service (alarm) commands:");
4297 pw.println(" help");
4298 pw.println(" Print this help text.");
4299 pw.println(" set-time TIME");
4300 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4301 pw.println(" since the Epoch.");
4302 pw.println(" set-timezone TZ");
4303 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4304 }
4305 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004306}