blob: 576ec29301f922391cb5033df43b2bd7237d7eb1 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Jeff Sharkey9911a282018-02-14 22:29:11 -070019import static android.app.AlarmManager.ELAPSED_REALTIME;
20import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
21import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE;
22import static android.app.AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
23import static android.app.AlarmManager.RTC;
24import static android.app.AlarmManager.RTC_WAKEUP;
25
Suprabh Shukla75edab12018-01-29 14:09:06 -080026import android.annotation.UserIdInt;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080027import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020028import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070029import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070030import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070031import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070032import android.app.IAlarmCompleteListener;
33import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080034import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070035import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.app.PendingIntent;
Suprabh Shukla75edab12018-01-29 14:09:06 -080037import android.app.usage.UsageStatsManager;
38import android.app.usage.UsageStatsManagerInternal;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070040import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.Context;
42import android.content.Intent;
43import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070044import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070046import android.content.pm.PackageManager.NameNotFoundException;
47import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.Uri;
50import android.os.Binder;
51import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070052import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080054import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070056import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070058import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070059import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.os.SystemClock;
61import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080062import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070063import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070064import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020065import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080066import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020068import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080069import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080070import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080071import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070072import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020073import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070074import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080075import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080076import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080077import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020078import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070079import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070080import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070081import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082
Jeff Sharkey9911a282018-02-14 22:29:11 -070083import com.android.internal.annotations.GuardedBy;
84import com.android.internal.annotations.VisibleForTesting;
85import com.android.internal.util.ArrayUtils;
86import com.android.internal.util.DumpUtils;
87import com.android.internal.util.LocalLog;
88import com.android.server.AppStateTracker.Listener;
89
Christopher Tate4cb338d2013-07-26 13:11:31 -070090import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import java.io.FileDescriptor;
92import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070093import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -070094import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080096import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import java.util.Calendar;
98import java.util.Collections;
99import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500100import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700101import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700102import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200103import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700104import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400106import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800107import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108
Makoto Onuki2206af32017-11-21 16:25:35 -0800109/**
110 * Alarm manager implementaion.
111 *
112 * Unit test:
113 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
114 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700116 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
117 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700119 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120 static final int TIME_CHANGED_MASK = 1 << 16;
121 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800122
Christopher Tatee0a22b32013-07-11 14:43:13 -0700123 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800125
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800127 static final boolean localLOGV = false;
128 static final boolean DEBUG_BATCH = localLOGV || false;
129 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200130 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700131 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800132 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700133 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800134 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700135 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700136 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 static final int ALARM_EVENT = 1;
138 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200139
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700143
Adam Lesinski182f73f2013-12-05 16:48:06 -0800144 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700145
Christopher Tate24cd46f2016-02-02 14:28:01 -0800146 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
147 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700148 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
149 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200150
Adam Lesinski182f73f2013-12-05 16:48:06 -0800151 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800152
Christopher Tate14a7bb02015-10-01 10:24:31 -0700153 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800154 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800155 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700156
Adam Lesinski182f73f2013-12-05 16:48:06 -0800157 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800158
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700159 // List of alarms per uid deferred due to user applied background restrictions on the source app
160 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800161 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800162 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700163 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700164 private long mLastWakeupSet;
165 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800166 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800167 private long mLastTickSet;
168 private long mLastTickIssued; // elapsed
169 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800170 private long mLastTickAdded;
171 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800172 int mBroadcastRefCount = 0;
173 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700174 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700175 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
176 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800177 final AlarmHandler mHandler = new AlarmHandler();
178 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700179 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700181 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800182 PendingIntent mTimeTickSender;
183 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700184 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700185 boolean mInteractive = true;
186 long mNonInteractiveStartTime;
187 long mNonInteractiveTime;
188 long mLastAlarmDeliveryTime;
189 long mStartCurrentDelayTime;
190 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700191 long mLastTimeChangeClockTime;
192 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700193 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800194
Christopher Tatebb9cce52017-04-18 14:19:43 -0700195 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
196
197 /**
198 * This permission must be defined by the canonical System UI package,
199 * with protection level "signature".
200 */
201 private static final String SYSTEM_UI_SELF_PERMISSION =
202 "android.permission.systemui.IDENTITY";
203
204 /**
205 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
206 */
207 int mSystemUiUid;
208
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700209 /**
210 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700211 * used to determine the earliest we can dispatch the next such alarm. Times are in the
212 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700213 */
214 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
215
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800216 /**
217 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
218 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
219 */
220 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
221
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700222 final static class IdleDispatchEntry {
223 int uid;
224 String pkg;
225 String tag;
226 String op;
227 long elapsedRealtime;
228 long argRealtime;
229 }
230 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
231
Suprabh Shukla75edab12018-01-29 14:09:06 -0800232 interface Stats {
233 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800234 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800235 }
236
237 private final StatLogger mStatLogger = new StatLogger(new String[] {
238 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800239 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800240 });
241
Dianne Hackborna750a632015-06-16 17:18:23 -0700242 /**
243 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
244 */
245 Bundle mIdleOptions;
246
Jose Lima235510e2014-08-13 12:50:01 -0700247 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
248 new SparseArray<>();
249 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
250 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200251 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
252 new SparseBooleanArray();
253 private boolean mNextAlarmClockMayChange;
254
255 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700256 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
257 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200258
Makoto Onukie4918212018-02-06 11:30:15 -0800259 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800260 private boolean mAppStandbyParole;
261 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800262
Dianne Hackborna750a632015-06-16 17:18:23 -0700263 /**
264 * All times are in milliseconds. These constants are kept synchronized with the system
265 * global Settings. Any access to this class or its fields should be done while
266 * holding the AlarmManagerService.mLock lock.
267 */
268 private final class Constants extends ContentObserver {
269 // Key names stored in the settings value.
270 private static final String KEY_MIN_FUTURITY = "min_futurity";
271 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800272 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700273 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
274 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
275 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
276 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700277 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700278
Suprabh Shukla75edab12018-01-29 14:09:06 -0800279 // Keys for specifying throttling delay based on app standby bucketing
280 private final String[] KEYS_APP_STANDBY_DELAY = {
281 "standby_active_delay",
282 "standby_working_delay",
283 "standby_frequent_delay",
284 "standby_rare_delay",
285 "standby_never_delay",
286 };
287
Dianne Hackborna750a632015-06-16 17:18:23 -0700288 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
289 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800290 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700291 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700292 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700293 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700294 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800295 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
296 0, // Active
297 6 * 60_000, // Working
298 30 * 60_000, // Frequent
299 2 * 60 * 60_000, // Rare
300 10 * 24 * 60 * 60_000 // Never
301 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700302
Dianne Hackborna750a632015-06-16 17:18:23 -0700303 // Minimum futurity of a new alarm
304 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
305
306 // Minimum alarm recurrence interval
307 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
308
Christopher Tate22e919d2018-02-16 16:16:50 -0800309 // Maximum alarm recurrence interval
310 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
311
Dianne Hackborna750a632015-06-16 17:18:23 -0700312 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
313 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
314
315 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
316 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
317
318 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
319 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
320 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
321
Christopher Tate14a7bb02015-10-01 10:24:31 -0700322 // Direct alarm listener callback timeout
323 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
324
Suprabh Shukla75edab12018-01-29 14:09:06 -0800325 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
326
Dianne Hackborna750a632015-06-16 17:18:23 -0700327 private ContentResolver mResolver;
328 private final KeyValueListParser mParser = new KeyValueListParser(',');
329 private long mLastAllowWhileIdleWhitelistDuration = -1;
330
331 public Constants(Handler handler) {
332 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700333 updateAllowWhileIdleWhitelistDurationLocked();
334 }
335
336 public void start(ContentResolver resolver) {
337 mResolver = resolver;
338 mResolver.registerContentObserver(Settings.Global.getUriFor(
339 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
340 updateConstants();
341 }
342
Dianne Hackborna750a632015-06-16 17:18:23 -0700343 public void updateAllowWhileIdleWhitelistDurationLocked() {
344 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
345 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
346 BroadcastOptions opts = BroadcastOptions.makeBasic();
347 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
348 mIdleOptions = opts.toBundle();
349 }
350 }
351
352 @Override
353 public void onChange(boolean selfChange, Uri uri) {
354 updateConstants();
355 }
356
357 private void updateConstants() {
358 synchronized (mLock) {
359 try {
360 mParser.setString(Settings.Global.getString(mResolver,
361 Settings.Global.ALARM_MANAGER_CONSTANTS));
362 } catch (IllegalArgumentException e) {
363 // Failed to parse the settings string, log this and move on
364 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800365 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700366 }
367
368 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
369 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800370 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700371 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
372 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
373 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
374 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
375 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
376 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
377 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700378 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
379 DEFAULT_LISTENER_TIMEOUT);
Suprabh Shukla75edab12018-01-29 14:09:06 -0800380 APP_STANDBY_MIN_DELAYS[0] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[0],
381 DEFAULT_APP_STANDBY_DELAYS[0]);
382 for (int i = 1; i < KEYS_APP_STANDBY_DELAY.length; i++) {
383 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
384 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
385 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700386 updateAllowWhileIdleWhitelistDurationLocked();
387 }
388 }
389
390 void dump(PrintWriter pw) {
391 pw.println(" Settings:");
392
393 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
394 TimeUtils.formatDuration(MIN_FUTURITY, pw);
395 pw.println();
396
397 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
398 TimeUtils.formatDuration(MIN_INTERVAL, pw);
399 pw.println();
400
Christopher Tate22e919d2018-02-16 16:16:50 -0800401 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
402 TimeUtils.formatDuration(MAX_INTERVAL, pw);
403 pw.println();
404
Christopher Tate14a7bb02015-10-01 10:24:31 -0700405 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
406 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
407 pw.println();
408
Dianne Hackborna750a632015-06-16 17:18:23 -0700409 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
410 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
411 pw.println();
412
413 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
414 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
415 pw.println();
416
417 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
418 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
419 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800420
421 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
422 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
423 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
424 pw.println();
425 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700426 }
Kweku Adams61e03292017-10-19 14:27:12 -0700427
428 void dumpProto(ProtoOutputStream proto, long fieldId) {
429 final long token = proto.start(fieldId);
430
431 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
432 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800433 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700434 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
435 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
436 ALLOW_WHILE_IDLE_SHORT_TIME);
437 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
438 ALLOW_WHILE_IDLE_LONG_TIME);
439 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
440 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
441
442 proto.end(token);
443 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700444 }
445
446 final Constants mConstants;
447
Christopher Tate1590f1e2014-10-02 17:27:57 -0700448 // Alarm delivery ordering bookkeeping
449 static final int PRIO_TICK = 0;
450 static final int PRIO_WAKEUP = 1;
451 static final int PRIO_NORMAL = 2;
452
Dianne Hackborna750a632015-06-16 17:18:23 -0700453 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700454 int seq;
455 int priority;
456
457 PriorityClass() {
458 seq = mCurrentSeq - 1;
459 priority = PRIO_NORMAL;
460 }
461 }
462
Dianne Hackborna750a632015-06-16 17:18:23 -0700463 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700464 int mCurrentSeq = 0;
465
Dianne Hackborna750a632015-06-16 17:18:23 -0700466 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700467 public long when;
468 public int uid;
469 public String action;
470
471 public WakeupEvent(long theTime, int theUid, String theAction) {
472 when = theTime;
473 uid = theUid;
474 action = theAction;
475 }
476 }
477
Adam Lesinski182f73f2013-12-05 16:48:06 -0800478 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
479 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700480
Adrian Roosc42a1e12014-07-07 23:35:53 +0200481 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 long start; // These endpoints are always in ELAPSED
483 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700484 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485
486 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
487
488 Batch() {
489 start = 0;
490 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700491 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700492 }
493
494 Batch(Alarm seed) {
495 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800496 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700497 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800499 if (seed.operation == mTimeTickSender) {
500 mLastTickAdded = System.currentTimeMillis();
501 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700502 }
503
504 int size() {
505 return alarms.size();
506 }
507
508 Alarm get(int index) {
509 return alarms.get(index);
510 }
511
512 boolean canHold(long whenElapsed, long maxWhen) {
513 return (end >= whenElapsed) && (start <= maxWhen);
514 }
515
516 boolean add(Alarm alarm) {
517 boolean newStart = false;
518 // narrows the batch if necessary; presumes that canHold(alarm) is true
519 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
520 if (index < 0) {
521 index = 0 - index - 1;
522 }
523 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800524 if (alarm.operation == mTimeTickSender) {
525 mLastTickAdded = System.currentTimeMillis();
526 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700527 if (DEBUG_BATCH) {
528 Slog.v(TAG, "Adding " + alarm + " to " + this);
529 }
530 if (alarm.whenElapsed > start) {
531 start = alarm.whenElapsed;
532 newStart = true;
533 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700534 if (alarm.maxWhenElapsed < end) {
535 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700536 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700537 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700538
539 if (DEBUG_BATCH) {
540 Slog.v(TAG, " => now " + this);
541 }
542 return newStart;
543 }
544
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800545 boolean remove(Alarm alarm) {
546 return remove(a -> (a == alarm));
547 }
548
Christopher Tate1d99c392017-12-07 16:54:04 -0800549 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700550 boolean didRemove = false;
551 long newStart = 0; // recalculate endpoints as we go
552 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700553 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700554 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800556 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700557 alarms.remove(i);
558 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200559 if (alarm.alarmClock != null) {
560 mNextAlarmClockMayChange = true;
561 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800562 if (alarm.operation == mTimeTickSender) {
563 mLastTickRemoved = System.currentTimeMillis();
564 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 } else {
566 if (alarm.whenElapsed > newStart) {
567 newStart = alarm.whenElapsed;
568 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700569 if (alarm.maxWhenElapsed < newEnd) {
570 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700571 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700572 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700573 i++;
574 }
575 }
576 if (didRemove) {
577 // commit the new batch bounds
578 start = newStart;
579 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700580 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700581 }
582 return didRemove;
583 }
584
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 boolean hasPackage(final String packageName) {
586 final int N = alarms.size();
587 for (int i = 0; i < N; i++) {
588 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700589 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700590 return true;
591 }
592 }
593 return false;
594 }
595
596 boolean hasWakeups() {
597 final int N = alarms.size();
598 for (int i = 0; i < N; i++) {
599 Alarm a = alarms.get(i);
600 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
601 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
602 return true;
603 }
604 }
605 return false;
606 }
607
608 @Override
609 public String toString() {
610 StringBuilder b = new StringBuilder(40);
611 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
612 b.append(" num="); b.append(size());
613 b.append(" start="); b.append(start);
614 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700615 if (flags != 0) {
616 b.append(" flgs=0x");
617 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700618 }
619 b.append('}');
620 return b.toString();
621 }
Kweku Adams61e03292017-10-19 14:27:12 -0700622
623 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
624 long nowRTC) {
625 final long token = proto.start(fieldId);
626
627 proto.write(BatchProto.START_REALTIME, start);
628 proto.write(BatchProto.END_REALTIME, end);
629 proto.write(BatchProto.FLAGS, flags);
630 for (Alarm a : alarms) {
631 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
632 }
633
634 proto.end(token);
635 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700636 }
637
638 static class BatchTimeOrder implements Comparator<Batch> {
639 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800640 long when1 = b1.start;
641 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800642 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700643 return 1;
644 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800645 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700646 return -1;
647 }
648 return 0;
649 }
650 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800651
652 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
653 @Override
654 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700655 // priority class trumps everything. TICK < WAKEUP < NORMAL
656 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
657 return -1;
658 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
659 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800660 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700661
662 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800663 if (lhs.whenElapsed < rhs.whenElapsed) {
664 return -1;
665 } else if (lhs.whenElapsed > rhs.whenElapsed) {
666 return 1;
667 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700668
669 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800670 return 0;
671 }
672 };
673
Christopher Tate1590f1e2014-10-02 17:27:57 -0700674 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
675 final int N = alarms.size();
676 for (int i = 0; i < N; i++) {
677 Alarm a = alarms.get(i);
678
679 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700680 if (a.operation != null
681 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700682 alarmPrio = PRIO_TICK;
683 } else if (a.wakeup) {
684 alarmPrio = PRIO_WAKEUP;
685 } else {
686 alarmPrio = PRIO_NORMAL;
687 }
688
689 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800690 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700691 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700692 if (packagePrio == null) {
693 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700694 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700695 }
696 a.priorityClass = packagePrio;
697
698 if (packagePrio.seq != mCurrentSeq) {
699 // first alarm we've seen in the current delivery generation from this package
700 packagePrio.priority = alarmPrio;
701 packagePrio.seq = mCurrentSeq;
702 } else {
703 // Multiple alarms from this package being delivered in this generation;
704 // bump the package's delivery class if it's warranted.
705 // TICK < WAKEUP < NORMAL
706 if (alarmPrio < packagePrio.priority) {
707 packagePrio.priority = alarmPrio;
708 }
709 }
710 }
711 }
712
Christopher Tatee0a22b32013-07-11 14:43:13 -0700713 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800714 static final long MIN_FUZZABLE_INTERVAL = 10000;
715 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700716 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
717
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700718 // set to non-null if in idle mode; while in this mode, any alarms we don't want
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700719 // to run during this time are placed in mPendingWhileIdleAlarms
720 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700721 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700722 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700723
Jeff Brownb880d882014-02-10 19:47:07 -0800724 public AlarmManagerService(Context context) {
725 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700726 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800727
Christopher Tate1d99c392017-12-07 16:54:04 -0800728 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800729 }
730
Christopher Tatee0a22b32013-07-11 14:43:13 -0700731 static long convertToElapsed(long when, int type) {
732 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
733 if (isRtc) {
734 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
735 }
736 return when;
737 }
738
739 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
740 // calculate the end of our nominal delivery window for the alarm.
741 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
742 // Current heuristic: batchable window is 75% of either the recurrence interval
743 // [for a periodic alarm] or of the time from now to the desired delivery time,
744 // with a minimum delay/interval of 10 seconds, under which we will simply not
745 // defer the alarm.
746 long futurity = (interval == 0)
747 ? (triggerAtTime - now)
748 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700749 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700750 futurity = 0;
751 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800752 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700753 }
754
755 // returns true if the batch was added at the head
756 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
757 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
758 if (index < 0) {
759 index = 0 - index - 1;
760 }
761 list.add(index, newBatch);
762 return (index == 0);
763 }
764
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800765 private void insertAndBatchAlarmLocked(Alarm alarm) {
766 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
767 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
768
769 if (whichBatch < 0) {
770 addBatchLocked(mAlarmBatches, new Batch(alarm));
771 } else {
772 final Batch batch = mAlarmBatches.get(whichBatch);
773 if (batch.add(alarm)) {
774 // The start time of this batch advanced, so batch ordering may
775 // have just been broken. Move it to where it now belongs.
776 mAlarmBatches.remove(whichBatch);
777 addBatchLocked(mAlarmBatches, batch);
778 }
779 }
780 }
781
Christopher Tate385e4982013-07-23 18:22:29 -0700782 // Return the index of the matching batch, or -1 if none found.
783 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700784 final int N = mAlarmBatches.size();
785 for (int i = 0; i < N; i++) {
786 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700787 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700788 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700789 }
790 }
Christopher Tate385e4982013-07-23 18:22:29 -0700791 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700792 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800793 /** @return total count of the alarms in a set of alarm batches. */
794 static int getAlarmCount(ArrayList<Batch> batches) {
795 int ret = 0;
796
797 final int size = batches.size();
798 for (int i = 0; i < size; i++) {
799 ret += batches.get(i).size();
800 }
801 return ret;
802 }
803
804 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
805 if (alarms.size() == 0) {
806 return false;
807 }
808 final int batchSize = alarms.size();
809 for (int j = 0; j < batchSize; j++) {
810 if (alarms.get(j).operation == mTimeTickSender) {
811 return true;
812 }
813 }
814 return false;
815 }
816
817 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
818 final int numBatches = batches.size();
819 for (int i = 0; i < numBatches; i++) {
820 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
821 return true;
822 }
823 }
824 return false;
825 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700826
827 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
828 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700829 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700830 rebatchAllAlarmsLocked(true);
831 }
832 }
833
834 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800835 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800836 final int oldCount =
837 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
838 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
839 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
840
Christopher Tate4cb338d2013-07-26 13:11:31 -0700841 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
842 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700843 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700844 final long nowElapsed = SystemClock.elapsedRealtime();
845 final int oldBatches = oldSet.size();
846 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
847 Batch batch = oldSet.get(batchNum);
848 final int N = batch.size();
849 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700850 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700851 }
852 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700853 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
854 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
855 + " to " + mPendingIdleUntil);
856 if (mPendingIdleUntil == null) {
857 // Somehow we lost this... we need to restore all of the pending alarms.
858 restorePendingWhileIdleAlarmsLocked();
859 }
860 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800861 final int newCount =
862 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
863 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
864 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
865
866 if (oldCount != newCount) {
867 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
868 }
869 if (oldHasTick != newHasTick) {
870 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
871 }
872
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700873 rescheduleKernelAlarmsLocked();
874 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800875 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700876 }
877
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800878 /**
879 * Re-orders the alarm batches based on newly evaluated send times based on the current
880 * app-standby buckets
881 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
882 * null indicates all
883 * @return True if there was any reordering done to the current list.
884 */
885 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
886 final long start = mStatLogger.getTime();
887 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
888
889 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
890 final Batch batch = mAlarmBatches.get(batchIndex);
891 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
892 final Alarm alarm = batch.get(alarmIndex);
893 final Pair<String, Integer> packageUser =
894 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
895 if (targetPackages != null && !targetPackages.contains(packageUser)) {
896 continue;
897 }
898 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
899 batch.remove(alarm);
900 rescheduledAlarms.add(alarm);
901 }
902 }
903 if (batch.size() == 0) {
904 mAlarmBatches.remove(batchIndex);
905 }
906 }
907 for (int i = 0; i < rescheduledAlarms.size(); i++) {
908 final Alarm a = rescheduledAlarms.get(i);
909 insertAndBatchAlarmLocked(a);
910 }
911
912 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
913 return rescheduledAlarms.size() > 0;
914 }
915
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700916 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
917 a.when = a.origWhen;
918 long whenElapsed = convertToElapsed(a.when, a.type);
919 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700920 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700921 // Exact
922 maxElapsed = whenElapsed;
923 } else {
924 // Not exact. Preserve any explicit window, otherwise recalculate
925 // the window based on the alarm's new futurity. Note that this
926 // reflects a policy of preferring timely to deferred delivery.
927 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800928 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700929 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
930 }
931 a.whenElapsed = whenElapsed;
932 a.maxWhenElapsed = maxElapsed;
933 setImplLocked(a, true, doValidate);
934 }
935
Christopher Tate22e919d2018-02-16 16:16:50 -0800936 static long clampPositive(long val) {
937 return (val >= 0) ? val : Long.MAX_VALUE;
938 }
939
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700940 /**
941 * Sends alarms that were blocked due to user applied background restrictions - either because
942 * the user lifted those or the uid came to foreground.
943 *
944 * @param uid uid to filter on
945 * @param packageName package to filter on, or null for all packages in uid
946 */
947 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
948 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
949 if (alarmsForUid == null || alarmsForUid.size() == 0) {
950 return;
951 }
952 final ArrayList<Alarm> alarmsToDeliver;
953 if (packageName != null) {
954 if (DEBUG_BG_LIMIT) {
955 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
956 }
957 alarmsToDeliver = new ArrayList<>();
958 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
959 final Alarm a = alarmsForUid.get(i);
960 if (a.matches(packageName)) {
961 alarmsToDeliver.add(alarmsForUid.remove(i));
962 }
963 }
964 if (alarmsForUid.size() == 0) {
965 mPendingBackgroundAlarms.remove(uid);
966 }
967 } else {
968 if (DEBUG_BG_LIMIT) {
969 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
970 }
971 alarmsToDeliver = alarmsForUid;
972 mPendingBackgroundAlarms.remove(uid);
973 }
974 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
975 }
976
Makoto Onuki2206af32017-11-21 16:25:35 -0800977 /**
978 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
979 * restricted.
980 *
981 * This is only called when the global "force all apps-standby" flag changes or when the
982 * power save whitelist changes, so it's okay to be slow.
983 */
984 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700985 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800986
987 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
988 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
989
990 if (alarmsToDeliver.size() > 0) {
991 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
992 }
993 }
994
995 @VisibleForTesting
996 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
997 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
998 Predicate<Alarm> isBackgroundRestricted) {
999
1000 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1001 final int uid = pendingAlarms.keyAt(uidIndex);
1002 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1003
1004 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1005 final Alarm alarm = alarmsForUid.get(alarmIndex);
1006
1007 if (isBackgroundRestricted.test(alarm)) {
1008 continue;
1009 }
1010
1011 unrestrictedAlarms.add(alarm);
1012 alarmsForUid.remove(alarmIndex);
1013 }
1014
1015 if (alarmsForUid.size() == 0) {
1016 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001017 }
1018 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001019 }
1020
1021 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1022 final int N = alarms.size();
1023 boolean hasWakeup = false;
1024 for (int i = 0; i < N; i++) {
1025 final Alarm alarm = alarms.get(i);
1026 if (alarm.wakeup) {
1027 hasWakeup = true;
1028 }
1029 alarm.count = 1;
1030 // Recurring alarms may have passed several alarm intervals while the
1031 // alarm was kept pending. Send the appropriate trigger count.
1032 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001033 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001034 // Also schedule its next recurrence
1035 final long delta = alarm.count * alarm.repeatInterval;
1036 final long nextElapsed = alarm.whenElapsed + delta;
1037 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1038 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1039 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1040 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1041 // Kernel alarms will be rescheduled as needed in setImplLocked
1042 }
1043 }
1044 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1045 // No need to wakeup for non wakeup alarms
1046 if (mPendingNonWakeupAlarms.size() == 0) {
1047 mStartCurrentDelayTime = nowELAPSED;
1048 mNextNonWakeupDeliveryTime = nowELAPSED
1049 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1050 }
1051 mPendingNonWakeupAlarms.addAll(alarms);
1052 mNumDelayedAlarms += alarms.size();
1053 } else {
1054 if (DEBUG_BG_LIMIT) {
1055 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1056 }
1057 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1058 if (mPendingNonWakeupAlarms.size() > 0) {
1059 alarms.addAll(mPendingNonWakeupAlarms);
1060 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1061 mTotalDelayTime += thisDelayTime;
1062 if (mMaxDelayTime < thisDelayTime) {
1063 mMaxDelayTime = thisDelayTime;
1064 }
1065 mPendingNonWakeupAlarms.clear();
1066 }
1067 calculateDeliveryPriorities(alarms);
1068 Collections.sort(alarms, mAlarmDispatchComparator);
1069 deliverAlarmsLocked(alarms, nowELAPSED);
1070 }
1071 }
1072
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001073 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001074 if (RECORD_DEVICE_IDLE_ALARMS) {
1075 IdleDispatchEntry ent = new IdleDispatchEntry();
1076 ent.uid = 0;
1077 ent.pkg = "FINISH IDLE";
1078 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1079 mAllowWhileIdleDispatches.add(ent);
1080 }
1081
Dianne Hackborn35d54032015-04-23 10:30:43 -07001082 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001083 if (mPendingWhileIdleAlarms.size() > 0) {
1084 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1085 mPendingWhileIdleAlarms = new ArrayList<>();
1086 final long nowElapsed = SystemClock.elapsedRealtime();
1087 for (int i=alarms.size() - 1; i >= 0; i--) {
1088 Alarm a = alarms.get(i);
1089 reAddAlarmLocked(a, nowElapsed, false);
1090 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001091 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001092
1093 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001094 rescheduleKernelAlarmsLocked();
1095 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001096
1097 // And send a TIME_TICK right now, since it is important to get the UI updated.
1098 try {
1099 mTimeTickSender.send();
1100 } catch (PendingIntent.CanceledException e) {
1101 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001102 }
1103
Christopher Tate14a7bb02015-10-01 10:24:31 -07001104 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001105 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001106 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001107 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001108 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001109 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001110 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001111 final BroadcastStats mBroadcastStats;
1112 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001113 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001114
Christopher Tate14a7bb02015-10-01 10:24:31 -07001115 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1116 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1117 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001118 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001119 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001120 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001121 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001122 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001123 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001124 mBroadcastStats = (pendingIntent != null)
1125 ? service.getStatsLocked(pendingIntent)
1126 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001127 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001128 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001129 fs = new FilterStats(mBroadcastStats, mTag);
1130 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001131 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001132 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001133 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001134 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001135 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001136
1137 @Override
1138 public String toString() {
1139 return "InFlight{"
1140 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001141 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001142 + ", workSource=" + mWorkSource
1143 + ", uid=" + mUid
1144 + ", tag=" + mTag
1145 + ", broadcastStats=" + mBroadcastStats
1146 + ", filterStats=" + mFilterStats
1147 + ", alarmType=" + mAlarmType
1148 + "}";
1149 }
Kweku Adams61e03292017-10-19 14:27:12 -07001150
1151 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1152 final long token = proto.start(fieldId);
1153
1154 proto.write(InFlightProto.UID, mUid);
1155 proto.write(InFlightProto.TAG, mTag);
1156 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1157 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1158 if (mPendingIntent != null) {
1159 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1160 }
1161 if (mBroadcastStats != null) {
1162 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1163 }
1164 if (mFilterStats != null) {
1165 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1166 }
1167 if (mWorkSource != null) {
1168 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1169 }
1170
1171 proto.end(token);
1172 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001173 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001174
Adam Lesinski182f73f2013-12-05 16:48:06 -08001175 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001176 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001177 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001178
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001179 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001180 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001181 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 int numWakeup;
1183 long startTime;
1184 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001185
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001186 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001187 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001188 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001189 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001190
1191 @Override
1192 public String toString() {
1193 return "FilterStats{"
1194 + "tag=" + mTag
1195 + ", lastTime=" + lastTime
1196 + ", aggregateTime=" + aggregateTime
1197 + ", count=" + count
1198 + ", numWakeup=" + numWakeup
1199 + ", startTime=" + startTime
1200 + ", nesting=" + nesting
1201 + "}";
1202 }
Kweku Adams61e03292017-10-19 14:27:12 -07001203
1204 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1205 final long token = proto.start(fieldId);
1206
1207 proto.write(FilterStatsProto.TAG, mTag);
1208 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1209 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1210 proto.write(FilterStatsProto.COUNT, count);
1211 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1212 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1213 proto.write(FilterStatsProto.NESTING, nesting);
1214
1215 proto.end(token);
1216 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001217 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001218
Adam Lesinski182f73f2013-12-05 16:48:06 -08001219 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001220 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001221 final String mPackageName;
1222
1223 long aggregateTime;
1224 int count;
1225 int numWakeup;
1226 long startTime;
1227 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001228 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001229
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001230 BroadcastStats(int uid, String packageName) {
1231 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001232 mPackageName = packageName;
1233 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001234
1235 @Override
1236 public String toString() {
1237 return "BroadcastStats{"
1238 + "uid=" + mUid
1239 + ", packageName=" + mPackageName
1240 + ", aggregateTime=" + aggregateTime
1241 + ", count=" + count
1242 + ", numWakeup=" + numWakeup
1243 + ", startTime=" + startTime
1244 + ", nesting=" + nesting
1245 + "}";
1246 }
Kweku Adams61e03292017-10-19 14:27:12 -07001247
1248 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1249 final long token = proto.start(fieldId);
1250
1251 proto.write(BroadcastStatsProto.UID, mUid);
1252 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1253 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1254 proto.write(BroadcastStatsProto.COUNT, count);
1255 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1256 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1257 proto.write(BroadcastStatsProto.NESTING, nesting);
1258
1259 proto.end(token);
1260 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001262
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001263 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1264 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001265
1266 int mNumDelayedAlarms = 0;
1267 long mTotalDelayTime = 0;
1268 long mMaxDelayTime = 0;
1269
Adam Lesinski182f73f2013-12-05 16:48:06 -08001270 @Override
1271 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001272 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001273 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001274
1275 // We have to set current TimeZone info to kernel
1276 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001277 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001278
Christopher Tate247571462017-04-10 11:45:05 -07001279 // Also sure that we're booting with a halfway sensible current time
1280 if (mNativeData != 0) {
1281 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1282 if (System.currentTimeMillis() < systemBuildTime) {
1283 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1284 + ", advancing to build time " + systemBuildTime);
1285 setKernelTime(mNativeData, systemBuildTime);
1286 }
1287 }
1288
Christopher Tatebb9cce52017-04-18 14:19:43 -07001289 // Determine SysUI's uid
1290 final PackageManager packMan = getContext().getPackageManager();
1291 try {
1292 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1293 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1294 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1295 mSystemUiUid = sysUi.uid;
1296 } else {
1297 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1298 + " defined by non-privileged app " + sysUi.packageName
1299 + " - ignoring");
1300 }
1301 } catch (NameNotFoundException e) {
1302 }
1303
1304 if (mSystemUiUid <= 0) {
1305 Slog.wtf(TAG, "SysUI package not found!");
1306 }
1307
Adam Lesinski182f73f2013-12-05 16:48:06 -08001308 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001309 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001310
Adam Lesinski182f73f2013-12-05 16:48:06 -08001311 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001313 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001314 | Intent.FLAG_RECEIVER_FOREGROUND
1315 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001316 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001317 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001318 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1319 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001320 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001321 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001322
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001323 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001324 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 mClockReceiver.scheduleTimeTickEvent();
1326 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001327 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001329
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001330 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001331 AlarmThread waitThread = new AlarmThread();
1332 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001334 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001336
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001337 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001338 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001339 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1340 | ActivityManager.UID_OBSERVER_ACTIVE,
1341 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001342 } catch (RemoteException e) {
1343 // ignored; both services live in system_server
1344 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001345 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001346 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001347
1348 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001349 public void onBootPhase(int phase) {
1350 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1351 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001352 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001353 mLocalDeviceIdleController
1354 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001355 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1356 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001357
1358 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1359 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001360 }
1361 }
1362
1363 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 protected void finalize() throws Throwable {
1365 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001366 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 } finally {
1368 super.finalize();
1369 }
1370 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001371
Adam Lesinski182f73f2013-12-05 16:48:06 -08001372 void setTimeZoneImpl(String tz) {
1373 if (TextUtils.isEmpty(tz)) {
1374 return;
David Christieebe51fc2013-07-26 13:23:29 -07001375 }
1376
Adam Lesinski182f73f2013-12-05 16:48:06 -08001377 TimeZone zone = TimeZone.getTimeZone(tz);
1378 // Prevent reentrant calls from stepping on each other when writing
1379 // the time zone property
1380 boolean timeZoneWasChanged = false;
1381 synchronized (this) {
1382 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1383 if (current == null || !current.equals(zone.getID())) {
1384 if (localLOGV) {
1385 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1386 }
1387 timeZoneWasChanged = true;
1388 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1389 }
1390
1391 // Update the kernel timezone information
1392 // Kernel tracks time offsets as 'minutes west of GMT'
1393 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001394 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001395 }
1396
1397 TimeZone.setDefault(null);
1398
1399 if (timeZoneWasChanged) {
1400 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001401 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001402 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001403 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001404 intent.putExtra("time-zone", zone.getID());
1405 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1406 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001408
Adam Lesinski182f73f2013-12-05 16:48:06 -08001409 void removeImpl(PendingIntent operation) {
1410 if (operation == null) {
1411 return;
1412 }
1413 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001414 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001415 }
1416 }
1417
1418 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001419 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1420 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1421 int callingUid, String callingPackage) {
1422 // must be *either* PendingIntent or AlarmReceiver, but not both
1423 if ((operation == null && directReceiver == null)
1424 || (operation != null && directReceiver != null)) {
1425 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1426 // NB: previous releases failed silently here, so we are continuing to do the same
1427 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 return;
1429 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001430
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001431 // Sanity check the window length. This will catch people mistakenly
1432 // trying to pass an end-of-window timestamp rather than a duration.
1433 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1434 Slog.w(TAG, "Window length " + windowLength
1435 + "ms suspiciously long; limiting to 1 hour");
1436 windowLength = AlarmManager.INTERVAL_HOUR;
1437 }
1438
Christopher Tate498c6cb2014-11-17 16:09:27 -08001439 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001440 // seconds when the API expects milliseconds, or apps trying shenanigans
1441 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001442 final long minInterval = mConstants.MIN_INTERVAL;
1443 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001444 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001445 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001446 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001447 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001448 } else if (interval > mConstants.MAX_INTERVAL) {
1449 Slog.w(TAG, "Suspiciously long interval " + interval
1450 + " millis; clamping");
1451 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001452 }
1453
Christopher Tatee0a22b32013-07-11 14:43:13 -07001454 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1455 throw new IllegalArgumentException("Invalid alarm type " + type);
1456 }
1457
Christopher Tate5f221e82013-07-30 17:13:15 -07001458 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001459 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001460 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001461 + " pid=" + what);
1462 triggerAtTime = 0;
1463 }
1464
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001465 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001466 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1467 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001468 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001469 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1470
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001471 final long maxElapsed;
1472 if (windowLength == AlarmManager.WINDOW_EXACT) {
1473 maxElapsed = triggerElapsed;
1474 } else if (windowLength < 0) {
1475 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001476 // Fix this window in place, so that as time approaches we don't collapse it.
1477 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001478 } else {
1479 maxElapsed = triggerElapsed + windowLength;
1480 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001481
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001482 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001483 if (DEBUG_BATCH) {
1484 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001485 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001486 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001487 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001489 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001490 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1491 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494
Christopher Tate3e04b472013-10-21 17:51:31 -07001495 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001496 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1497 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1498 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001499 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001500 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1501 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001502 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001503 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001504 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1505 + " -- package not allowed to start");
1506 return;
1507 }
1508 } catch (RemoteException e) {
1509 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001510 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001511 setImplLocked(a, false, doValidate);
1512 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001513
Suprabh Shukla75edab12018-01-29 14:09:06 -08001514 private long getMinDelayForBucketLocked(int bucket) {
1515 // Return the minimum time that should elapse before an app in the specified bucket
1516 // can receive alarms again
1517 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) {
1518 return mConstants.APP_STANDBY_MIN_DELAYS[4];
1519 }
1520 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_RARE) {
1521 return mConstants.APP_STANDBY_MIN_DELAYS[3];
1522 }
1523 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_FREQUENT) {
1524 return mConstants.APP_STANDBY_MIN_DELAYS[2];
1525 }
1526 else if (bucket >= UsageStatsManager.STANDBY_BUCKET_WORKING_SET) {
1527 return mConstants.APP_STANDBY_MIN_DELAYS[1];
1528 }
1529 else return mConstants.APP_STANDBY_MIN_DELAYS[0];
1530 }
1531
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001532 /**
1533 * Adjusts the alarm delivery time based on the current app standby bucket.
1534 * @param alarm The alarm to adjust
1535 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001536 */
1537 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001538 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001539 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001540 }
1541 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001542 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001543 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001544 alarm.whenElapsed = alarm.expectedWhenElapsed;
1545 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1546 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001547 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001548 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001549 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001550 final long oldWhenElapsed = alarm.whenElapsed;
1551 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1552
Suprabh Shukla75edab12018-01-29 14:09:06 -08001553 final String sourcePackage = alarm.sourcePackage;
1554 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1555 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1556 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1557
1558 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1559 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1560 if (lastElapsed > 0) {
1561 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001562 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001563 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001564 } else {
1565 // app is now eligible to run alarms at the originally requested window.
1566 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001567 alarm.whenElapsed = alarm.expectedWhenElapsed;
1568 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001569 }
1570 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001571 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001572 }
1573
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001574 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1575 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001576 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001577 // The caller has given the time they want this to happen at, however we need
1578 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001579 // bring us out of idle at an earlier time.
1580 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001581 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001582 }
1583 // Add fuzz to make the alarm go off some time before the actual desired time.
1584 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001585 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001586 if (fuzz > 0) {
1587 if (mRandom == null) {
1588 mRandom = new Random();
1589 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001590 final int delta = mRandom.nextInt(fuzz);
1591 a.whenElapsed -= delta;
1592 if (false) {
1593 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1594 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1595 Slog.d(TAG, "Applied fuzz: " + fuzz);
1596 Slog.d(TAG, "Final delta: " + delta);
1597 Slog.d(TAG, "Final when: " + a.whenElapsed);
1598 }
1599 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001600 }
1601
1602 } else if (mPendingIdleUntil != null) {
1603 // We currently have an idle until alarm scheduled; if the new alarm has
1604 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001605 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1606 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1607 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001608 == 0) {
1609 mPendingWhileIdleAlarms.add(a);
1610 return;
1611 }
1612 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001613 if (RECORD_DEVICE_IDLE_ALARMS) {
1614 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1615 IdleDispatchEntry ent = new IdleDispatchEntry();
1616 ent.uid = a.uid;
1617 ent.pkg = a.operation.getCreatorPackage();
1618 ent.tag = a.operation.getTag("");
1619 ent.op = "SET";
1620 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1621 ent.argRealtime = a.whenElapsed;
1622 mAllowWhileIdleDispatches.add(ent);
1623 }
1624 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001625 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001626 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001627
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001628 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001629 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001630 }
1631
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001632 boolean needRebatch = false;
1633
1634 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001635 if (RECORD_DEVICE_IDLE_ALARMS) {
1636 if (mPendingIdleUntil == null) {
1637 IdleDispatchEntry ent = new IdleDispatchEntry();
1638 ent.uid = 0;
1639 ent.pkg = "START IDLE";
1640 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1641 mAllowWhileIdleDispatches.add(ent);
1642 }
1643 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001644 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1645 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1646 + " to " + a);
1647 }
1648
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001649 mPendingIdleUntil = a;
1650 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001651 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1652 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1653 mNextWakeFromIdle = a;
1654 // If this wake from idle is earlier than whatever was previously scheduled,
1655 // and we are currently idling, then we need to rebatch alarms in case the idle
1656 // until time needs to be updated.
1657 if (mPendingIdleUntil != null) {
1658 needRebatch = true;
1659 }
1660 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001661 }
1662
1663 if (!rebatching) {
1664 if (DEBUG_VALIDATE) {
1665 if (doValidate && !validateConsistencyLocked()) {
1666 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1667 + " when(hex)=" + Long.toHexString(a.when)
1668 + " whenElapsed=" + a.whenElapsed
1669 + " maxWhenElapsed=" + a.maxWhenElapsed
1670 + " interval=" + a.repeatInterval + " op=" + a.operation
1671 + " flags=0x" + Integer.toHexString(a.flags));
1672 rebatchAllAlarmsLocked(false);
1673 needRebatch = false;
1674 }
1675 }
1676
1677 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001678 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001679 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001680
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001681 rescheduleKernelAlarmsLocked();
1682 updateNextAlarmClockLocked();
1683 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001684 }
1685
Christopher Tate1d99c392017-12-07 16:54:04 -08001686 /**
1687 * System-process internal API
1688 */
1689 private final class LocalService implements AlarmManagerInternal {
1690 @Override
1691 public void removeAlarmsForUid(int uid) {
1692 synchronized (mLock) {
1693 removeLocked(uid);
1694 }
1695 }
1696 }
1697
1698 /**
1699 * Public-facing binder interface
1700 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001701 private final IBinder mService = new IAlarmManager.Stub() {
1702 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001703 public void set(String callingPackage,
1704 int type, long triggerAtTime, long windowLength, long interval, int flags,
1705 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1706 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001707 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001708
1709 // make sure the caller is not lying about which package should be blamed for
1710 // wakelock time spent in alarm delivery
1711 mAppOps.checkPackage(callingUid, callingPackage);
1712
1713 // Repeating alarms must use PendingIntent, not direct listener
1714 if (interval != 0) {
1715 if (directReceiver != null) {
1716 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1717 }
1718 }
1719
Adam Lesinski182f73f2013-12-05 16:48:06 -08001720 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001721 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001722 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001723 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001724 }
1725
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001726 // No incoming callers can request either WAKE_FROM_IDLE or
1727 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1728 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1729 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1730
1731 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1732 // manager when to come out of idle mode, which is only for DeviceIdleController.
1733 if (callingUid != Process.SYSTEM_UID) {
1734 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1735 }
1736
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001737 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001738 if (windowLength == AlarmManager.WINDOW_EXACT) {
1739 flags |= AlarmManager.FLAG_STANDALONE;
1740 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001741
1742 // If this alarm is for an alarm clock, then it must be standalone and we will
1743 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001744 if (alarmClock != null) {
1745 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001746
1747 // If the caller is a core system component or on the user's whitelist, and not calling
1748 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1749 // This means we will allow these alarms to go off as normal even while idle, with no
1750 // timing restrictions.
1751 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001752 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001753 || ((mAppStateTracker != null)
1754 && mAppStateTracker.isUidPowerSaveWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001755 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1756 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001757 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001758
Christopher Tate14a7bb02015-10-01 10:24:31 -07001759 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1760 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001761 }
Christopher Tate89779822012-08-31 14:40:03 -07001762
Adam Lesinski182f73f2013-12-05 16:48:06 -08001763 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001764 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001765 getContext().enforceCallingOrSelfPermission(
1766 "android.permission.SET_TIME",
1767 "setTime");
1768
Greg Hackmann0cab8962014-02-21 16:35:52 -08001769 if (mNativeData == 0) {
1770 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1771 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001772 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001773
1774 synchronized (mLock) {
1775 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001778
1779 @Override
1780 public void setTimeZone(String tz) {
1781 getContext().enforceCallingOrSelfPermission(
1782 "android.permission.SET_TIME_ZONE",
1783 "setTimeZone");
1784
1785 final long oldId = Binder.clearCallingIdentity();
1786 try {
1787 setTimeZoneImpl(tz);
1788 } finally {
1789 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001790 }
1791 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001792
Adam Lesinski182f73f2013-12-05 16:48:06 -08001793 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001794 public void remove(PendingIntent operation, IAlarmListener listener) {
1795 if (operation == null && listener == null) {
1796 Slog.w(TAG, "remove() with no intent or listener");
1797 return;
1798 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001799
Christopher Tate14a7bb02015-10-01 10:24:31 -07001800 synchronized (mLock) {
1801 removeLocked(operation, listener);
1802 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001803 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001804
Adam Lesinski182f73f2013-12-05 16:48:06 -08001805 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001806 public long getNextWakeFromIdleTime() {
1807 return getNextWakeFromIdleTimeImpl();
1808 }
1809
1810 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001811 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001812 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1813 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1814 "getNextAlarmClock", null);
1815
1816 return getNextAlarmClockImpl(userId);
1817 }
1818
1819 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001820 public long currentNetworkTimeMillis() {
1821 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1822 if (time.hasCache()) {
1823 return time.currentTimeMillis();
1824 } else {
1825 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1826 }
1827 }
1828
1829 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001830 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001831 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001832
1833 if (args.length > 0 && "--proto".equals(args[0])) {
1834 dumpProto(fd);
1835 } else {
1836 dumpImpl(pw);
1837 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001838 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001839 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001840
Adam Lesinski182f73f2013-12-05 16:48:06 -08001841 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 synchronized (mLock) {
1843 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001844 mConstants.dump(pw);
1845 pw.println();
1846
Makoto Onukie4918212018-02-06 11:30:15 -08001847 if (mAppStateTracker != null) {
1848 mAppStateTracker.dump(pw, " ");
1849 pw.println();
1850 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001851
Suprabh Shukla75edab12018-01-29 14:09:06 -08001852 pw.println(" App Standby Parole: " + mAppStandbyParole);
1853 pw.println();
1854
Christopher Tatee0a22b32013-07-11 14:43:13 -07001855 final long nowRTC = System.currentTimeMillis();
1856 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001857 final long nowUPTIME = SystemClock.uptimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001858 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001859
Dianne Hackborna750a632015-06-16 17:18:23 -07001860 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001861 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001862 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001863 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001864 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001865 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001866 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1867 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001868 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001869 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1870 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001871 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1872 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001873
1874 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1875 if (ssm != null) {
1876 pw.println();
1877 pw.print(" RuntimeStarted=");
1878 pw.print(sdf.format(
1879 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1880 if (ssm.isRuntimeRestarted()) {
1881 pw.print(" (Runtime restarted)");
1882 }
1883 pw.println();
1884 pw.print(" Runtime uptime (elapsed): ");
1885 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1886 pw.println();
1887 pw.print(" Runtime uptime (uptime): ");
1888 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1889 pw.println();
1890 }
1891
Dianne Hackbornc3527222015-05-13 14:03:20 -07001892 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001893 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001894 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001895 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1896 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001897 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001898 pw.print(" Max wakeup delay: ");
1899 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1900 pw.println();
1901 pw.print(" Time since last dispatch: ");
1902 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1903 pw.println();
1904 pw.print(" Next non-wakeup delivery time: ");
1905 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1906 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001907
1908 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1909 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001910 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001911 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001912 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001913 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001914 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1915 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001916 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001917 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1918 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001919 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001920 pw.print(" = "); pw.println(mLastWakeup);
1921 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1922 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001923 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001924
John Spurlock604a5ee2015-06-01 12:27:22 -04001925 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001926 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001927 final TreeSet<Integer> users = new TreeSet<>();
1928 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1929 users.add(mNextAlarmClockForUser.keyAt(i));
1930 }
1931 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1932 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1933 }
1934 for (int user : users) {
1935 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1936 final long time = next != null ? next.getTriggerTime() : 0;
1937 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001938 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001939 pw.print(" pendingSend:"); pw.print(pendingSend);
1940 pw.print(" time:"); pw.print(time);
1941 if (time > 0) {
1942 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1943 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1944 }
1945 pw.println();
1946 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001947 if (mAlarmBatches.size() > 0) {
1948 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001949 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001950 pw.println(mAlarmBatches.size());
1951 for (Batch b : mAlarmBatches) {
1952 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001953 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001954 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001955 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001956 pw.println();
1957 pw.println(" Pending user blocked background alarms: ");
1958 boolean blocked = false;
1959 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1960 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1961 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1962 blocked = true;
1963 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1964 }
1965 }
1966 if (!blocked) {
1967 pw.println(" none");
1968 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001969
Suprabh Shukla75edab12018-01-29 14:09:06 -08001970 pw.println(" mLastAlarmDeliveredForPackage:");
1971 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
1972 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
1973 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
1974 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
1975 pw.println();
1976 }
1977 pw.println();
1978
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001979 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001980 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001981 pw.println(" Idle mode state:");
1982 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001983 if (mPendingIdleUntil != null) {
1984 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001985 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001986 } else {
1987 pw.println("null");
1988 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001989 pw.println(" Pending alarms:");
1990 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001991 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001992 if (mNextWakeFromIdle != null) {
1993 pw.println();
1994 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001995 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001996 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001997
1998 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001999 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002000 if (mPendingNonWakeupAlarms.size() > 0) {
2001 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002002 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002003 } else {
2004 pw.println("(none)");
2005 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002006 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002007 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2008 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002009 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002010 pw.print(", max non-interactive time: ");
2011 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2012 pw.println();
2013
2014 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002015 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002016 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2017 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2018 pw.print(" Listener send count: "); pw.println(mListenerCount);
2019 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002020 pw.println();
2021
Christopher Tate7f2a0352015-12-08 10:24:33 -08002022 if (mInFlight.size() > 0) {
2023 pw.println("Outstanding deliveries:");
2024 for (int i = 0; i < mInFlight.size(); i++) {
2025 pw.print(" #"); pw.print(i); pw.print(": ");
2026 pw.println(mInFlight.get(i));
2027 }
2028 pw.println();
2029 }
2030
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002031 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002032 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002033 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002034 pw.print(" UID ");
2035 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2036 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002037 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002038 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2039 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2040
2041 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2042 pw.print(" Next allowed:");
2043 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2044 pw.print(" (");
2045 TimeUtils.formatDuration(minInterval, 0, pw);
2046 pw.print(")");
2047
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002048 pw.println();
2049 }
2050 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002051
2052 pw.print(" mUseAllowWhileIdleShortTime: [");
2053 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2054 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2055 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2056 pw.print(" ");
2057 }
2058 }
2059 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002060 pw.println();
2061
Dianne Hackborn81038902012-11-26 17:04:09 -08002062 if (mLog.dump(pw, " Recent problems", " ")) {
2063 pw.println();
2064 }
2065
2066 final FilterStats[] topFilters = new FilterStats[10];
2067 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2068 @Override
2069 public int compare(FilterStats lhs, FilterStats rhs) {
2070 if (lhs.aggregateTime < rhs.aggregateTime) {
2071 return 1;
2072 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2073 return -1;
2074 }
2075 return 0;
2076 }
2077 };
2078 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002079 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002080 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2081 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2082 for (int ip=0; ip<uidStats.size(); ip++) {
2083 BroadcastStats bs = uidStats.valueAt(ip);
2084 for (int is=0; is<bs.filterStats.size(); is++) {
2085 FilterStats fs = bs.filterStats.valueAt(is);
2086 int pos = len > 0
2087 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2088 if (pos < 0) {
2089 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002090 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002091 if (pos < topFilters.length) {
2092 int copylen = topFilters.length - pos - 1;
2093 if (copylen > 0) {
2094 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2095 }
2096 topFilters[pos] = fs;
2097 if (len < topFilters.length) {
2098 len++;
2099 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002100 }
2101 }
2102 }
2103 }
2104 if (len > 0) {
2105 pw.println(" Top Alarms:");
2106 for (int i=0; i<len; i++) {
2107 FilterStats fs = topFilters[i];
2108 pw.print(" ");
2109 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2110 TimeUtils.formatDuration(fs.aggregateTime, pw);
2111 pw.print(" running, "); pw.print(fs.numWakeup);
2112 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002113 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2114 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002115 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002116 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002117 pw.println();
2118 }
2119 }
2120
2121 pw.println(" ");
2122 pw.println(" Alarm Stats:");
2123 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002124 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2125 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2126 for (int ip=0; ip<uidStats.size(); ip++) {
2127 BroadcastStats bs = uidStats.valueAt(ip);
2128 pw.print(" ");
2129 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2130 UserHandle.formatUid(pw, bs.mUid);
2131 pw.print(":");
2132 pw.print(bs.mPackageName);
2133 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2134 pw.print(" running, "); pw.print(bs.numWakeup);
2135 pw.println(" wakeups:");
2136 tmpFilters.clear();
2137 for (int is=0; is<bs.filterStats.size(); is++) {
2138 tmpFilters.add(bs.filterStats.valueAt(is));
2139 }
2140 Collections.sort(tmpFilters, comparator);
2141 for (int i=0; i<tmpFilters.size(); i++) {
2142 FilterStats fs = tmpFilters.get(i);
2143 pw.print(" ");
2144 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2145 TimeUtils.formatDuration(fs.aggregateTime, pw);
2146 pw.print(" "); pw.print(fs.numWakeup);
2147 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002148 pw.print(" alarms, last ");
2149 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2150 pw.println(":");
2151 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002152 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002153 pw.println();
2154 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002155 }
2156 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002157 pw.println();
2158 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002159
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002160 if (RECORD_DEVICE_IDLE_ALARMS) {
2161 pw.println();
2162 pw.println(" Allow while idle dispatches:");
2163 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2164 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2165 pw.print(" ");
2166 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2167 pw.print(": ");
2168 UserHandle.formatUid(pw, ent.uid);
2169 pw.print(":");
2170 pw.println(ent.pkg);
2171 if (ent.op != null) {
2172 pw.print(" ");
2173 pw.print(ent.op);
2174 pw.print(" / ");
2175 pw.print(ent.tag);
2176 if (ent.argRealtime != 0) {
2177 pw.print(" (");
2178 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2179 pw.print(")");
2180 }
2181 pw.println();
2182 }
2183 }
2184 }
2185
Christopher Tate18a75f12013-07-01 18:18:59 -07002186 if (WAKEUP_STATS) {
2187 pw.println();
2188 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002189 long last = -1;
2190 for (WakeupEvent event : mRecentWakeups) {
2191 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2192 pw.print('|');
2193 if (last < 0) {
2194 pw.print('0');
2195 } else {
2196 pw.print(event.when - last);
2197 }
2198 last = event.when;
2199 pw.print('|'); pw.print(event.uid);
2200 pw.print('|'); pw.print(event.action);
2201 pw.println();
2202 }
2203 pw.println();
2204 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002205 }
2206 }
2207
Kweku Adams61e03292017-10-19 14:27:12 -07002208 void dumpProto(FileDescriptor fd) {
2209 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2210
2211 synchronized (mLock) {
2212 final long nowRTC = System.currentTimeMillis();
2213 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002214 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2215 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2216 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002217 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002218 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002219 mLastTimeChangeRealtime);
2220
Yi Jin2b30f322018-02-20 15:41:47 -08002221 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002222
Makoto Onukie4918212018-02-06 11:30:15 -08002223 if (mAppStateTracker != null) {
2224 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002225 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002226 }
Kweku Adams61e03292017-10-19 14:27:12 -07002227
Yi Jin2b30f322018-02-20 15:41:47 -08002228 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002229 if (!mInteractive) {
2230 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002231 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002232 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002233 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002234 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002235 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002236 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002237 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002238 nowElapsed - mNextNonWakeupDeliveryTime);
2239 }
2240
Yi Jin2b30f322018-02-20 15:41:47 -08002241 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002242 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002243 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002244 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002245 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002246 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002247 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002248 nowElapsed - mLastWakeupSet);
Yi Jin2b30f322018-02-20 15:41:47 -08002249 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002250
2251 final TreeSet<Integer> users = new TreeSet<>();
2252 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2253 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2254 users.add(mNextAlarmClockForUser.keyAt(i));
2255 }
2256 final int pendingSendNextAlarmClockChangedForUserSize =
2257 mPendingSendNextAlarmClockChangedForUser.size();
2258 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2259 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2260 }
2261 for (int user : users) {
2262 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2263 final long time = next != null ? next.getTriggerTime() : 0;
2264 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002265 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002266 proto.write(AlarmClockMetadataProto.USER, user);
2267 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2268 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2269 proto.end(aToken);
2270 }
2271 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002272 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002273 nowElapsed, nowRTC);
2274 }
2275 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2276 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2277 if (blockedAlarms != null) {
2278 for (Alarm a : blockedAlarms) {
2279 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002280 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002281 nowElapsed, nowRTC);
2282 }
2283 }
2284 }
2285 if (mPendingIdleUntil != null) {
2286 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002287 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002288 }
2289 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002290 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002291 nowElapsed, nowRTC);
2292 }
2293 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002294 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002295 nowElapsed, nowRTC);
2296 }
2297
2298 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002299 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002300 nowElapsed, nowRTC);
2301 }
2302
Yi Jin2b30f322018-02-20 15:41:47 -08002303 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2304 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2305 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2306 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002307 mNonInteractiveTime);
2308
Yi Jin2b30f322018-02-20 15:41:47 -08002309 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2310 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2311 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2312 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2313 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002314
2315 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002316 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002317 }
2318
Kweku Adams61e03292017-10-19 14:27:12 -07002319 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2320 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002321 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002322 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2323 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2324
Yi Jin2b30f322018-02-20 15:41:47 -08002325 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2326 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2327 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002328 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002329 proto.end(token);
2330 }
2331
Makoto Onukiadb50d82018-01-29 16:20:30 -08002332 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2333 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002334 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002335 mUseAllowWhileIdleShortTime.keyAt(i));
2336 }
2337 }
2338
Yi Jin2b30f322018-02-20 15:41:47 -08002339 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002340
2341 final FilterStats[] topFilters = new FilterStats[10];
2342 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2343 @Override
2344 public int compare(FilterStats lhs, FilterStats rhs) {
2345 if (lhs.aggregateTime < rhs.aggregateTime) {
2346 return 1;
2347 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2348 return -1;
2349 }
2350 return 0;
2351 }
2352 };
2353 int len = 0;
2354 // Get the top 10 FilterStats, ordered by aggregateTime.
2355 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2356 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2357 for (int ip = 0; ip < uidStats.size(); ++ip) {
2358 BroadcastStats bs = uidStats.valueAt(ip);
2359 for (int is = 0; is < bs.filterStats.size(); ++is) {
2360 FilterStats fs = bs.filterStats.valueAt(is);
2361 int pos = len > 0
2362 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2363 if (pos < 0) {
2364 pos = -pos - 1;
2365 }
2366 if (pos < topFilters.length) {
2367 int copylen = topFilters.length - pos - 1;
2368 if (copylen > 0) {
2369 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2370 }
2371 topFilters[pos] = fs;
2372 if (len < topFilters.length) {
2373 len++;
2374 }
2375 }
2376 }
2377 }
2378 }
2379 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002380 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002381 FilterStats fs = topFilters[i];
2382
Yi Jin2b30f322018-02-20 15:41:47 -08002383 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2384 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002385 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002386 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002387
2388 proto.end(token);
2389 }
2390
2391 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2392 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2393 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2394 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002395 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002396
2397 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002398 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002399
2400 // uidStats is an ArrayMap, which we can't sort.
2401 tmpFilters.clear();
2402 for (int is = 0; is < bs.filterStats.size(); ++is) {
2403 tmpFilters.add(bs.filterStats.valueAt(is));
2404 }
2405 Collections.sort(tmpFilters, comparator);
2406 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002407 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002408 }
2409
2410 proto.end(token);
2411 }
2412 }
2413
2414 if (RECORD_DEVICE_IDLE_ALARMS) {
2415 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2416 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2417 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002418 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002419
2420 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2421 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2422 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2423 proto.write(IdleDispatchEntryProto.OP, ent.op);
2424 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2425 ent.elapsedRealtime);
2426 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2427
2428 proto.end(token);
2429 }
2430 }
2431
2432 if (WAKEUP_STATS) {
2433 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002434 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002435 proto.write(WakeupEventProto.UID, event.uid);
2436 proto.write(WakeupEventProto.ACTION, event.action);
2437 proto.write(WakeupEventProto.WHEN, event.when);
2438 proto.end(token);
2439 }
2440 }
2441 }
2442
2443 proto.flush();
2444 }
2445
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002446 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002447 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2448 PrintWriter pw = new PrintWriter(bs);
2449 final long nowRTC = System.currentTimeMillis();
2450 final long nowELAPSED = SystemClock.elapsedRealtime();
2451 final int NZ = mAlarmBatches.size();
2452 for (int iz = 0; iz < NZ; iz++) {
2453 Batch bz = mAlarmBatches.get(iz);
2454 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002455 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002456 pw.flush();
2457 Slog.v(TAG, bs.toString());
2458 bs.reset();
2459 }
2460 }
2461
2462 private boolean validateConsistencyLocked() {
2463 if (DEBUG_VALIDATE) {
2464 long lastTime = Long.MIN_VALUE;
2465 final int N = mAlarmBatches.size();
2466 for (int i = 0; i < N; i++) {
2467 Batch b = mAlarmBatches.get(i);
2468 if (b.start >= lastTime) {
2469 // duplicate start times are okay because of standalone batches
2470 lastTime = b.start;
2471 } else {
2472 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002473 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2474 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002475 return false;
2476 }
2477 }
2478 }
2479 return true;
2480 }
2481
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002482 private Batch findFirstWakeupBatchLocked() {
2483 final int N = mAlarmBatches.size();
2484 for (int i = 0; i < N; i++) {
2485 Batch b = mAlarmBatches.get(i);
2486 if (b.hasWakeups()) {
2487 return b;
2488 }
2489 }
2490 return null;
2491 }
2492
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002493 long getNextWakeFromIdleTimeImpl() {
2494 synchronized (mLock) {
2495 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2496 }
2497 }
2498
2499 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002500 synchronized (mLock) {
2501 return mNextAlarmClockForUser.get(userId);
2502 }
2503 }
2504
2505 /**
2506 * Recomputes the next alarm clock for all users.
2507 */
2508 private void updateNextAlarmClockLocked() {
2509 if (!mNextAlarmClockMayChange) {
2510 return;
2511 }
2512 mNextAlarmClockMayChange = false;
2513
Jose Lima235510e2014-08-13 12:50:01 -07002514 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002515 nextForUser.clear();
2516
2517 final int N = mAlarmBatches.size();
2518 for (int i = 0; i < N; i++) {
2519 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2520 final int M = alarms.size();
2521
2522 for (int j = 0; j < M; j++) {
2523 Alarm a = alarms.get(j);
2524 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002525 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002526 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002527
2528 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002529 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002530 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002531 " for user " + userId);
2532 }
2533
2534 // Alarms and batches are sorted by time, no need to compare times here.
2535 if (nextForUser.get(userId) == null) {
2536 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002537 } else if (a.alarmClock.equals(current)
2538 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2539 // same/earlier time and it's the one we cited before, so stick with it
2540 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002541 }
2542 }
2543 }
2544 }
2545
2546 // Update mNextAlarmForUser with new values.
2547 final int NN = nextForUser.size();
2548 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002549 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002550 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002551 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002552 if (!newAlarm.equals(currentAlarm)) {
2553 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2554 }
2555 }
2556
2557 // Remove users without any alarm clocks scheduled.
2558 final int NNN = mNextAlarmClockForUser.size();
2559 for (int i = NNN - 1; i >= 0; i--) {
2560 int userId = mNextAlarmClockForUser.keyAt(i);
2561 if (nextForUser.get(userId) == null) {
2562 updateNextAlarmInfoForUserLocked(userId, null);
2563 }
2564 }
2565 }
2566
Jose Lima235510e2014-08-13 12:50:01 -07002567 private void updateNextAlarmInfoForUserLocked(int userId,
2568 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002569 if (alarmClock != null) {
2570 if (DEBUG_ALARM_CLOCK) {
2571 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002572 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002573 }
2574 mNextAlarmClockForUser.put(userId, alarmClock);
2575 } else {
2576 if (DEBUG_ALARM_CLOCK) {
2577 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2578 }
2579 mNextAlarmClockForUser.remove(userId);
2580 }
2581
2582 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2583 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2584 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2585 }
2586
2587 /**
2588 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2589 * for which alarm clocks have changed since the last call to this.
2590 *
2591 * Do not call with a lock held. Only call from mHandler's thread.
2592 *
2593 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2594 */
2595 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002596 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002597 pendingUsers.clear();
2598
2599 synchronized (mLock) {
2600 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2601 for (int i = 0; i < N; i++) {
2602 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2603 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2604 }
2605 mPendingSendNextAlarmClockChangedForUser.clear();
2606 }
2607
2608 final int N = pendingUsers.size();
2609 for (int i = 0; i < N; i++) {
2610 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002611 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002612 Settings.System.putStringForUser(getContext().getContentResolver(),
2613 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002614 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002615 userId);
2616
2617 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2618 new UserHandle(userId));
2619 }
2620 }
2621
2622 /**
2623 * Formats an alarm like platform/packages/apps/DeskClock used to.
2624 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002625 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2626 int userId) {
2627 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002628 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2629 return (info == null) ? "" :
2630 DateFormat.format(pattern, info.getTriggerTime()).toString();
2631 }
2632
Adam Lesinski182f73f2013-12-05 16:48:06 -08002633 void rescheduleKernelAlarmsLocked() {
2634 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2635 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002636 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002637 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002638 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002639 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002640 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002641 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002642 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002643 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002644 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002645 if (firstBatch != firstWakeup) {
2646 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002647 }
2648 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002649 if (mPendingNonWakeupAlarms.size() > 0) {
2650 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2651 nextNonWakeup = mNextNonWakeupDeliveryTime;
2652 }
2653 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002654 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002655 mNextNonWakeup = nextNonWakeup;
2656 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2657 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002658 }
2659
Christopher Tate14a7bb02015-10-01 10:24:31 -07002660 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002661 if (operation == null && directReceiver == null) {
2662 if (localLOGV) {
2663 Slog.w(TAG, "requested remove() of null operation",
2664 new RuntimeException("here"));
2665 }
2666 return;
2667 }
2668
Adam Lesinski182f73f2013-12-05 16:48:06 -08002669 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002670 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002671 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2672 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002673 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002674 if (b.size() == 0) {
2675 mAlarmBatches.remove(i);
2676 }
2677 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002678 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002679 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002680 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2681 mPendingWhileIdleAlarms.remove(i);
2682 }
2683 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002684 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2685 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2686 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2687 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2688 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2689 alarmsForUid.remove(j);
2690 }
2691 }
2692 if (alarmsForUid.size() == 0) {
2693 mPendingBackgroundAlarms.removeAt(i);
2694 }
2695 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002696 if (didRemove) {
2697 if (DEBUG_BATCH) {
2698 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2699 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002700 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002701 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002702 mPendingIdleUntil = null;
2703 restorePending = true;
2704 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002705 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002706 mNextWakeFromIdle = null;
2707 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002708 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002709 if (restorePending) {
2710 restorePendingWhileIdleAlarmsLocked();
2711 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002712 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002713 }
2714 }
2715
Christopher Tate1d99c392017-12-07 16:54:04 -08002716 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002717 if (uid == Process.SYSTEM_UID) {
2718 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2719 return;
2720 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002721 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002722 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002723 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2724 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002725 didRemove |= b.remove(whichAlarms);
2726 if (b.size() == 0) {
2727 mAlarmBatches.remove(i);
2728 }
2729 }
2730 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2731 final Alarm a = mPendingWhileIdleAlarms.get(i);
2732 if (a.uid == uid) {
2733 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2734 mPendingWhileIdleAlarms.remove(i);
2735 }
2736 }
2737 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2738 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2739 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2740 if (alarmsForUid.get(j).uid == uid) {
2741 alarmsForUid.remove(j);
2742 }
2743 }
2744 if (alarmsForUid.size() == 0) {
2745 mPendingBackgroundAlarms.removeAt(i);
2746 }
2747 }
2748 if (didRemove) {
2749 if (DEBUG_BATCH) {
2750 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2751 }
2752 rebatchAllAlarmsLocked(true);
2753 rescheduleKernelAlarmsLocked();
2754 updateNextAlarmClockLocked();
2755 }
2756 }
2757
2758 void removeLocked(final String packageName) {
2759 if (packageName == null) {
2760 if (localLOGV) {
2761 Slog.w(TAG, "requested remove() of null packageName",
2762 new RuntimeException("here"));
2763 }
2764 return;
2765 }
2766
2767 boolean didRemove = false;
2768 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002769 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002770 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2771 Batch b = mAlarmBatches.get(i);
2772 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002773 if (b.size() == 0) {
2774 mAlarmBatches.remove(i);
2775 }
2776 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002777 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2778 if (oldHasTick != newHasTick) {
2779 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2780 }
2781
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002782 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002783 final Alarm a = mPendingWhileIdleAlarms.get(i);
2784 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002785 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2786 mPendingWhileIdleAlarms.remove(i);
2787 }
2788 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002789 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2790 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2791 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2792 if (alarmsForUid.get(j).matches(packageName)) {
2793 alarmsForUid.remove(j);
2794 }
2795 }
2796 if (alarmsForUid.size() == 0) {
2797 mPendingBackgroundAlarms.removeAt(i);
2798 }
2799 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002800 if (didRemove) {
2801 if (DEBUG_BATCH) {
2802 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2803 }
2804 rebatchAllAlarmsLocked(true);
2805 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002806 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002807 }
2808 }
2809
Christopher Tate1d99c392017-12-07 16:54:04 -08002810 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002811 if (uid == Process.SYSTEM_UID) {
2812 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2813 return;
2814 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002815 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002816 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2817 try {
2818 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2819 uid, a.packageName)) {
2820 return true;
2821 }
2822 } catch (RemoteException e) { /* fall through */}
2823 return false;
2824 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002825 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2826 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002827 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002828 if (b.size() == 0) {
2829 mAlarmBatches.remove(i);
2830 }
2831 }
2832 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2833 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002834 if (a.uid == uid) {
2835 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2836 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002837 }
2838 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002839 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2840 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2841 mPendingBackgroundAlarms.removeAt(i);
2842 }
2843 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002844 if (didRemove) {
2845 if (DEBUG_BATCH) {
2846 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2847 }
2848 rebatchAllAlarmsLocked(true);
2849 rescheduleKernelAlarmsLocked();
2850 updateNextAlarmClockLocked();
2851 }
2852 }
2853
Adam Lesinski182f73f2013-12-05 16:48:06 -08002854 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002855 if (userHandle == UserHandle.USER_SYSTEM) {
2856 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2857 return;
2858 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002859 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002860 final Predicate<Alarm> whichAlarms =
2861 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002862 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2863 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002864 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002865 if (b.size() == 0) {
2866 mAlarmBatches.remove(i);
2867 }
2868 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002869 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002870 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002871 == userHandle) {
2872 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2873 mPendingWhileIdleAlarms.remove(i);
2874 }
2875 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002876 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2877 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2878 mPendingBackgroundAlarms.removeAt(i);
2879 }
2880 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002881 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2882 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2883 mLastAllowWhileIdleDispatch.removeAt(i);
2884 }
2885 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002886
2887 if (didRemove) {
2888 if (DEBUG_BATCH) {
2889 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2890 }
2891 rebatchAllAlarmsLocked(true);
2892 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002893 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002894 }
2895 }
2896
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002897 void interactiveStateChangedLocked(boolean interactive) {
2898 if (mInteractive != interactive) {
2899 mInteractive = interactive;
2900 final long nowELAPSED = SystemClock.elapsedRealtime();
2901 if (interactive) {
2902 if (mPendingNonWakeupAlarms.size() > 0) {
2903 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2904 mTotalDelayTime += thisDelayTime;
2905 if (mMaxDelayTime < thisDelayTime) {
2906 mMaxDelayTime = thisDelayTime;
2907 }
2908 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2909 mPendingNonWakeupAlarms.clear();
2910 }
2911 if (mNonInteractiveStartTime > 0) {
2912 long dur = nowELAPSED - mNonInteractiveStartTime;
2913 if (dur > mNonInteractiveTime) {
2914 mNonInteractiveTime = dur;
2915 }
2916 }
2917 } else {
2918 mNonInteractiveStartTime = nowELAPSED;
2919 }
2920 }
2921 }
2922
Adam Lesinski182f73f2013-12-05 16:48:06 -08002923 boolean lookForPackageLocked(String packageName) {
2924 for (int i = 0; i < mAlarmBatches.size(); i++) {
2925 Batch b = mAlarmBatches.get(i);
2926 if (b.hasPackage(packageName)) {
2927 return true;
2928 }
2929 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002930 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002931 final Alarm a = mPendingWhileIdleAlarms.get(i);
2932 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002933 return true;
2934 }
2935 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002936 return false;
2937 }
2938
2939 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002940 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002941 // The kernel never triggers alarms with negative wakeup times
2942 // so we ensure they are positive.
2943 long alarmSeconds, alarmNanoseconds;
2944 if (when < 0) {
2945 alarmSeconds = 0;
2946 alarmNanoseconds = 0;
2947 } else {
2948 alarmSeconds = when / 1000;
2949 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2950 }
Kweku Adams61e03292017-10-19 14:27:12 -07002951
Christopher Tate8b98ade2018-02-09 11:13:19 -08002952 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2953 if (result != 0) {
2954 final long nowElapsed = SystemClock.elapsedRealtime();
2955 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2956 + " type=" + type + " when=" + when
2957 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2958 + "), ret = " + result + " = " + Os.strerror(result));
2959 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002960 } else {
2961 Message msg = Message.obtain();
2962 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002963
Adam Lesinski182f73f2013-12-05 16:48:06 -08002964 mHandler.removeMessages(ALARM_EVENT);
2965 mHandler.sendMessageAtTime(msg, when);
2966 }
2967 }
2968
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002969 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002970 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002971 for (int i=list.size()-1; i>=0; i--) {
2972 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002973 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2974 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002975 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002976 }
2977 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002978
2979 private static final String labelForType(int type) {
2980 switch (type) {
2981 case RTC: return "RTC";
2982 case RTC_WAKEUP : return "RTC_WAKEUP";
2983 case ELAPSED_REALTIME : return "ELAPSED";
2984 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002985 }
2986 return "--unknown--";
2987 }
2988
2989 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002990 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002991 for (int i=list.size()-1; i>=0; i--) {
2992 Alarm a = list.get(i);
2993 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002994 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2995 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002996 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002997 }
2998 }
2999
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003000 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003001 final boolean allowWhileIdle = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003002 if (alarm.alarmClock != null) {
3003 // Don't block alarm clocks
3004 return false;
3005 }
3006 if (alarm.operation != null
3007 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
3008 // Don't block starting foreground components
3009 return false;
3010 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003011 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003012 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003013 return (mAppStateTracker != null) &&
3014 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage, allowWhileIdle);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003015 }
3016
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003017 private native long init();
3018 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003019 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003020 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003021 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003022 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003023
Makoto Onukiadb50d82018-01-29 16:20:30 -08003024 private long getWhileIdleMinIntervalLocked(int uid) {
3025 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003026 final boolean ebs = (mAppStateTracker != null)
3027 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003028 if (!dozing && !ebs) {
3029 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3030 }
3031 if (dozing) {
3032 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3033 }
3034 if (mUseAllowWhileIdleShortTime.get(uid)) {
3035 // if the last allow-while-idle went off while uid was fg, or the uid
3036 // recently came into fg, don't block the alarm for long.
3037 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3038 }
3039 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3040 }
3041
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003042 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003043 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003044 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003045 // batches are temporally sorted, so we need only pull from the
3046 // start of the list until we either empty it or hit a batch
3047 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003048 while (mAlarmBatches.size() > 0) {
3049 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003050 if (batch.start > nowELAPSED) {
3051 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003052 break;
3053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003054
Christopher Tatee0a22b32013-07-11 14:43:13 -07003055 // We will (re)schedule some alarms now; don't let that interfere
3056 // with delivery of this current batch
3057 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003058
Christopher Tatee0a22b32013-07-11 14:43:13 -07003059 final int N = batch.size();
3060 for (int i = 0; i < N; i++) {
3061 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003062
3063 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3064 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
3065 // schedule such alarms.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08003066 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, 0);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003067 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003068 if (nowELAPSED < minTime) {
3069 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3070 // alarm went off for this app. Reschedule the alarm to be in the
3071 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003072 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003073 if (alarm.maxWhenElapsed < minTime) {
3074 alarm.maxWhenElapsed = minTime;
3075 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003076 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003077 if (RECORD_DEVICE_IDLE_ALARMS) {
3078 IdleDispatchEntry ent = new IdleDispatchEntry();
3079 ent.uid = alarm.uid;
3080 ent.pkg = alarm.operation.getCreatorPackage();
3081 ent.tag = alarm.operation.getTag("");
3082 ent.op = "RESCHEDULE";
3083 ent.elapsedRealtime = nowELAPSED;
3084 ent.argRealtime = lastTime;
3085 mAllowWhileIdleDispatches.add(ent);
3086 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003087 setImplLocked(alarm, true, false);
3088 continue;
3089 }
3090 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003091 if (isBackgroundRestricted(alarm)) {
3092 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3093 if (DEBUG_BG_LIMIT) {
3094 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3095 }
3096 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3097 if (alarmsForUid == null) {
3098 alarmsForUid = new ArrayList<>();
3099 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3100 }
3101 alarmsForUid.add(alarm);
3102 continue;
3103 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003104
Christopher Tatee0a22b32013-07-11 14:43:13 -07003105 alarm.count = 1;
3106 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003107 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3108 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003109 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003110 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003111 if (mPendingIdleUntil == alarm) {
3112 mPendingIdleUntil = null;
3113 rebatchAllAlarmsLocked(false);
3114 restorePendingWhileIdleAlarmsLocked();
3115 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003116 if (mNextWakeFromIdle == alarm) {
3117 mNextWakeFromIdle = null;
3118 rebatchAllAlarmsLocked(false);
3119 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003120
3121 // Recurring alarms may have passed several alarm intervals while the
3122 // phone was asleep or off, so pass a trigger count when sending them.
3123 if (alarm.repeatInterval > 0) {
3124 // this adjustment will be zero if we're late by
3125 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003126 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003127
3128 // Also schedule its next recurrence
3129 final long delta = alarm.count * alarm.repeatInterval;
3130 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003131 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003132 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003133 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3134 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003135 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003136
Christopher Tate864d42e2014-12-02 11:48:53 -08003137 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003138 hasWakeup = true;
3139 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003140
3141 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3142 if (alarm.alarmClock != null) {
3143 mNextAlarmClockMayChange = true;
3144 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003145 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003146 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003147
Christopher Tate1590f1e2014-10-02 17:27:57 -07003148 // This is a new alarm delivery set; bump the sequence number to indicate that
3149 // all apps' alarm delivery classes should be recalculated.
3150 mCurrentSeq++;
3151 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003152 Collections.sort(triggerList, mAlarmDispatchComparator);
3153
3154 if (localLOGV) {
3155 for (int i=0; i<triggerList.size(); i++) {
3156 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3157 }
3158 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003159
3160 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003161 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003162
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003163 /**
3164 * This Comparator sorts Alarms into increasing time order.
3165 */
3166 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3167 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003168 long when1 = a1.whenElapsed;
3169 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003170 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003171 return 1;
3172 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003173 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003174 return -1;
3175 }
3176 return 0;
3177 }
3178 }
Kweku Adams61e03292017-10-19 14:27:12 -07003179
Makoto Onuki2206af32017-11-21 16:25:35 -08003180 @VisibleForTesting
3181 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003182 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003183 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003184 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003185 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003186 public final IAlarmListener listener;
3187 public final String listenerTag;
3188 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003189 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003190 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003191 public final AlarmManager.AlarmClockInfo alarmClock;
3192 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003193 public final int creatorUid;
3194 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003195 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003196 public int count;
3197 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003198 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003199 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003200 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003201 // Expected alarm expiry time before app standby deferring is applied.
3202 public long expectedWhenElapsed;
3203 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003204 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003205 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003206
Christopher Tate3e04b472013-10-21 17:51:31 -07003207 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003208 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3209 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3210 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003211 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003212 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003213 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3214 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003215 when = _when;
3216 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003217 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003218 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003219 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003220 repeatInterval = _interval;
3221 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003222 listener = _rec;
3223 listenerTag = _listenerTag;
3224 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003225 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003226 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003227 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003228 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003229 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003230 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003231 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003233
Christopher Tate14a7bb02015-10-01 10:24:31 -07003234 public static String makeTag(PendingIntent pi, String tag, int type) {
3235 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3236 ? "*walarm*:" : "*alarm*:";
3237 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3238 }
3239
3240 public WakeupEvent makeWakeupEvent(long nowRTC) {
3241 return new WakeupEvent(nowRTC, creatorUid,
3242 (operation != null)
3243 ? operation.getIntent().getAction()
3244 : ("<listener>:" + listenerTag));
3245 }
3246
3247 // Returns true if either matches
3248 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3249 return (operation != null)
3250 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003251 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003252 }
3253
3254 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003255 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003256 }
3257
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003259 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003260 StringBuilder sb = new StringBuilder(128);
3261 sb.append("Alarm{");
3262 sb.append(Integer.toHexString(System.identityHashCode(this)));
3263 sb.append(" type ");
3264 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003265 sb.append(" when ");
3266 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003267 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003268 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003269 sb.append('}');
3270 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 }
3272
Kweku Adams61e03292017-10-19 14:27:12 -07003273 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003274 SimpleDateFormat sdf) {
3275 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003276 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003277 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003278 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3279 expectedWhenElapsed, nowELAPSED, pw);
3280 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3281 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003282 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3283 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003284 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3285 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003286 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003287 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003288 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003289 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003290 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003291 }
3292 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003293 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003294 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003295 pw.print(" count="); pw.print(count);
3296 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003297 if (alarmClock != null) {
3298 pw.print(prefix); pw.println("Alarm clock:");
3299 pw.print(prefix); pw.print(" triggerTime=");
3300 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3301 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3302 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003303 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003304 if (listener != null) {
3305 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3306 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 }
Kweku Adams61e03292017-10-19 14:27:12 -07003308
3309 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3310 long nowRTC) {
3311 final long token = proto.start(fieldId);
3312
3313 proto.write(AlarmProto.TAG, statsTag);
3314 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003315 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003316 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3317 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3318 proto.write(AlarmProto.COUNT, count);
3319 proto.write(AlarmProto.FLAGS, flags);
3320 if (alarmClock != null) {
3321 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3322 }
3323 if (operation != null) {
3324 operation.writeToProto(proto, AlarmProto.OPERATION);
3325 }
3326 if (listener != null) {
3327 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3328 }
3329
3330 proto.end(token);
3331 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003333
Christopher Tatee0a22b32013-07-11 14:43:13 -07003334 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3335 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003336 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3337 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003338 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003339 break;
3340 }
3341
Christopher Tatee0a22b32013-07-11 14:43:13 -07003342 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003343 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3344 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003345 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003346 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003347 }
3348 }
3349
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003350 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3351 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3352 if (timeSinceOn < 5*60*1000) {
3353 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3354 return 2*60*1000;
3355 } else if (timeSinceOn < 30*60*1000) {
3356 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3357 return 15*60*1000;
3358 } else {
3359 // Otherwise, we will delay by at most an hour.
3360 return 60*60*1000;
3361 }
3362 }
3363
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003364 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003365 if (duration < 15*60*1000) {
3366 // If the duration until the time is less than 15 minutes, the maximum fuzz
3367 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003368 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003369 } else if (duration < 90*60*1000) {
3370 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3371 return 15*60*1000;
3372 } else {
3373 // Otherwise, we will fuzz by at most half an hour.
3374 return 30*60*1000;
3375 }
3376 }
3377
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003378 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3379 if (mInteractive) {
3380 return false;
3381 }
3382 if (mLastAlarmDeliveryTime <= 0) {
3383 return false;
3384 }
minho.choo649acab2014-12-12 16:13:55 +09003385 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003386 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3387 // and the next delivery time is in the past, then just deliver them all. This
3388 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3389 return false;
3390 }
3391 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3392 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3393 }
3394
3395 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3396 mLastAlarmDeliveryTime = nowELAPSED;
3397 for (int i=0; i<triggerList.size(); i++) {
3398 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003399 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003400 if (alarm.wakeup) {
3401 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3402 } else {
3403 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3404 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003405 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003406 if (localLOGV) {
3407 Slog.v(TAG, "sending alarm " + alarm);
3408 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003409 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003410 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3411 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003412 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003413 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003414 } catch (RuntimeException e) {
3415 Slog.w(TAG, "Failure sending alarm.", e);
3416 }
Tim Murray175c0f92017-11-28 15:01:04 -08003417 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003418 }
3419 }
3420
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003421 private boolean isExemptFromAppStandby(Alarm a) {
3422 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3423 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3424 }
3425
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003426 private class AlarmThread extends Thread
3427 {
3428 public AlarmThread()
3429 {
3430 super("AlarmManager");
3431 }
Kweku Adams61e03292017-10-19 14:27:12 -07003432
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003433 public void run()
3434 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003435 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003437 while (true)
3438 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003439 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003440
Dianne Hackbornc3527222015-05-13 14:03:20 -07003441 final long nowRTC = System.currentTimeMillis();
3442 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003443 synchronized (mLock) {
3444 mLastWakeup = nowELAPSED;
3445 }
3446
3447 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003448
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003449 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003450 // The kernel can give us spurious time change notifications due to
3451 // small adjustments it makes internally; we want to filter those out.
3452 final long lastTimeChangeClockTime;
3453 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003454 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003455 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3456 expectedClockTime = lastTimeChangeClockTime
3457 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003458 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003459 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3460 || nowRTC > (expectedClockTime+1000)) {
3461 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003462 // let's do it!
3463 if (DEBUG_BATCH) {
3464 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3465 }
3466 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003467 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003468 rebatchAllAlarms();
3469 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003470 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003471 synchronized (mLock) {
3472 mNumTimeChanged++;
3473 mLastTimeChangeClockTime = nowRTC;
3474 mLastTimeChangeRealtime = nowELAPSED;
3475 }
3476 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3477 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003478 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003479 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3480 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003481 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3482
3483 // The world has changed on us, so we need to re-evaluate alarms
3484 // regardless of whether the kernel has told us one went off.
3485 result |= IS_WAKEUP_MASK;
3486 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003487 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003488
Dianne Hackbornc3527222015-05-13 14:03:20 -07003489 if (result != TIME_CHANGED_MASK) {
3490 // If this was anything besides just a time change, then figure what if
3491 // anything to do about alarms.
3492 synchronized (mLock) {
3493 if (localLOGV) Slog.v(
3494 TAG, "Checking for alarms... rtc=" + nowRTC
3495 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003496
Dianne Hackbornc3527222015-05-13 14:03:20 -07003497 if (WAKEUP_STATS) {
3498 if ((result & IS_WAKEUP_MASK) != 0) {
3499 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3500 int n = 0;
3501 for (WakeupEvent event : mRecentWakeups) {
3502 if (event.when > newEarliest) break;
3503 n++; // number of now-stale entries at the list head
3504 }
3505 for (int i = 0; i < n; i++) {
3506 mRecentWakeups.remove();
3507 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003508
Dianne Hackbornc3527222015-05-13 14:03:20 -07003509 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003510 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003511 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003512
Christopher Tate8b98ade2018-02-09 11:13:19 -08003513 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003514 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3515 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3516 // if there are no wakeup alarms and the screen is off, we can
3517 // delay what we have so far until the future.
3518 if (mPendingNonWakeupAlarms.size() == 0) {
3519 mStartCurrentDelayTime = nowELAPSED;
3520 mNextNonWakeupDeliveryTime = nowELAPSED
3521 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3522 }
3523 mPendingNonWakeupAlarms.addAll(triggerList);
3524 mNumDelayedAlarms += triggerList.size();
3525 rescheduleKernelAlarmsLocked();
3526 updateNextAlarmClockLocked();
3527 } else {
3528 // now deliver the alarm intents; if there are pending non-wakeup
3529 // alarms, we need to merge them in to the list. note we don't
3530 // just deliver them first because we generally want non-wakeup
3531 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003532 if (mPendingNonWakeupAlarms.size() > 0) {
3533 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3534 triggerList.addAll(mPendingNonWakeupAlarms);
3535 Collections.sort(triggerList, mAlarmDispatchComparator);
3536 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3537 mTotalDelayTime += thisDelayTime;
3538 if (mMaxDelayTime < thisDelayTime) {
3539 mMaxDelayTime = thisDelayTime;
3540 }
3541 mPendingNonWakeupAlarms.clear();
3542 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003543 final ArraySet<Pair<String, Integer>> triggerPackages =
3544 new ArraySet<>();
3545 for (int i = 0; i < triggerList.size(); i++) {
3546 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003547 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003548 triggerPackages.add(Pair.create(
3549 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003550 }
3551 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003552 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003553 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3554 rescheduleKernelAlarmsLocked();
3555 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003557 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003558
3559 } else {
3560 // Just in case -- even though no wakeup flag was set, make sure
3561 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003562 synchronized (mLock) {
3563 rescheduleKernelAlarmsLocked();
3564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003565 }
3566 }
3567 }
3568 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003569
David Christieebe51fc2013-07-26 13:23:29 -07003570 /**
3571 * Attribute blame for a WakeLock.
3572 * @param pi PendingIntent to attribute blame to if ws is null.
3573 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003574 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003575 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003576 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003577 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003578 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003579 final boolean unimportant = pi == mTimeTickSender;
3580 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003581 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003582 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003583 } else {
3584 mWakeLock.setHistoryTag(null);
3585 }
3586 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003587 if (ws != null) {
3588 mWakeLock.setWorkSource(ws);
3589 return;
3590 }
3591
Christopher Tate14a7bb02015-10-01 10:24:31 -07003592 final int uid = (knownUid >= 0)
3593 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003594 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003595 if (uid >= 0) {
3596 mWakeLock.setWorkSource(new WorkSource(uid));
3597 return;
3598 }
3599 } catch (Exception e) {
3600 }
3601
3602 // Something went wrong; fall back to attributing the lock to the OS
3603 mWakeLock.setWorkSource(null);
3604 }
3605
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003606 private class AlarmHandler extends Handler {
3607 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003608 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3609 public static final int LISTENER_TIMEOUT = 3;
3610 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003611 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3612 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003613 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003614
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003615 public AlarmHandler() {
3616 }
Kweku Adams61e03292017-10-19 14:27:12 -07003617
Makoto Onuki4d298b52018-02-05 10:54:58 -08003618 public void postRemoveForStopped(int uid) {
3619 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3620 }
3621
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003622 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003623 switch (msg.what) {
3624 case ALARM_EVENT: {
3625 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3626 synchronized (mLock) {
3627 final long nowRTC = System.currentTimeMillis();
3628 final long nowELAPSED = SystemClock.elapsedRealtime();
3629 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3630 updateNextAlarmClockLocked();
3631 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003632
Christopher Tate14a7bb02015-10-01 10:24:31 -07003633 // now trigger the alarms without the lock held
3634 for (int i=0; i<triggerList.size(); i++) {
3635 Alarm alarm = triggerList.get(i);
3636 try {
3637 alarm.operation.send();
3638 } catch (PendingIntent.CanceledException e) {
3639 if (alarm.repeatInterval > 0) {
3640 // This IntentSender is no longer valid, but this
3641 // is a repeating alarm, so toss the hoser.
3642 removeImpl(alarm.operation);
3643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 }
3645 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003646 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003647 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003648
3649 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3650 sendNextAlarmClockChanged();
3651 break;
3652
3653 case LISTENER_TIMEOUT:
3654 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3655 break;
3656
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003657 case REPORT_ALARMS_ACTIVE:
3658 if (mLocalDeviceIdleController != null) {
3659 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3660 }
3661 break;
3662
Suprabh Shukla75edab12018-01-29 14:09:06 -08003663 case APP_STANDBY_PAROLE_CHANGED:
3664 synchronized (mLock) {
3665 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003666 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3667 rescheduleKernelAlarmsLocked();
3668 updateNextAlarmClockLocked();
3669 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003670 }
3671 break;
3672
3673 case APP_STANDBY_BUCKET_CHANGED:
3674 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003675 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3676 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3677 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3678 rescheduleKernelAlarmsLocked();
3679 updateNextAlarmClockLocked();
3680 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003681 }
3682 break;
3683
Makoto Onuki4d298b52018-02-05 10:54:58 -08003684 case REMOVE_FOR_STOPPED:
3685 synchronized (mLock) {
3686 removeForStoppedLocked(msg.arg1);
3687 }
3688 break;
3689
Christopher Tate14a7bb02015-10-01 10:24:31 -07003690 default:
3691 // nope, just ignore it
3692 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003693 }
3694 }
3695 }
Kweku Adams61e03292017-10-19 14:27:12 -07003696
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003697 class ClockReceiver extends BroadcastReceiver {
3698 public ClockReceiver() {
3699 IntentFilter filter = new IntentFilter();
3700 filter.addAction(Intent.ACTION_TIME_TICK);
3701 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003702 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003703 }
Kweku Adams61e03292017-10-19 14:27:12 -07003704
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003705 @Override
3706 public void onReceive(Context context, Intent intent) {
3707 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003708 if (DEBUG_BATCH) {
3709 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3710 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003711 synchronized (mLock) {
3712 mLastTickReceived = System.currentTimeMillis();
3713 }
Christopher Tate385e4982013-07-23 18:22:29 -07003714 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3716 // Since the kernel does not keep track of DST, we need to
3717 // reset the TZ information at the beginning of each day
3718 // based off of the current Zone gmt offset + userspace tracked
3719 // daylight savings information.
3720 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003721 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003722 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003723 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003724 }
3725 }
Kweku Adams61e03292017-10-19 14:27:12 -07003726
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003727 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003728 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003729 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003730
3731 // Schedule this event for the amount of time that it would take to get to
3732 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003733 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003734
David Christieebe51fc2013-07-26 13:23:29 -07003735 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003736 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003737 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3738 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003739
3740 // Finally, remember when we set the tick alarm
3741 synchronized (mLock) {
3742 mLastTickSet = currentTime;
3743 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003744 }
Christopher Tate385e4982013-07-23 18:22:29 -07003745
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003746 public void scheduleDateChangedEvent() {
3747 Calendar calendar = Calendar.getInstance();
3748 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003749 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003750 calendar.set(Calendar.MINUTE, 0);
3751 calendar.set(Calendar.SECOND, 0);
3752 calendar.set(Calendar.MILLISECOND, 0);
3753 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003754
3755 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003756 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3757 AlarmManager.FLAG_STANDALONE, workSource, null,
3758 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003759 }
3760 }
Kweku Adams61e03292017-10-19 14:27:12 -07003761
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003762 class InteractiveStateReceiver extends BroadcastReceiver {
3763 public InteractiveStateReceiver() {
3764 IntentFilter filter = new IntentFilter();
3765 filter.addAction(Intent.ACTION_SCREEN_OFF);
3766 filter.addAction(Intent.ACTION_SCREEN_ON);
3767 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3768 getContext().registerReceiver(this, filter);
3769 }
3770
3771 @Override
3772 public void onReceive(Context context, Intent intent) {
3773 synchronized (mLock) {
3774 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3775 }
3776 }
3777 }
3778
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003779 class UninstallReceiver extends BroadcastReceiver {
3780 public UninstallReceiver() {
3781 IntentFilter filter = new IntentFilter();
3782 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3783 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003784 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003785 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003786 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003787 // Register for events related to sdcard installation.
3788 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003789 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003790 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003791 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003792 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003793 }
Kweku Adams61e03292017-10-19 14:27:12 -07003794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 @Override
3796 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003797 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003798 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003799 String action = intent.getAction();
3800 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003801 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3802 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3803 for (String packageName : pkgList) {
3804 if (lookForPackageLocked(packageName)) {
3805 setResultCode(Activity.RESULT_OK);
3806 return;
3807 }
3808 }
3809 return;
3810 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003811 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003812 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3813 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3814 if (userHandle >= 0) {
3815 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003816 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3817 final Pair<String, Integer> packageUser =
3818 mLastAlarmDeliveredForPackage.keyAt(i);
3819 if (packageUser.second == userHandle) {
3820 mLastAlarmDeliveredForPackage.removeAt(i);
3821 }
3822 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003823 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003824 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003825 if (uid >= 0) {
3826 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003827 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003828 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003829 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003830 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3831 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3832 // This package is being updated; don't kill its alarms.
3833 return;
3834 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003835 Uri data = intent.getData();
3836 if (data != null) {
3837 String pkg = data.getSchemeSpecificPart();
3838 if (pkg != null) {
3839 pkgList = new String[]{pkg};
3840 }
3841 }
3842 }
3843 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003844 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3845 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3846 if (ArrayUtils.contains(pkgList, packageUser.first)
3847 && packageUser.second == UserHandle.getUserId(uid)) {
3848 mLastAlarmDeliveredForPackage.removeAt(i);
3849 }
3850 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003851 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003852 if (uid >= 0) {
3853 // package-removed case
3854 removeLocked(uid);
3855 } else {
3856 // external-applications-unavailable etc case
3857 removeLocked(pkg);
3858 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003859 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003860 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3861 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3862 if (uidStats.remove(pkg) != null) {
3863 if (uidStats.size() <= 0) {
3864 mBroadcastStats.removeAt(i);
3865 }
3866 }
3867 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003869 }
3870 }
3871 }
3872 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003873
3874 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003875 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003876 }
3877
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003878 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003879 if (disabled) {
3880 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003881 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003882 }
3883
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003884 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003885 }
3886
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003887 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003888 if (disabled) {
3889 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003890 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003891 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003892
3893 @Override public void onUidCachedChanged(int uid, boolean cached) {
3894 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003895 };
3896
Suprabh Shukla75edab12018-01-29 14:09:06 -08003897 /**
3898 * Tracking of app assignments to standby buckets
3899 */
3900 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3901 @Override
3902 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08003903 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003904 if (DEBUG_STANDBY) {
3905 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3906 bucket);
3907 }
3908 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003909 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3910 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003911 }
3912
3913 @Override
3914 public void onParoleStateChanged(boolean isParoleOn) {
3915 if (DEBUG_STANDBY) {
3916 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3917 }
3918 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3919 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3920 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3921 Boolean.valueOf(isParoleOn)).sendToTarget();
3922 }
3923 };
3924
Makoto Onuki2206af32017-11-21 16:25:35 -08003925 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003926 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003927 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003928 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003929 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003930 }
3931 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003932
3933 @Override
3934 public void unblockAlarmsForUid(int uid) {
3935 synchronized (mLock) {
3936 sendPendingBackgroundAlarmsLocked(uid, null);
3937 }
3938 }
3939
3940 @Override
3941 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3942 synchronized (mLock) {
3943 sendPendingBackgroundAlarmsLocked(uid, packageName);
3944 }
3945 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003946
3947 @Override
3948 public void onUidForeground(int uid, boolean foreground) {
3949 synchronized (mLock) {
3950 if (foreground) {
3951 mUseAllowWhileIdleShortTime.put(uid, true);
3952
3953 // Note we don't have to drain the pending while-idle alarms here, because
3954 // this event should coincide with unblockAlarmsForUid().
3955 }
3956 }
3957 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003958 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003960 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003961 String pkg = pi.getCreatorPackage();
3962 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003963 return getStatsLocked(uid, pkg);
3964 }
3965
3966 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003967 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3968 if (uidStats == null) {
3969 uidStats = new ArrayMap<String, BroadcastStats>();
3970 mBroadcastStats.put(uid, uidStats);
3971 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003972 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003973 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003974 bs = new BroadcastStats(uid, pkgName);
3975 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003976 }
3977 return bs;
3978 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003979
Christopher Tate21e9f192017-08-08 13:49:11 -07003980 /**
3981 * Canonical count of (operation.send() - onSendFinished()) and
3982 * listener send/complete/timeout invocations.
3983 * Guarded by the usual lock.
3984 */
3985 @GuardedBy("mLock")
3986 private int mSendCount = 0;
3987 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003988 private int mSendFinishCount = 0;
3989 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003990 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003991 @GuardedBy("mLock")
3992 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003993
Christopher Tate14a7bb02015-10-01 10:24:31 -07003994 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003995
Christopher Tate14a7bb02015-10-01 10:24:31 -07003996 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3997 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003998 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003999 return mInFlight.remove(i);
4000 }
4001 }
4002 mLog.w("No in-flight alarm for " + pi + " " + intent);
4003 return null;
4004 }
4005
4006 private InFlight removeLocked(IBinder listener) {
4007 for (int i = 0; i < mInFlight.size(); i++) {
4008 if (mInFlight.get(i).mListener == listener) {
4009 return mInFlight.remove(i);
4010 }
4011 }
4012 mLog.w("No in-flight alarm for listener " + listener);
4013 return null;
4014 }
4015
4016 private void updateStatsLocked(InFlight inflight) {
4017 final long nowELAPSED = SystemClock.elapsedRealtime();
4018 BroadcastStats bs = inflight.mBroadcastStats;
4019 bs.nesting--;
4020 if (bs.nesting <= 0) {
4021 bs.nesting = 0;
4022 bs.aggregateTime += nowELAPSED - bs.startTime;
4023 }
4024 FilterStats fs = inflight.mFilterStats;
4025 fs.nesting--;
4026 if (fs.nesting <= 0) {
4027 fs.nesting = 0;
4028 fs.aggregateTime += nowELAPSED - fs.startTime;
4029 }
4030 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004031 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4032 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004033 }
4034 }
4035
4036 private void updateTrackingLocked(InFlight inflight) {
4037 if (inflight != null) {
4038 updateStatsLocked(inflight);
4039 }
4040 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004041 if (DEBUG_WAKELOCK) {
4042 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4043 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004044 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004045 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004046 mWakeLock.release();
4047 if (mInFlight.size() > 0) {
4048 mLog.w("Finished all dispatches with " + mInFlight.size()
4049 + " remaining inflights");
4050 for (int i=0; i<mInFlight.size(); i++) {
4051 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4052 }
4053 mInFlight.clear();
4054 }
4055 } else {
4056 // the next of our alarms is now in flight. reattribute the wakelock.
4057 if (mInFlight.size() > 0) {
4058 InFlight inFlight = mInFlight.get(0);
4059 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4060 inFlight.mAlarmType, inFlight.mTag, -1, false);
4061 } else {
4062 // should never happen
4063 mLog.w("Alarm wakelock still held but sent queue empty");
4064 mWakeLock.setWorkSource(null);
4065 }
4066 }
4067 }
4068
4069 /**
4070 * Callback that arrives when a direct-call alarm reports that delivery has finished
4071 */
4072 @Override
4073 public void alarmComplete(IBinder who) {
4074 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004075 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004076 + " pid=" + Binder.getCallingPid());
4077 return;
4078 }
4079
4080 final long ident = Binder.clearCallingIdentity();
4081 try {
4082 synchronized (mLock) {
4083 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4084 InFlight inflight = removeLocked(who);
4085 if (inflight != null) {
4086 if (DEBUG_LISTENER_CALLBACK) {
4087 Slog.i(TAG, "alarmComplete() from " + who);
4088 }
4089 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004090 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004091 } else {
4092 // Delivery timed out, and the timeout handling already took care of
4093 // updating our tracking here, so we needn't do anything further.
4094 if (DEBUG_LISTENER_CALLBACK) {
4095 Slog.i(TAG, "Late alarmComplete() from " + who);
4096 }
4097 }
4098 }
4099 } finally {
4100 Binder.restoreCallingIdentity(ident);
4101 }
4102 }
4103
4104 /**
4105 * Callback that arrives when a PendingIntent alarm has finished delivery
4106 */
4107 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004108 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4109 String resultData, Bundle resultExtras) {
4110 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004111 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004112 updateTrackingLocked(removeLocked(pi, intent));
4113 }
4114 }
4115
4116 /**
4117 * Timeout of a direct-call alarm delivery
4118 */
4119 public void alarmTimedOut(IBinder who) {
4120 synchronized (mLock) {
4121 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004122 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004123 // TODO: implement ANR policy for the target
4124 if (DEBUG_LISTENER_CALLBACK) {
4125 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004126 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004127 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004128 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004129 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004130 if (DEBUG_LISTENER_CALLBACK) {
4131 Slog.i(TAG, "Spurious timeout of listener " + who);
4132 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004133 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004134 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004135 }
4136 }
4137
4138 /**
4139 * Deliver an alarm and set up the post-delivery handling appropriately
4140 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004141 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004142 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4143 if (alarm.operation != null) {
4144 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004145 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004146
4147 if (alarm.priorityClass.priority == PRIO_TICK) {
4148 mLastTickIssued = nowELAPSED;
4149 }
4150
Christopher Tate14a7bb02015-10-01 10:24:31 -07004151 try {
4152 alarm.operation.send(getContext(), 0,
4153 mBackgroundIntent.putExtra(
4154 Intent.EXTRA_ALARM_COUNT, alarm.count),
4155 mDeliveryTracker, mHandler, null,
4156 allowWhileIdle ? mIdleOptions : null);
4157 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004158 if (alarm.operation == mTimeTickSender) {
4159 Slog.wtf(TAG, "mTimeTickSender canceled");
4160 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004161 if (alarm.repeatInterval > 0) {
4162 // This IntentSender is no longer valid, but this
4163 // is a repeating alarm, so toss it
4164 removeImpl(alarm.operation);
4165 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004166 // No actual delivery was possible, so the delivery tracker's
4167 // 'finished' callback won't be invoked. We also don't need
4168 // to do any wakelock or stats tracking, so we have nothing
4169 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004170 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004171 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004172 }
4173 } else {
4174 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004175 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004176 try {
4177 if (DEBUG_LISTENER_CALLBACK) {
4178 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4179 + " listener=" + alarm.listener.asBinder());
4180 }
4181 alarm.listener.doAlarm(this);
4182 mHandler.sendMessageDelayed(
4183 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4184 alarm.listener.asBinder()),
4185 mConstants.LISTENER_TIMEOUT);
4186 } catch (Exception e) {
4187 if (DEBUG_LISTENER_CALLBACK) {
4188 Slog.i(TAG, "Alarm undeliverable to listener "
4189 + alarm.listener.asBinder(), e);
4190 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004191 // As in the PendingIntent.CanceledException case, delivery of the
4192 // alarm was not possible, so we have no wakelock or timeout or
4193 // stats management to do. It threw before we posted the delayed
4194 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004195 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004196 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004197 }
4198 }
4199
4200 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004201 if (DEBUG_WAKELOCK) {
4202 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4203 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004204 if (mBroadcastRefCount == 0) {
4205 setWakelockWorkSource(alarm.operation, alarm.workSource,
4206 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4207 true);
4208 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004209 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004210 }
4211 final InFlight inflight = new InFlight(AlarmManagerService.this,
4212 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4213 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4214 mInFlight.add(inflight);
4215 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004216 if (allowWhileIdle) {
4217 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004218 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004219 if ((mAppStateTracker == null)
4220 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004221 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4222 } else {
4223 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4224 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004225 if (RECORD_DEVICE_IDLE_ALARMS) {
4226 IdleDispatchEntry ent = new IdleDispatchEntry();
4227 ent.uid = alarm.uid;
4228 ent.pkg = alarm.packageName;
4229 ent.tag = alarm.statsTag;
4230 ent.op = "DELIVER";
4231 ent.elapsedRealtime = nowELAPSED;
4232 mAllowWhileIdleDispatches.add(ent);
4233 }
4234 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004235 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004236 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4237 UserHandle.getUserId(alarm.creatorUid));
4238 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4239 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004240
4241 final BroadcastStats bs = inflight.mBroadcastStats;
4242 bs.count++;
4243 if (bs.nesting == 0) {
4244 bs.nesting = 1;
4245 bs.startTime = nowELAPSED;
4246 } else {
4247 bs.nesting++;
4248 }
4249 final FilterStats fs = inflight.mFilterStats;
4250 fs.count++;
4251 if (fs.nesting == 0) {
4252 fs.nesting = 1;
4253 fs.startTime = nowELAPSED;
4254 } else {
4255 fs.nesting++;
4256 }
4257 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4258 || alarm.type == RTC_WAKEUP) {
4259 bs.numWakeup++;
4260 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004261 ActivityManager.noteWakeupAlarm(
4262 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4263 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004264 }
4265 }
4266 }
4267}