blob: 8ce4e64b192555092061cad875c49d3130df2b64 [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 Onukie8edbcf2018-03-02 16:49:29 -08001871 final long nowUPTIME = SystemClock.uptimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001872 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001873
Dianne Hackborna750a632015-06-16 17:18:23 -07001874 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001875 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001876 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001877 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001878 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001879 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001880 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1881 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001882 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001883 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1884 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001885 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1886 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001887
1888 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1889 if (ssm != null) {
1890 pw.println();
1891 pw.print(" RuntimeStarted=");
1892 pw.print(sdf.format(
1893 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1894 if (ssm.isRuntimeRestarted()) {
1895 pw.print(" (Runtime restarted)");
1896 }
1897 pw.println();
1898 pw.print(" Runtime uptime (elapsed): ");
1899 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1900 pw.println();
1901 pw.print(" Runtime uptime (uptime): ");
1902 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1903 pw.println();
1904 }
1905
Dianne Hackbornc3527222015-05-13 14:03:20 -07001906 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001907 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001908 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001909 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1910 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001911 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001912 pw.print(" Max wakeup delay: ");
1913 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1914 pw.println();
1915 pw.print(" Time since last dispatch: ");
1916 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1917 pw.println();
1918 pw.print(" Next non-wakeup delivery time: ");
1919 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1920 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001921
1922 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1923 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001924 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001925 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001926 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001927 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001928 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1929 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001930 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001931 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1932 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001933 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001934 pw.print(" = "); pw.println(mLastWakeup);
1935 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1936 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001937 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001938
John Spurlock604a5ee2015-06-01 12:27:22 -04001939 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001940 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001941 final TreeSet<Integer> users = new TreeSet<>();
1942 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1943 users.add(mNextAlarmClockForUser.keyAt(i));
1944 }
1945 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1946 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1947 }
1948 for (int user : users) {
1949 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1950 final long time = next != null ? next.getTriggerTime() : 0;
1951 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001952 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001953 pw.print(" pendingSend:"); pw.print(pendingSend);
1954 pw.print(" time:"); pw.print(time);
1955 if (time > 0) {
1956 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1957 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1958 }
1959 pw.println();
1960 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001961 if (mAlarmBatches.size() > 0) {
1962 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001963 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001964 pw.println(mAlarmBatches.size());
1965 for (Batch b : mAlarmBatches) {
1966 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001967 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001968 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001970 pw.println();
1971 pw.println(" Pending user blocked background alarms: ");
1972 boolean blocked = false;
1973 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1974 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1975 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1976 blocked = true;
1977 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1978 }
1979 }
1980 if (!blocked) {
1981 pw.println(" none");
1982 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001983
Suprabh Shukla75edab12018-01-29 14:09:06 -08001984 pw.println(" mLastAlarmDeliveredForPackage:");
1985 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1986 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1987 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1988 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1989 pw.println();
1990 }
1991 pw.println();
1992
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001993 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001994 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001995 pw.println(" Idle mode state:");
1996 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001997 if (mPendingIdleUntil != null) {
1998 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001999 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002000 } else {
2001 pw.println("null");
2002 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002003 pw.println(" Pending alarms:");
2004 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002005 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002006 if (mNextWakeFromIdle != null) {
2007 pw.println();
2008 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002009 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002010 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002011
2012 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002013 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002014 if (mPendingNonWakeupAlarms.size() > 0) {
2015 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002016 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002017 } else {
2018 pw.println("(none)");
2019 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002020 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002021 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2022 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002023 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002024 pw.print(", max non-interactive time: ");
2025 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2026 pw.println();
2027
2028 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002029 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002030 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2031 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2032 pw.print(" Listener send count: "); pw.println(mListenerCount);
2033 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002034 pw.println();
2035
Christopher Tate7f2a0352015-12-08 10:24:33 -08002036 if (mInFlight.size() > 0) {
2037 pw.println("Outstanding deliveries:");
2038 for (int i = 0; i < mInFlight.size(); i++) {
2039 pw.print(" #"); pw.print(i); pw.print(": ");
2040 pw.println(mInFlight.get(i));
2041 }
2042 pw.println();
2043 }
2044
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002045 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002046 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002047 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002048 pw.print(" UID ");
2049 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2050 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002051 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002052 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2053 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2054
2055 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2056 pw.print(" Next allowed:");
2057 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2058 pw.print(" (");
2059 TimeUtils.formatDuration(minInterval, 0, pw);
2060 pw.print(")");
2061
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002062 pw.println();
2063 }
2064 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002065
2066 pw.print(" mUseAllowWhileIdleShortTime: [");
2067 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2068 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2069 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2070 pw.print(" ");
2071 }
2072 }
2073 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002074 pw.println();
2075
Dianne Hackborn81038902012-11-26 17:04:09 -08002076 if (mLog.dump(pw, " Recent problems", " ")) {
2077 pw.println();
2078 }
2079
2080 final FilterStats[] topFilters = new FilterStats[10];
2081 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2082 @Override
2083 public int compare(FilterStats lhs, FilterStats rhs) {
2084 if (lhs.aggregateTime < rhs.aggregateTime) {
2085 return 1;
2086 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2087 return -1;
2088 }
2089 return 0;
2090 }
2091 };
2092 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002093 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002094 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2095 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2096 for (int ip=0; ip<uidStats.size(); ip++) {
2097 BroadcastStats bs = uidStats.valueAt(ip);
2098 for (int is=0; is<bs.filterStats.size(); is++) {
2099 FilterStats fs = bs.filterStats.valueAt(is);
2100 int pos = len > 0
2101 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2102 if (pos < 0) {
2103 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002104 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002105 if (pos < topFilters.length) {
2106 int copylen = topFilters.length - pos - 1;
2107 if (copylen > 0) {
2108 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2109 }
2110 topFilters[pos] = fs;
2111 if (len < topFilters.length) {
2112 len++;
2113 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002114 }
2115 }
2116 }
2117 }
2118 if (len > 0) {
2119 pw.println(" Top Alarms:");
2120 for (int i=0; i<len; i++) {
2121 FilterStats fs = topFilters[i];
2122 pw.print(" ");
2123 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2124 TimeUtils.formatDuration(fs.aggregateTime, pw);
2125 pw.print(" running, "); pw.print(fs.numWakeup);
2126 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002127 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2128 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002129 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002130 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002131 pw.println();
2132 }
2133 }
2134
2135 pw.println(" ");
2136 pw.println(" Alarm Stats:");
2137 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002138 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2139 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2140 for (int ip=0; ip<uidStats.size(); ip++) {
2141 BroadcastStats bs = uidStats.valueAt(ip);
2142 pw.print(" ");
2143 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2144 UserHandle.formatUid(pw, bs.mUid);
2145 pw.print(":");
2146 pw.print(bs.mPackageName);
2147 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2148 pw.print(" running, "); pw.print(bs.numWakeup);
2149 pw.println(" wakeups:");
2150 tmpFilters.clear();
2151 for (int is=0; is<bs.filterStats.size(); is++) {
2152 tmpFilters.add(bs.filterStats.valueAt(is));
2153 }
2154 Collections.sort(tmpFilters, comparator);
2155 for (int i=0; i<tmpFilters.size(); i++) {
2156 FilterStats fs = tmpFilters.get(i);
2157 pw.print(" ");
2158 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2159 TimeUtils.formatDuration(fs.aggregateTime, pw);
2160 pw.print(" "); pw.print(fs.numWakeup);
2161 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002162 pw.print(" alarms, last ");
2163 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2164 pw.println(":");
2165 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002166 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002167 pw.println();
2168 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002169 }
2170 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002171 pw.println();
2172 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002173
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002174 if (RECORD_DEVICE_IDLE_ALARMS) {
2175 pw.println();
2176 pw.println(" Allow while idle dispatches:");
2177 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2178 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2179 pw.print(" ");
2180 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2181 pw.print(": ");
2182 UserHandle.formatUid(pw, ent.uid);
2183 pw.print(":");
2184 pw.println(ent.pkg);
2185 if (ent.op != null) {
2186 pw.print(" ");
2187 pw.print(ent.op);
2188 pw.print(" / ");
2189 pw.print(ent.tag);
2190 if (ent.argRealtime != 0) {
2191 pw.print(" (");
2192 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2193 pw.print(")");
2194 }
2195 pw.println();
2196 }
2197 }
2198 }
2199
Christopher Tate18a75f12013-07-01 18:18:59 -07002200 if (WAKEUP_STATS) {
2201 pw.println();
2202 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002203 long last = -1;
2204 for (WakeupEvent event : mRecentWakeups) {
2205 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2206 pw.print('|');
2207 if (last < 0) {
2208 pw.print('0');
2209 } else {
2210 pw.print(event.when - last);
2211 }
2212 last = event.when;
2213 pw.print('|'); pw.print(event.uid);
2214 pw.print('|'); pw.print(event.action);
2215 pw.println();
2216 }
2217 pw.println();
2218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002219 }
2220 }
2221
Kweku Adams61e03292017-10-19 14:27:12 -07002222 void dumpProto(FileDescriptor fd) {
2223 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2224
2225 synchronized (mLock) {
2226 final long nowRTC = System.currentTimeMillis();
2227 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002228 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2229 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2230 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002231 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002232 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002233 mLastTimeChangeRealtime);
2234
Yi Jin2b30f322018-02-20 15:41:47 -08002235 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002236
Makoto Onukie4918212018-02-06 11:30:15 -08002237 if (mAppStateTracker != null) {
2238 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002239 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002240 }
Kweku Adams61e03292017-10-19 14:27:12 -07002241
Yi Jin2b30f322018-02-20 15:41:47 -08002242 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002243 if (!mInteractive) {
2244 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002245 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002246 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002247 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002248 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002249 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002250 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002251 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002252 nowElapsed - mNextNonWakeupDeliveryTime);
2253 }
2254
Yi Jin2b30f322018-02-20 15:41:47 -08002255 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002256 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002257 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002258 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002259 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002260 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002261 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002262 nowElapsed - mLastWakeupSet);
Yi Jin2b30f322018-02-20 15:41:47 -08002263 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002264
2265 final TreeSet<Integer> users = new TreeSet<>();
2266 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2267 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2268 users.add(mNextAlarmClockForUser.keyAt(i));
2269 }
2270 final int pendingSendNextAlarmClockChangedForUserSize =
2271 mPendingSendNextAlarmClockChangedForUser.size();
2272 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2273 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2274 }
2275 for (int user : users) {
2276 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2277 final long time = next != null ? next.getTriggerTime() : 0;
2278 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002279 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002280 proto.write(AlarmClockMetadataProto.USER, user);
2281 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2282 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2283 proto.end(aToken);
2284 }
2285 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002286 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002287 nowElapsed, nowRTC);
2288 }
2289 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2290 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2291 if (blockedAlarms != null) {
2292 for (Alarm a : blockedAlarms) {
2293 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002294 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002295 nowElapsed, nowRTC);
2296 }
2297 }
2298 }
2299 if (mPendingIdleUntil != null) {
2300 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002301 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002302 }
2303 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002304 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002305 nowElapsed, nowRTC);
2306 }
2307 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002308 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002309 nowElapsed, nowRTC);
2310 }
2311
2312 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002313 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002314 nowElapsed, nowRTC);
2315 }
2316
Yi Jin2b30f322018-02-20 15:41:47 -08002317 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2318 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2319 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2320 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002321 mNonInteractiveTime);
2322
Yi Jin2b30f322018-02-20 15:41:47 -08002323 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2324 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2325 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2326 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2327 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002328
2329 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002330 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002331 }
2332
Kweku Adams61e03292017-10-19 14:27:12 -07002333 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2334 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002335 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002336 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2337 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2338
Yi Jin2b30f322018-02-20 15:41:47 -08002339 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2340 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2341 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002342 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002343 proto.end(token);
2344 }
2345
Makoto Onukiadb50d82018-01-29 16:20:30 -08002346 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2347 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002348 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002349 mUseAllowWhileIdleShortTime.keyAt(i));
2350 }
2351 }
2352
Yi Jin2b30f322018-02-20 15:41:47 -08002353 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002354
2355 final FilterStats[] topFilters = new FilterStats[10];
2356 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2357 @Override
2358 public int compare(FilterStats lhs, FilterStats rhs) {
2359 if (lhs.aggregateTime < rhs.aggregateTime) {
2360 return 1;
2361 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2362 return -1;
2363 }
2364 return 0;
2365 }
2366 };
2367 int len = 0;
2368 // Get the top 10 FilterStats, ordered by aggregateTime.
2369 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2370 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2371 for (int ip = 0; ip < uidStats.size(); ++ip) {
2372 BroadcastStats bs = uidStats.valueAt(ip);
2373 for (int is = 0; is < bs.filterStats.size(); ++is) {
2374 FilterStats fs = bs.filterStats.valueAt(is);
2375 int pos = len > 0
2376 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2377 if (pos < 0) {
2378 pos = -pos - 1;
2379 }
2380 if (pos < topFilters.length) {
2381 int copylen = topFilters.length - pos - 1;
2382 if (copylen > 0) {
2383 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2384 }
2385 topFilters[pos] = fs;
2386 if (len < topFilters.length) {
2387 len++;
2388 }
2389 }
2390 }
2391 }
2392 }
2393 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002394 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002395 FilterStats fs = topFilters[i];
2396
Yi Jin2b30f322018-02-20 15:41:47 -08002397 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2398 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002399 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002400 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002401
2402 proto.end(token);
2403 }
2404
2405 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2406 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2407 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2408 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002409 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002410
2411 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002412 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002413
2414 // uidStats is an ArrayMap, which we can't sort.
2415 tmpFilters.clear();
2416 for (int is = 0; is < bs.filterStats.size(); ++is) {
2417 tmpFilters.add(bs.filterStats.valueAt(is));
2418 }
2419 Collections.sort(tmpFilters, comparator);
2420 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002421 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002422 }
2423
2424 proto.end(token);
2425 }
2426 }
2427
2428 if (RECORD_DEVICE_IDLE_ALARMS) {
2429 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2430 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2431 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002432 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002433
2434 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2435 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2436 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2437 proto.write(IdleDispatchEntryProto.OP, ent.op);
2438 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2439 ent.elapsedRealtime);
2440 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2441
2442 proto.end(token);
2443 }
2444 }
2445
2446 if (WAKEUP_STATS) {
2447 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002448 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002449 proto.write(WakeupEventProto.UID, event.uid);
2450 proto.write(WakeupEventProto.ACTION, event.action);
2451 proto.write(WakeupEventProto.WHEN, event.when);
2452 proto.end(token);
2453 }
2454 }
2455 }
2456
2457 proto.flush();
2458 }
2459
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002460 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002461 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2462 PrintWriter pw = new PrintWriter(bs);
2463 final long nowRTC = System.currentTimeMillis();
2464 final long nowELAPSED = SystemClock.elapsedRealtime();
2465 final int NZ = mAlarmBatches.size();
2466 for (int iz = 0; iz < NZ; iz++) {
2467 Batch bz = mAlarmBatches.get(iz);
2468 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002469 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002470 pw.flush();
2471 Slog.v(TAG, bs.toString());
2472 bs.reset();
2473 }
2474 }
2475
2476 private boolean validateConsistencyLocked() {
2477 if (DEBUG_VALIDATE) {
2478 long lastTime = Long.MIN_VALUE;
2479 final int N = mAlarmBatches.size();
2480 for (int i = 0; i < N; i++) {
2481 Batch b = mAlarmBatches.get(i);
2482 if (b.start >= lastTime) {
2483 // duplicate start times are okay because of standalone batches
2484 lastTime = b.start;
2485 } else {
2486 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002487 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2488 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002489 return false;
2490 }
2491 }
2492 }
2493 return true;
2494 }
2495
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002496 private Batch findFirstWakeupBatchLocked() {
2497 final int N = mAlarmBatches.size();
2498 for (int i = 0; i < N; i++) {
2499 Batch b = mAlarmBatches.get(i);
2500 if (b.hasWakeups()) {
2501 return b;
2502 }
2503 }
2504 return null;
2505 }
2506
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002507 long getNextWakeFromIdleTimeImpl() {
2508 synchronized (mLock) {
2509 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2510 }
2511 }
2512
2513 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002514 synchronized (mLock) {
2515 return mNextAlarmClockForUser.get(userId);
2516 }
2517 }
2518
2519 /**
2520 * Recomputes the next alarm clock for all users.
2521 */
2522 private void updateNextAlarmClockLocked() {
2523 if (!mNextAlarmClockMayChange) {
2524 return;
2525 }
2526 mNextAlarmClockMayChange = false;
2527
Jose Lima235510e2014-08-13 12:50:01 -07002528 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002529 nextForUser.clear();
2530
2531 final int N = mAlarmBatches.size();
2532 for (int i = 0; i < N; i++) {
2533 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2534 final int M = alarms.size();
2535
2536 for (int j = 0; j < M; j++) {
2537 Alarm a = alarms.get(j);
2538 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002539 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002540 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002541
2542 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002543 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002544 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002545 " for user " + userId);
2546 }
2547
2548 // Alarms and batches are sorted by time, no need to compare times here.
2549 if (nextForUser.get(userId) == null) {
2550 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002551 } else if (a.alarmClock.equals(current)
2552 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2553 // same/earlier time and it's the one we cited before, so stick with it
2554 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002555 }
2556 }
2557 }
2558 }
2559
2560 // Update mNextAlarmForUser with new values.
2561 final int NN = nextForUser.size();
2562 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002563 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002564 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002565 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002566 if (!newAlarm.equals(currentAlarm)) {
2567 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2568 }
2569 }
2570
2571 // Remove users without any alarm clocks scheduled.
2572 final int NNN = mNextAlarmClockForUser.size();
2573 for (int i = NNN - 1; i >= 0; i--) {
2574 int userId = mNextAlarmClockForUser.keyAt(i);
2575 if (nextForUser.get(userId) == null) {
2576 updateNextAlarmInfoForUserLocked(userId, null);
2577 }
2578 }
2579 }
2580
Jose Lima235510e2014-08-13 12:50:01 -07002581 private void updateNextAlarmInfoForUserLocked(int userId,
2582 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002583 if (alarmClock != null) {
2584 if (DEBUG_ALARM_CLOCK) {
2585 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002586 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002587 }
2588 mNextAlarmClockForUser.put(userId, alarmClock);
2589 } else {
2590 if (DEBUG_ALARM_CLOCK) {
2591 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2592 }
2593 mNextAlarmClockForUser.remove(userId);
2594 }
2595
2596 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2597 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2598 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2599 }
2600
2601 /**
2602 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2603 * for which alarm clocks have changed since the last call to this.
2604 *
2605 * Do not call with a lock held. Only call from mHandler's thread.
2606 *
2607 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2608 */
2609 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002610 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002611 pendingUsers.clear();
2612
2613 synchronized (mLock) {
2614 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2615 for (int i = 0; i < N; i++) {
2616 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2617 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2618 }
2619 mPendingSendNextAlarmClockChangedForUser.clear();
2620 }
2621
2622 final int N = pendingUsers.size();
2623 for (int i = 0; i < N; i++) {
2624 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002625 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002626 Settings.System.putStringForUser(getContext().getContentResolver(),
2627 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002628 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002629 userId);
2630
2631 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2632 new UserHandle(userId));
2633 }
2634 }
2635
2636 /**
2637 * Formats an alarm like platform/packages/apps/DeskClock used to.
2638 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002639 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2640 int userId) {
2641 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002642 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2643 return (info == null) ? "" :
2644 DateFormat.format(pattern, info.getTriggerTime()).toString();
2645 }
2646
Adam Lesinski182f73f2013-12-05 16:48:06 -08002647 void rescheduleKernelAlarmsLocked() {
2648 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2649 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002650 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002651 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002652 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002653 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002654 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002655 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002656 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002657 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002658 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002659 if (firstBatch != firstWakeup) {
2660 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002661 }
2662 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002663 if (mPendingNonWakeupAlarms.size() > 0) {
2664 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2665 nextNonWakeup = mNextNonWakeupDeliveryTime;
2666 }
2667 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002668 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002669 mNextNonWakeup = nextNonWakeup;
2670 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2671 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002672 }
2673
Christopher Tate14a7bb02015-10-01 10:24:31 -07002674 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002675 if (operation == null && directReceiver == null) {
2676 if (localLOGV) {
2677 Slog.w(TAG, "requested remove() of null operation",
2678 new RuntimeException("here"));
2679 }
2680 return;
2681 }
2682
Adam Lesinski182f73f2013-12-05 16:48:06 -08002683 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002684 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002685 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2686 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002687 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002688 if (b.size() == 0) {
2689 mAlarmBatches.remove(i);
2690 }
2691 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002692 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002693 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002694 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2695 mPendingWhileIdleAlarms.remove(i);
2696 }
2697 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002698 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2699 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2700 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2701 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2702 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2703 alarmsForUid.remove(j);
2704 }
2705 }
2706 if (alarmsForUid.size() == 0) {
2707 mPendingBackgroundAlarms.removeAt(i);
2708 }
2709 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002710 if (didRemove) {
2711 if (DEBUG_BATCH) {
2712 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2713 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002714 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002715 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002716 mPendingIdleUntil = null;
2717 restorePending = true;
2718 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002719 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002720 mNextWakeFromIdle = null;
2721 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002722 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002723 if (restorePending) {
2724 restorePendingWhileIdleAlarmsLocked();
2725 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002726 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002727 }
2728 }
2729
Christopher Tate1d99c392017-12-07 16:54:04 -08002730 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002731 if (uid == Process.SYSTEM_UID) {
2732 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2733 return;
2734 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002735 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002736 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002737 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2738 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002739 didRemove |= b.remove(whichAlarms);
2740 if (b.size() == 0) {
2741 mAlarmBatches.remove(i);
2742 }
2743 }
2744 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2745 final Alarm a = mPendingWhileIdleAlarms.get(i);
2746 if (a.uid == uid) {
2747 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2748 mPendingWhileIdleAlarms.remove(i);
2749 }
2750 }
2751 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2752 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2753 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2754 if (alarmsForUid.get(j).uid == uid) {
2755 alarmsForUid.remove(j);
2756 }
2757 }
2758 if (alarmsForUid.size() == 0) {
2759 mPendingBackgroundAlarms.removeAt(i);
2760 }
2761 }
2762 if (didRemove) {
2763 if (DEBUG_BATCH) {
2764 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2765 }
2766 rebatchAllAlarmsLocked(true);
2767 rescheduleKernelAlarmsLocked();
2768 updateNextAlarmClockLocked();
2769 }
2770 }
2771
2772 void removeLocked(final String packageName) {
2773 if (packageName == null) {
2774 if (localLOGV) {
2775 Slog.w(TAG, "requested remove() of null packageName",
2776 new RuntimeException("here"));
2777 }
2778 return;
2779 }
2780
2781 boolean didRemove = false;
2782 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002783 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002784 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2785 Batch b = mAlarmBatches.get(i);
2786 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002787 if (b.size() == 0) {
2788 mAlarmBatches.remove(i);
2789 }
2790 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002791 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2792 if (oldHasTick != newHasTick) {
2793 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2794 }
2795
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002796 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002797 final Alarm a = mPendingWhileIdleAlarms.get(i);
2798 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002799 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2800 mPendingWhileIdleAlarms.remove(i);
2801 }
2802 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002803 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2804 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2805 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2806 if (alarmsForUid.get(j).matches(packageName)) {
2807 alarmsForUid.remove(j);
2808 }
2809 }
2810 if (alarmsForUid.size() == 0) {
2811 mPendingBackgroundAlarms.removeAt(i);
2812 }
2813 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002814 if (didRemove) {
2815 if (DEBUG_BATCH) {
2816 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2817 }
2818 rebatchAllAlarmsLocked(true);
2819 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002820 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002821 }
2822 }
2823
Christopher Tate1d99c392017-12-07 16:54:04 -08002824 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002825 if (uid == Process.SYSTEM_UID) {
2826 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2827 return;
2828 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002829 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002830 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2831 try {
2832 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2833 uid, a.packageName)) {
2834 return true;
2835 }
2836 } catch (RemoteException e) { /* fall through */}
2837 return false;
2838 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002839 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2840 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002841 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002842 if (b.size() == 0) {
2843 mAlarmBatches.remove(i);
2844 }
2845 }
2846 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2847 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002848 if (a.uid == uid) {
2849 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2850 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002851 }
2852 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002853 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2854 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2855 mPendingBackgroundAlarms.removeAt(i);
2856 }
2857 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002858 if (didRemove) {
2859 if (DEBUG_BATCH) {
2860 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2861 }
2862 rebatchAllAlarmsLocked(true);
2863 rescheduleKernelAlarmsLocked();
2864 updateNextAlarmClockLocked();
2865 }
2866 }
2867
Adam Lesinski182f73f2013-12-05 16:48:06 -08002868 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002869 if (userHandle == UserHandle.USER_SYSTEM) {
2870 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2871 return;
2872 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002873 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002874 final Predicate<Alarm> whichAlarms =
2875 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002876 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2877 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002878 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002879 if (b.size() == 0) {
2880 mAlarmBatches.remove(i);
2881 }
2882 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002883 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002884 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002885 == userHandle) {
2886 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2887 mPendingWhileIdleAlarms.remove(i);
2888 }
2889 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002890 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2891 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2892 mPendingBackgroundAlarms.removeAt(i);
2893 }
2894 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002895 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2896 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2897 mLastAllowWhileIdleDispatch.removeAt(i);
2898 }
2899 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002900
2901 if (didRemove) {
2902 if (DEBUG_BATCH) {
2903 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2904 }
2905 rebatchAllAlarmsLocked(true);
2906 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002907 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002908 }
2909 }
2910
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002911 void interactiveStateChangedLocked(boolean interactive) {
2912 if (mInteractive != interactive) {
2913 mInteractive = interactive;
2914 final long nowELAPSED = SystemClock.elapsedRealtime();
2915 if (interactive) {
2916 if (mPendingNonWakeupAlarms.size() > 0) {
2917 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2918 mTotalDelayTime += thisDelayTime;
2919 if (mMaxDelayTime < thisDelayTime) {
2920 mMaxDelayTime = thisDelayTime;
2921 }
2922 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2923 mPendingNonWakeupAlarms.clear();
2924 }
2925 if (mNonInteractiveStartTime > 0) {
2926 long dur = nowELAPSED - mNonInteractiveStartTime;
2927 if (dur > mNonInteractiveTime) {
2928 mNonInteractiveTime = dur;
2929 }
2930 }
2931 } else {
2932 mNonInteractiveStartTime = nowELAPSED;
2933 }
2934 }
2935 }
2936
Adam Lesinski182f73f2013-12-05 16:48:06 -08002937 boolean lookForPackageLocked(String packageName) {
2938 for (int i = 0; i < mAlarmBatches.size(); i++) {
2939 Batch b = mAlarmBatches.get(i);
2940 if (b.hasPackage(packageName)) {
2941 return true;
2942 }
2943 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002944 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002945 final Alarm a = mPendingWhileIdleAlarms.get(i);
2946 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002947 return true;
2948 }
2949 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002950 return false;
2951 }
2952
2953 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002954 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002955 // The kernel never triggers alarms with negative wakeup times
2956 // so we ensure they are positive.
2957 long alarmSeconds, alarmNanoseconds;
2958 if (when < 0) {
2959 alarmSeconds = 0;
2960 alarmNanoseconds = 0;
2961 } else {
2962 alarmSeconds = when / 1000;
2963 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2964 }
Kweku Adams61e03292017-10-19 14:27:12 -07002965
Christopher Tate8b98ade2018-02-09 11:13:19 -08002966 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2967 if (result != 0) {
2968 final long nowElapsed = SystemClock.elapsedRealtime();
2969 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2970 + " type=" + type + " when=" + when
2971 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2972 + "), ret = " + result + " = " + Os.strerror(result));
2973 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002974 } else {
2975 Message msg = Message.obtain();
2976 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002977
Adam Lesinski182f73f2013-12-05 16:48:06 -08002978 mHandler.removeMessages(ALARM_EVENT);
2979 mHandler.sendMessageAtTime(msg, when);
2980 }
2981 }
2982
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002983 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002984 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002985 for (int i=list.size()-1; i>=0; i--) {
2986 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002987 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2988 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002989 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002990 }
2991 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002992
2993 private static final String labelForType(int type) {
2994 switch (type) {
2995 case RTC: return "RTC";
2996 case RTC_WAKEUP : return "RTC_WAKEUP";
2997 case ELAPSED_REALTIME : return "ELAPSED";
2998 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002999 }
3000 return "--unknown--";
3001 }
3002
3003 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003004 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003005 for (int i=list.size()-1; i>=0; i--) {
3006 Alarm a = list.get(i);
3007 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003008 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3009 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003010 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003011 }
3012 }
3013
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003014 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003015 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003016 if (alarm.alarmClock != null) {
3017 // Don't block alarm clocks
3018 return false;
3019 }
3020 if (alarm.operation != null
3021 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
3022 // Don't block starting foreground components
3023 return false;
3024 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003025 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003026 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003027 return (mAppStateTracker != null) &&
3028 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage, allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003029 }
3030
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003031 private native long init();
3032 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003033 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003034 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003035 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003036 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003037
Makoto Onukiadb50d82018-01-29 16:20:30 -08003038 private long getWhileIdleMinIntervalLocked(int uid) {
3039 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003040 final boolean ebs = (mAppStateTracker != null)
3041 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003042 if (!dozing && !ebs) {
3043 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3044 }
3045 if (dozing) {
3046 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3047 }
3048 if (mUseAllowWhileIdleShortTime.get(uid)) {
3049 // if the last allow-while-idle went off while uid was fg, or the uid
3050 // recently came into fg, don't block the alarm for long.
3051 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3052 }
3053 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3054 }
3055
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003056 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003057 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003058 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003059 // batches are temporally sorted, so we need only pull from the
3060 // start of the list until we either empty it or hit a batch
3061 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003062 while (mAlarmBatches.size() > 0) {
3063 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003064 if (batch.start > nowELAPSED) {
3065 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003066 break;
3067 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068
Christopher Tatee0a22b32013-07-11 14:43:13 -07003069 // We will (re)schedule some alarms now; don't let that interfere
3070 // with delivery of this current batch
3071 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003072
Christopher Tatee0a22b32013-07-11 14:43:13 -07003073 final int N = batch.size();
3074 for (int i = 0; i < N; i++) {
3075 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003076
3077 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3078 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
3079 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003080 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003081 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003082 if (nowELAPSED < minTime) {
3083 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3084 // alarm went off for this app. Reschedule the alarm to be in the
3085 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003086 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003087 if (alarm.maxWhenElapsed < minTime) {
3088 alarm.maxWhenElapsed = minTime;
3089 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003090 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003091 if (RECORD_DEVICE_IDLE_ALARMS) {
3092 IdleDispatchEntry ent = new IdleDispatchEntry();
3093 ent.uid = alarm.uid;
3094 ent.pkg = alarm.operation.getCreatorPackage();
3095 ent.tag = alarm.operation.getTag("");
3096 ent.op = "RESCHEDULE";
3097 ent.elapsedRealtime = nowELAPSED;
3098 ent.argRealtime = lastTime;
3099 mAllowWhileIdleDispatches.add(ent);
3100 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003101 setImplLocked(alarm, true, false);
3102 continue;
3103 }
3104 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003105 if (isBackgroundRestricted(alarm)) {
3106 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3107 if (DEBUG_BG_LIMIT) {
3108 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3109 }
3110 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3111 if (alarmsForUid == null) {
3112 alarmsForUid = new ArrayList<>();
3113 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3114 }
3115 alarmsForUid.add(alarm);
3116 continue;
3117 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003118
Christopher Tatee0a22b32013-07-11 14:43:13 -07003119 alarm.count = 1;
3120 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003121 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3122 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003123 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003124 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003125 if (mPendingIdleUntil == alarm) {
3126 mPendingIdleUntil = null;
3127 rebatchAllAlarmsLocked(false);
3128 restorePendingWhileIdleAlarmsLocked();
3129 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003130 if (mNextWakeFromIdle == alarm) {
3131 mNextWakeFromIdle = null;
3132 rebatchAllAlarmsLocked(false);
3133 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003134
3135 // Recurring alarms may have passed several alarm intervals while the
3136 // phone was asleep or off, so pass a trigger count when sending them.
3137 if (alarm.repeatInterval > 0) {
3138 // this adjustment will be zero if we're late by
3139 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003140 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003141
3142 // Also schedule its next recurrence
3143 final long delta = alarm.count * alarm.repeatInterval;
3144 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003145 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003146 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003147 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3148 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003149 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003150
Christopher Tate864d42e2014-12-02 11:48:53 -08003151 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003152 hasWakeup = true;
3153 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003154
3155 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3156 if (alarm.alarmClock != null) {
3157 mNextAlarmClockMayChange = true;
3158 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003160 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003161
Christopher Tate1590f1e2014-10-02 17:27:57 -07003162 // This is a new alarm delivery set; bump the sequence number to indicate that
3163 // all apps' alarm delivery classes should be recalculated.
3164 mCurrentSeq++;
3165 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003166 Collections.sort(triggerList, mAlarmDispatchComparator);
3167
3168 if (localLOGV) {
3169 for (int i=0; i<triggerList.size(); i++) {
3170 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3171 }
3172 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003173
3174 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003176
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003177 /**
3178 * This Comparator sorts Alarms into increasing time order.
3179 */
3180 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3181 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003182 long when1 = a1.whenElapsed;
3183 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003184 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003185 return 1;
3186 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003187 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003188 return -1;
3189 }
3190 return 0;
3191 }
3192 }
Kweku Adams61e03292017-10-19 14:27:12 -07003193
Makoto Onuki2206af32017-11-21 16:25:35 -08003194 @VisibleForTesting
3195 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003196 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003197 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003198 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003199 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003200 public final IAlarmListener listener;
3201 public final String listenerTag;
3202 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003203 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003204 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003205 public final AlarmManager.AlarmClockInfo alarmClock;
3206 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003207 public final int creatorUid;
3208 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003209 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 public int count;
3211 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003212 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003213 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003214 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003215 // Expected alarm expiry time before app standby deferring is applied.
3216 public long expectedWhenElapsed;
3217 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003218 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003219 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003220
Christopher Tate3e04b472013-10-21 17:51:31 -07003221 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003222 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3223 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3224 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003225 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003226 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003227 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3228 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003229 when = _when;
3230 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003231 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003232 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003233 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003234 repeatInterval = _interval;
3235 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003236 listener = _rec;
3237 listenerTag = _listenerTag;
3238 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003239 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003240 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003241 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003242 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003243 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003244 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003245 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003246 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003247
Christopher Tate14a7bb02015-10-01 10:24:31 -07003248 public static String makeTag(PendingIntent pi, String tag, int type) {
3249 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3250 ? "*walarm*:" : "*alarm*:";
3251 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3252 }
3253
3254 public WakeupEvent makeWakeupEvent(long nowRTC) {
3255 return new WakeupEvent(nowRTC, creatorUid,
3256 (operation != null)
3257 ? operation.getIntent().getAction()
3258 : ("<listener>:" + listenerTag));
3259 }
3260
3261 // Returns true if either matches
3262 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3263 return (operation != null)
3264 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003265 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003266 }
3267
3268 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003269 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003270 }
3271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003273 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003274 StringBuilder sb = new StringBuilder(128);
3275 sb.append("Alarm{");
3276 sb.append(Integer.toHexString(System.identityHashCode(this)));
3277 sb.append(" type ");
3278 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003279 sb.append(" when ");
3280 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003281 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003282 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003283 sb.append('}');
3284 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003285 }
3286
Kweku Adams61e03292017-10-19 14:27:12 -07003287 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003288 SimpleDateFormat sdf) {
3289 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003290 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003291 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003292 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3293 expectedWhenElapsed, nowELAPSED, pw);
3294 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3295 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003296 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3297 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003298 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3299 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003300 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003301 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003302 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003303 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003304 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003305 }
3306 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003307 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003308 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003309 pw.print(" count="); pw.print(count);
3310 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003311 if (alarmClock != null) {
3312 pw.print(prefix); pw.println("Alarm clock:");
3313 pw.print(prefix); pw.print(" triggerTime=");
3314 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3315 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3316 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003317 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003318 if (listener != null) {
3319 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3320 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003321 }
Kweku Adams61e03292017-10-19 14:27:12 -07003322
3323 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3324 long nowRTC) {
3325 final long token = proto.start(fieldId);
3326
3327 proto.write(AlarmProto.TAG, statsTag);
3328 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003329 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003330 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3331 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3332 proto.write(AlarmProto.COUNT, count);
3333 proto.write(AlarmProto.FLAGS, flags);
3334 if (alarmClock != null) {
3335 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3336 }
3337 if (operation != null) {
3338 operation.writeToProto(proto, AlarmProto.OPERATION);
3339 }
3340 if (listener != null) {
3341 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3342 }
3343
3344 proto.end(token);
3345 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003347
Christopher Tatee0a22b32013-07-11 14:43:13 -07003348 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3349 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003350 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3351 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003352 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003353 break;
3354 }
3355
Christopher Tatee0a22b32013-07-11 14:43:13 -07003356 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003357 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3358 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003359 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003360 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003361 }
3362 }
3363
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003364 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3365 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3366 if (timeSinceOn < 5*60*1000) {
3367 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3368 return 2*60*1000;
3369 } else if (timeSinceOn < 30*60*1000) {
3370 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3371 return 15*60*1000;
3372 } else {
3373 // Otherwise, we will delay by at most an hour.
3374 return 60*60*1000;
3375 }
3376 }
3377
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003378 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003379 if (duration < 15*60*1000) {
3380 // If the duration until the time is less than 15 minutes, the maximum fuzz
3381 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003382 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003383 } else if (duration < 90*60*1000) {
3384 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3385 return 15*60*1000;
3386 } else {
3387 // Otherwise, we will fuzz by at most half an hour.
3388 return 30*60*1000;
3389 }
3390 }
3391
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003392 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3393 if (mInteractive) {
3394 return false;
3395 }
3396 if (mLastAlarmDeliveryTime <= 0) {
3397 return false;
3398 }
minho.choo649acab2014-12-12 16:13:55 +09003399 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003400 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3401 // and the next delivery time is in the past, then just deliver them all. This
3402 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3403 return false;
3404 }
3405 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3406 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3407 }
3408
3409 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3410 mLastAlarmDeliveryTime = nowELAPSED;
3411 for (int i=0; i<triggerList.size(); i++) {
3412 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003413 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003414 if (alarm.wakeup) {
3415 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3416 } else {
3417 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3418 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003419 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003420 if (localLOGV) {
3421 Slog.v(TAG, "sending alarm " + alarm);
3422 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003423 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003424 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3425 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003426 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003427 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003428 } catch (RuntimeException e) {
3429 Slog.w(TAG, "Failure sending alarm.", e);
3430 }
Tim Murray175c0f92017-11-28 15:01:04 -08003431 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003432 }
3433 }
3434
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003435 private boolean isExemptFromAppStandby(Alarm a) {
3436 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3437 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3438 }
3439
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003440 private class AlarmThread extends Thread
3441 {
3442 public AlarmThread()
3443 {
3444 super("AlarmManager");
3445 }
Kweku Adams61e03292017-10-19 14:27:12 -07003446
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003447 public void run()
3448 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003449 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3450
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003451 while (true)
3452 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003453 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003454
Dianne Hackbornc3527222015-05-13 14:03:20 -07003455 final long nowRTC = System.currentTimeMillis();
3456 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003457 synchronized (mLock) {
3458 mLastWakeup = nowELAPSED;
3459 }
3460
3461 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003462
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003463 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003464 // The kernel can give us spurious time change notifications due to
3465 // small adjustments it makes internally; we want to filter those out.
3466 final long lastTimeChangeClockTime;
3467 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003468 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003469 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3470 expectedClockTime = lastTimeChangeClockTime
3471 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003472 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003473 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3474 || nowRTC > (expectedClockTime+1000)) {
3475 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003476 // let's do it!
3477 if (DEBUG_BATCH) {
3478 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3479 }
3480 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003481 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003482 rebatchAllAlarms();
3483 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003484 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003485 synchronized (mLock) {
3486 mNumTimeChanged++;
3487 mLastTimeChangeClockTime = nowRTC;
3488 mLastTimeChangeRealtime = nowELAPSED;
3489 }
3490 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3491 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003492 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003493 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3494 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003495 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3496
3497 // The world has changed on us, so we need to re-evaluate alarms
3498 // regardless of whether the kernel has told us one went off.
3499 result |= IS_WAKEUP_MASK;
3500 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003501 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003502
Dianne Hackbornc3527222015-05-13 14:03:20 -07003503 if (result != TIME_CHANGED_MASK) {
3504 // If this was anything besides just a time change, then figure what if
3505 // anything to do about alarms.
3506 synchronized (mLock) {
3507 if (localLOGV) Slog.v(
3508 TAG, "Checking for alarms... rtc=" + nowRTC
3509 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003510
Dianne Hackbornc3527222015-05-13 14:03:20 -07003511 if (WAKEUP_STATS) {
3512 if ((result & IS_WAKEUP_MASK) != 0) {
3513 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3514 int n = 0;
3515 for (WakeupEvent event : mRecentWakeups) {
3516 if (event.when > newEarliest) break;
3517 n++; // number of now-stale entries at the list head
3518 }
3519 for (int i = 0; i < n; i++) {
3520 mRecentWakeups.remove();
3521 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003522
Dianne Hackbornc3527222015-05-13 14:03:20 -07003523 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003524 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003525 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003526
Christopher Tate8b98ade2018-02-09 11:13:19 -08003527 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003528 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3529 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3530 // if there are no wakeup alarms and the screen is off, we can
3531 // delay what we have so far until the future.
3532 if (mPendingNonWakeupAlarms.size() == 0) {
3533 mStartCurrentDelayTime = nowELAPSED;
3534 mNextNonWakeupDeliveryTime = nowELAPSED
3535 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3536 }
3537 mPendingNonWakeupAlarms.addAll(triggerList);
3538 mNumDelayedAlarms += triggerList.size();
3539 rescheduleKernelAlarmsLocked();
3540 updateNextAlarmClockLocked();
3541 } else {
3542 // now deliver the alarm intents; if there are pending non-wakeup
3543 // alarms, we need to merge them in to the list. note we don't
3544 // just deliver them first because we generally want non-wakeup
3545 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003546 if (mPendingNonWakeupAlarms.size() > 0) {
3547 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3548 triggerList.addAll(mPendingNonWakeupAlarms);
3549 Collections.sort(triggerList, mAlarmDispatchComparator);
3550 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3551 mTotalDelayTime += thisDelayTime;
3552 if (mMaxDelayTime < thisDelayTime) {
3553 mMaxDelayTime = thisDelayTime;
3554 }
3555 mPendingNonWakeupAlarms.clear();
3556 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003557 final ArraySet<Pair<String, Integer>> triggerPackages =
3558 new ArraySet<>();
3559 for (int i = 0; i < triggerList.size(); i++) {
3560 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003561 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003562 triggerPackages.add(Pair.create(
3563 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003564 }
3565 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003566 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003567 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3568 rescheduleKernelAlarmsLocked();
3569 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003570 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003571 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003572
3573 } else {
3574 // Just in case -- even though no wakeup flag was set, make sure
3575 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003576 synchronized (mLock) {
3577 rescheduleKernelAlarmsLocked();
3578 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003579 }
3580 }
3581 }
3582 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003583
David Christieebe51fc2013-07-26 13:23:29 -07003584 /**
3585 * Attribute blame for a WakeLock.
3586 * @param pi PendingIntent to attribute blame to if ws is null.
3587 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003588 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003589 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003590 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003591 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003592 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003593 final boolean unimportant = pi == mTimeTickSender;
3594 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003595 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003596 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003597 } else {
3598 mWakeLock.setHistoryTag(null);
3599 }
3600 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003601 if (ws != null) {
3602 mWakeLock.setWorkSource(ws);
3603 return;
3604 }
3605
Christopher Tate14a7bb02015-10-01 10:24:31 -07003606 final int uid = (knownUid >= 0)
3607 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003608 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003609 if (uid >= 0) {
3610 mWakeLock.setWorkSource(new WorkSource(uid));
3611 return;
3612 }
3613 } catch (Exception e) {
3614 }
3615
3616 // Something went wrong; fall back to attributing the lock to the OS
3617 mWakeLock.setWorkSource(null);
3618 }
3619
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003620 private class AlarmHandler extends Handler {
3621 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003622 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3623 public static final int LISTENER_TIMEOUT = 3;
3624 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003625 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3626 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003627 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003628
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003629 public AlarmHandler() {
3630 }
Kweku Adams61e03292017-10-19 14:27:12 -07003631
Makoto Onuki4d298b52018-02-05 10:54:58 -08003632 public void postRemoveForStopped(int uid) {
3633 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3634 }
3635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003636 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003637 switch (msg.what) {
3638 case ALARM_EVENT: {
3639 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3640 synchronized (mLock) {
3641 final long nowRTC = System.currentTimeMillis();
3642 final long nowELAPSED = SystemClock.elapsedRealtime();
3643 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3644 updateNextAlarmClockLocked();
3645 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003646
Christopher Tate14a7bb02015-10-01 10:24:31 -07003647 // now trigger the alarms without the lock held
3648 for (int i=0; i<triggerList.size(); i++) {
3649 Alarm alarm = triggerList.get(i);
3650 try {
3651 alarm.operation.send();
3652 } catch (PendingIntent.CanceledException e) {
3653 if (alarm.repeatInterval > 0) {
3654 // This IntentSender is no longer valid, but this
3655 // is a repeating alarm, so toss the hoser.
3656 removeImpl(alarm.operation);
3657 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 }
3659 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003660 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003661 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003662
3663 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3664 sendNextAlarmClockChanged();
3665 break;
3666
3667 case LISTENER_TIMEOUT:
3668 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3669 break;
3670
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003671 case REPORT_ALARMS_ACTIVE:
3672 if (mLocalDeviceIdleController != null) {
3673 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3674 }
3675 break;
3676
Suprabh Shukla75edab12018-01-29 14:09:06 -08003677 case APP_STANDBY_PAROLE_CHANGED:
3678 synchronized (mLock) {
3679 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003680 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3681 rescheduleKernelAlarmsLocked();
3682 updateNextAlarmClockLocked();
3683 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003684 }
3685 break;
3686
3687 case APP_STANDBY_BUCKET_CHANGED:
3688 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003689 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3690 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3691 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3692 rescheduleKernelAlarmsLocked();
3693 updateNextAlarmClockLocked();
3694 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003695 }
3696 break;
3697
Makoto Onuki4d298b52018-02-05 10:54:58 -08003698 case REMOVE_FOR_STOPPED:
3699 synchronized (mLock) {
3700 removeForStoppedLocked(msg.arg1);
3701 }
3702 break;
3703
Christopher Tate14a7bb02015-10-01 10:24:31 -07003704 default:
3705 // nope, just ignore it
3706 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
3708 }
3709 }
Kweku Adams61e03292017-10-19 14:27:12 -07003710
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003711 class ClockReceiver extends BroadcastReceiver {
3712 public ClockReceiver() {
3713 IntentFilter filter = new IntentFilter();
3714 filter.addAction(Intent.ACTION_TIME_TICK);
3715 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003716 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003717 }
Kweku Adams61e03292017-10-19 14:27:12 -07003718
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003719 @Override
3720 public void onReceive(Context context, Intent intent) {
3721 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003722 if (DEBUG_BATCH) {
3723 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3724 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003725 synchronized (mLock) {
3726 mLastTickReceived = System.currentTimeMillis();
3727 }
Christopher Tate385e4982013-07-23 18:22:29 -07003728 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3730 // Since the kernel does not keep track of DST, we need to
3731 // reset the TZ information at the beginning of each day
3732 // based off of the current Zone gmt offset + userspace tracked
3733 // daylight savings information.
3734 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003735 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003736 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003737 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003738 }
3739 }
Kweku Adams61e03292017-10-19 14:27:12 -07003740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003742 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003743 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003744
3745 // Schedule this event for the amount of time that it would take to get to
3746 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003747 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003748
David Christieebe51fc2013-07-26 13:23:29 -07003749 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003750 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003751 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3752 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003753
3754 // Finally, remember when we set the tick alarm
3755 synchronized (mLock) {
3756 mLastTickSet = currentTime;
3757 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003758 }
Christopher Tate385e4982013-07-23 18:22:29 -07003759
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 public void scheduleDateChangedEvent() {
3761 Calendar calendar = Calendar.getInstance();
3762 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003763 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003764 calendar.set(Calendar.MINUTE, 0);
3765 calendar.set(Calendar.SECOND, 0);
3766 calendar.set(Calendar.MILLISECOND, 0);
3767 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003768
3769 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003770 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3771 AlarmManager.FLAG_STANDALONE, workSource, null,
3772 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003773 }
3774 }
Kweku Adams61e03292017-10-19 14:27:12 -07003775
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003776 class InteractiveStateReceiver extends BroadcastReceiver {
3777 public InteractiveStateReceiver() {
3778 IntentFilter filter = new IntentFilter();
3779 filter.addAction(Intent.ACTION_SCREEN_OFF);
3780 filter.addAction(Intent.ACTION_SCREEN_ON);
3781 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3782 getContext().registerReceiver(this, filter);
3783 }
3784
3785 @Override
3786 public void onReceive(Context context, Intent intent) {
3787 synchronized (mLock) {
3788 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3789 }
3790 }
3791 }
3792
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 class UninstallReceiver extends BroadcastReceiver {
3794 public UninstallReceiver() {
3795 IntentFilter filter = new IntentFilter();
3796 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3797 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003798 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003799 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003800 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003801 // Register for events related to sdcard installation.
3802 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003803 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003804 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003805 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003806 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003807 }
Kweku Adams61e03292017-10-19 14:27:12 -07003808
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 @Override
3810 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003811 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003812 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003813 String action = intent.getAction();
3814 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003815 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3816 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3817 for (String packageName : pkgList) {
3818 if (lookForPackageLocked(packageName)) {
3819 setResultCode(Activity.RESULT_OK);
3820 return;
3821 }
3822 }
3823 return;
3824 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003825 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003826 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3827 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3828 if (userHandle >= 0) {
3829 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003830 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3831 final Pair<String, Integer> packageUser =
3832 mLastAlarmDeliveredForPackage.keyAt(i);
3833 if (packageUser.second == userHandle) {
3834 mLastAlarmDeliveredForPackage.removeAt(i);
3835 }
3836 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003837 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003838 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003839 if (uid >= 0) {
3840 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003841 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003842 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003843 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003844 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3845 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3846 // This package is being updated; don't kill its alarms.
3847 return;
3848 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003849 Uri data = intent.getData();
3850 if (data != null) {
3851 String pkg = data.getSchemeSpecificPart();
3852 if (pkg != null) {
3853 pkgList = new String[]{pkg};
3854 }
3855 }
3856 }
3857 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003858 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3859 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3860 if (ArrayUtils.contains(pkgList, packageUser.first)
3861 && packageUser.second == UserHandle.getUserId(uid)) {
3862 mLastAlarmDeliveredForPackage.removeAt(i);
3863 }
3864 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003865 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003866 if (uid >= 0) {
3867 // package-removed case
3868 removeLocked(uid);
3869 } else {
3870 // external-applications-unavailable etc case
3871 removeLocked(pkg);
3872 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003873 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003874 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3875 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3876 if (uidStats.remove(pkg) != null) {
3877 if (uidStats.size() <= 0) {
3878 mBroadcastStats.removeAt(i);
3879 }
3880 }
3881 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003883 }
3884 }
3885 }
3886 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003887
3888 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003889 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003890 }
3891
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003892 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003893 if (disabled) {
3894 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003895 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003896 }
3897
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003898 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003899 }
3900
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003901 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003902 if (disabled) {
3903 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003904 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003905 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003906
3907 @Override public void onUidCachedChanged(int uid, boolean cached) {
3908 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003909 };
3910
Suprabh Shukla75edab12018-01-29 14:09:06 -08003911 /**
3912 * Tracking of app assignments to standby buckets
3913 */
3914 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3915 @Override
3916 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08003917 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003918 if (DEBUG_STANDBY) {
3919 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3920 bucket);
3921 }
3922 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003923 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3924 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003925 }
3926
3927 @Override
3928 public void onParoleStateChanged(boolean isParoleOn) {
3929 if (DEBUG_STANDBY) {
3930 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3931 }
3932 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3933 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3934 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3935 Boolean.valueOf(isParoleOn)).sendToTarget();
3936 }
3937 };
3938
Makoto Onuki2206af32017-11-21 16:25:35 -08003939 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003940 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003941 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003942 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003943 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003944 }
3945 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003946
3947 @Override
3948 public void unblockAlarmsForUid(int uid) {
3949 synchronized (mLock) {
3950 sendPendingBackgroundAlarmsLocked(uid, null);
3951 }
3952 }
3953
3954 @Override
3955 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3956 synchronized (mLock) {
3957 sendPendingBackgroundAlarmsLocked(uid, packageName);
3958 }
3959 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003960
3961 @Override
3962 public void onUidForeground(int uid, boolean foreground) {
3963 synchronized (mLock) {
3964 if (foreground) {
3965 mUseAllowWhileIdleShortTime.put(uid, true);
3966
3967 // Note we don't have to drain the pending while-idle alarms here, because
3968 // this event should coincide with unblockAlarmsForUid().
3969 }
3970 }
3971 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003972 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003973
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003974 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003975 String pkg = pi.getCreatorPackage();
3976 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003977 return getStatsLocked(uid, pkg);
3978 }
3979
3980 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003981 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3982 if (uidStats == null) {
3983 uidStats = new ArrayMap<String, BroadcastStats>();
3984 mBroadcastStats.put(uid, uidStats);
3985 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003986 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003987 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003988 bs = new BroadcastStats(uid, pkgName);
3989 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003990 }
3991 return bs;
3992 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003993
Christopher Tate21e9f192017-08-08 13:49:11 -07003994 /**
3995 * Canonical count of (operation.send() - onSendFinished()) and
3996 * listener send/complete/timeout invocations.
3997 * Guarded by the usual lock.
3998 */
3999 @GuardedBy("mLock")
4000 private int mSendCount = 0;
4001 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004002 private int mSendFinishCount = 0;
4003 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004004 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004005 @GuardedBy("mLock")
4006 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004007
Christopher Tate14a7bb02015-10-01 10:24:31 -07004008 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004009
Christopher Tate14a7bb02015-10-01 10:24:31 -07004010 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4011 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004012 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004013 return mInFlight.remove(i);
4014 }
4015 }
4016 mLog.w("No in-flight alarm for " + pi + " " + intent);
4017 return null;
4018 }
4019
4020 private InFlight removeLocked(IBinder listener) {
4021 for (int i = 0; i < mInFlight.size(); i++) {
4022 if (mInFlight.get(i).mListener == listener) {
4023 return mInFlight.remove(i);
4024 }
4025 }
4026 mLog.w("No in-flight alarm for listener " + listener);
4027 return null;
4028 }
4029
4030 private void updateStatsLocked(InFlight inflight) {
4031 final long nowELAPSED = SystemClock.elapsedRealtime();
4032 BroadcastStats bs = inflight.mBroadcastStats;
4033 bs.nesting--;
4034 if (bs.nesting <= 0) {
4035 bs.nesting = 0;
4036 bs.aggregateTime += nowELAPSED - bs.startTime;
4037 }
4038 FilterStats fs = inflight.mFilterStats;
4039 fs.nesting--;
4040 if (fs.nesting <= 0) {
4041 fs.nesting = 0;
4042 fs.aggregateTime += nowELAPSED - fs.startTime;
4043 }
4044 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004045 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4046 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004047 }
4048 }
4049
4050 private void updateTrackingLocked(InFlight inflight) {
4051 if (inflight != null) {
4052 updateStatsLocked(inflight);
4053 }
4054 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004055 if (DEBUG_WAKELOCK) {
4056 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4057 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004058 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004059 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004060 mWakeLock.release();
4061 if (mInFlight.size() > 0) {
4062 mLog.w("Finished all dispatches with " + mInFlight.size()
4063 + " remaining inflights");
4064 for (int i=0; i<mInFlight.size(); i++) {
4065 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4066 }
4067 mInFlight.clear();
4068 }
4069 } else {
4070 // the next of our alarms is now in flight. reattribute the wakelock.
4071 if (mInFlight.size() > 0) {
4072 InFlight inFlight = mInFlight.get(0);
4073 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4074 inFlight.mAlarmType, inFlight.mTag, -1, false);
4075 } else {
4076 // should never happen
4077 mLog.w("Alarm wakelock still held but sent queue empty");
4078 mWakeLock.setWorkSource(null);
4079 }
4080 }
4081 }
4082
4083 /**
4084 * Callback that arrives when a direct-call alarm reports that delivery has finished
4085 */
4086 @Override
4087 public void alarmComplete(IBinder who) {
4088 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004089 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004090 + " pid=" + Binder.getCallingPid());
4091 return;
4092 }
4093
4094 final long ident = Binder.clearCallingIdentity();
4095 try {
4096 synchronized (mLock) {
4097 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4098 InFlight inflight = removeLocked(who);
4099 if (inflight != null) {
4100 if (DEBUG_LISTENER_CALLBACK) {
4101 Slog.i(TAG, "alarmComplete() from " + who);
4102 }
4103 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004104 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004105 } else {
4106 // Delivery timed out, and the timeout handling already took care of
4107 // updating our tracking here, so we needn't do anything further.
4108 if (DEBUG_LISTENER_CALLBACK) {
4109 Slog.i(TAG, "Late alarmComplete() from " + who);
4110 }
4111 }
4112 }
4113 } finally {
4114 Binder.restoreCallingIdentity(ident);
4115 }
4116 }
4117
4118 /**
4119 * Callback that arrives when a PendingIntent alarm has finished delivery
4120 */
4121 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004122 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4123 String resultData, Bundle resultExtras) {
4124 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004125 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004126 updateTrackingLocked(removeLocked(pi, intent));
4127 }
4128 }
4129
4130 /**
4131 * Timeout of a direct-call alarm delivery
4132 */
4133 public void alarmTimedOut(IBinder who) {
4134 synchronized (mLock) {
4135 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004136 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004137 // TODO: implement ANR policy for the target
4138 if (DEBUG_LISTENER_CALLBACK) {
4139 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004140 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004141 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004142 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004143 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004144 if (DEBUG_LISTENER_CALLBACK) {
4145 Slog.i(TAG, "Spurious timeout of listener " + who);
4146 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004147 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004148 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004149 }
4150 }
4151
4152 /**
4153 * Deliver an alarm and set up the post-delivery handling appropriately
4154 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004155 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004156 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4157 if (alarm.operation != null) {
4158 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004159 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004160
4161 if (alarm.priorityClass.priority == PRIO_TICK) {
4162 mLastTickIssued = nowELAPSED;
4163 }
4164
Christopher Tate14a7bb02015-10-01 10:24:31 -07004165 try {
4166 alarm.operation.send(getContext(), 0,
4167 mBackgroundIntent.putExtra(
4168 Intent.EXTRA_ALARM_COUNT, alarm.count),
4169 mDeliveryTracker, mHandler, null,
4170 allowWhileIdle ? mIdleOptions : null);
4171 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004172 if (alarm.operation == mTimeTickSender) {
4173 Slog.wtf(TAG, "mTimeTickSender canceled");
4174 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004175 if (alarm.repeatInterval > 0) {
4176 // This IntentSender is no longer valid, but this
4177 // is a repeating alarm, so toss it
4178 removeImpl(alarm.operation);
4179 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004180 // No actual delivery was possible, so the delivery tracker's
4181 // 'finished' callback won't be invoked. We also don't need
4182 // to do any wakelock or stats tracking, so we have nothing
4183 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004184 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004185 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004186 }
4187 } else {
4188 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004189 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004190 try {
4191 if (DEBUG_LISTENER_CALLBACK) {
4192 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4193 + " listener=" + alarm.listener.asBinder());
4194 }
4195 alarm.listener.doAlarm(this);
4196 mHandler.sendMessageDelayed(
4197 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4198 alarm.listener.asBinder()),
4199 mConstants.LISTENER_TIMEOUT);
4200 } catch (Exception e) {
4201 if (DEBUG_LISTENER_CALLBACK) {
4202 Slog.i(TAG, "Alarm undeliverable to listener "
4203 + alarm.listener.asBinder(), e);
4204 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004205 // As in the PendingIntent.CanceledException case, delivery of the
4206 // alarm was not possible, so we have no wakelock or timeout or
4207 // stats management to do. It threw before we posted the delayed
4208 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004209 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004210 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004211 }
4212 }
4213
4214 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004215 if (DEBUG_WAKELOCK) {
4216 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4217 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004218 if (mBroadcastRefCount == 0) {
4219 setWakelockWorkSource(alarm.operation, alarm.workSource,
4220 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4221 true);
4222 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004223 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004224 }
4225 final InFlight inflight = new InFlight(AlarmManagerService.this,
4226 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4227 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4228 mInFlight.add(inflight);
4229 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004230 if (allowWhileIdle) {
4231 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004232 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004233 if ((mAppStateTracker == null)
4234 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004235 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4236 } else {
4237 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4238 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004239 if (RECORD_DEVICE_IDLE_ALARMS) {
4240 IdleDispatchEntry ent = new IdleDispatchEntry();
4241 ent.uid = alarm.uid;
4242 ent.pkg = alarm.packageName;
4243 ent.tag = alarm.statsTag;
4244 ent.op = "DELIVER";
4245 ent.elapsedRealtime = nowELAPSED;
4246 mAllowWhileIdleDispatches.add(ent);
4247 }
4248 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004249 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004250 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4251 UserHandle.getUserId(alarm.creatorUid));
4252 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4253 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004254
4255 final BroadcastStats bs = inflight.mBroadcastStats;
4256 bs.count++;
4257 if (bs.nesting == 0) {
4258 bs.nesting = 1;
4259 bs.startTime = nowELAPSED;
4260 } else {
4261 bs.nesting++;
4262 }
4263 final FilterStats fs = inflight.mFilterStats;
4264 fs.count++;
4265 if (fs.nesting == 0) {
4266 fs.nesting = 1;
4267 fs.startTime = nowELAPSED;
4268 } else {
4269 fs.nesting++;
4270 }
4271 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4272 || alarm.type == RTC_WAKEUP) {
4273 bs.numWakeup++;
4274 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004275 ActivityManager.noteWakeupAlarm(
4276 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4277 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004278 }
4279 }
4280 }
mswest463f4c99d2018-02-01 10:13:10 -08004281
4282 private class ShellCmd extends ShellCommand {
4283
4284 IAlarmManager getBinderService() {
4285 return IAlarmManager.Stub.asInterface(mService);
4286 }
4287
4288 @Override
4289 public int onCommand(String cmd) {
4290 if (cmd == null) {
4291 return handleDefaultCommands(cmd);
4292 }
4293
4294 final PrintWriter pw = getOutPrintWriter();
4295 try {
4296 switch (cmd) {
4297 case "set-time":
4298 final long millis = Long.parseLong(getNextArgRequired());
4299 return (getBinderService().setTime(millis)) ? 0 : -1;
4300 case "set-timezone":
4301 final String tz = getNextArgRequired();
4302 getBinderService().setTimeZone(tz);
4303 return 0;
4304 default:
4305 return handleDefaultCommands(cmd);
4306 }
4307 } catch (Exception e) {
4308 pw.println(e);
4309 }
4310 return -1;
4311 }
4312
4313 @Override
4314 public void onHelp() {
4315 PrintWriter pw = getOutPrintWriter();
4316 pw.println("Alarm manager service (alarm) commands:");
4317 pw.println(" help");
4318 pw.println(" Print this help text.");
4319 pw.println(" set-time TIME");
4320 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4321 pw.println(" since the Epoch.");
4322 pw.println(" set-timezone TZ");
4323 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4324 }
4325 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004326}