blob: 47b646c1a667be47bc7864ef431d4de359900239 [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;
Christopher Tatebfbd9882018-12-11 14:55:19 -080051import android.os.Build;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070053import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080055import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070057import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080058import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070059import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070060import android.os.RemoteException;
mswest463f4c99d2018-02-01 10:13:10 -080061import android.os.ResultReceiver;
62import android.os.ShellCallback;
63import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.os.SystemClock;
65import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080066import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070067import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070068import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020069import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080070import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020072import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080073import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080074import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080075import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070076import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020077import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070078import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080079import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080080import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080081import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020082import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070083import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070084import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070085import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086
Jeff Sharkey9911a282018-02-14 22:29:11 -070087import com.android.internal.annotations.GuardedBy;
88import com.android.internal.annotations.VisibleForTesting;
89import com.android.internal.util.ArrayUtils;
90import com.android.internal.util.DumpUtils;
91import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070092import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070093import com.android.server.AppStateTracker.Listener;
94
Christopher Tate4cb338d2013-07-26 13:11:31 -070095import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096import java.io.FileDescriptor;
97import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070098import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -070099import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800101import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800102import java.util.Calendar;
103import java.util.Collections;
104import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500105import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700106import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700107import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200108import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700109import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400111import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800112import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113
Makoto Onuki2206af32017-11-21 16:25:35 -0800114/**
115 * Alarm manager implementaion.
116 *
117 * Unit test:
118 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
119 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800120class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700121 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
122 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700124 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 static final int TIME_CHANGED_MASK = 1 << 16;
126 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800127
Christopher Tatee0a22b32013-07-11 14:43:13 -0700128 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800130
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 static final boolean localLOGV = false;
133 static final boolean DEBUG_BATCH = localLOGV || false;
134 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200135 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700136 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800137 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700138 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800139 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700140 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700141 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800142 static final int ALARM_EVENT = 1;
143 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200144
Christopher Tatef2159712018-03-27 16:04:14 -0700145 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
146 static final int ACTIVE_INDEX = 0;
147 static final int WORKING_INDEX = 1;
148 static final int FREQUENT_INDEX = 2;
149 static final int RARE_INDEX = 3;
150 static final int NEVER_INDEX = 4;
151
Christopher Tate14a7bb02015-10-01 10:24:31 -0700152 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700155
Adam Lesinski182f73f2013-12-05 16:48:06 -0800156 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700157
Christopher Tate24cd46f2016-02-02 14:28:01 -0800158 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
159 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700160 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
161 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200162
Adam Lesinski182f73f2013-12-05 16:48:06 -0800163 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800164
Christopher Tate14a7bb02015-10-01 10:24:31 -0700165 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800166 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800167 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700168
Adam Lesinski182f73f2013-12-05 16:48:06 -0800169 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800170
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700171 // List of alarms per uid deferred due to user applied background restrictions on the source app
172 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800173 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800174 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700175 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700176 private long mLastWakeupSet;
177 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800178 private long mLastTrigger;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800179 private long mLastTickSet;
180 private long mLastTickIssued; // elapsed
181 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800182 private long mLastTickAdded;
183 private long mLastTickRemoved;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800184 int mBroadcastRefCount = 0;
185 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700186 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700187 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
188 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800189 final AlarmHandler mHandler = new AlarmHandler();
190 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700191 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700193 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800194 PendingIntent mTimeTickSender;
195 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700196 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700197 boolean mInteractive = true;
198 long mNonInteractiveStartTime;
199 long mNonInteractiveTime;
200 long mLastAlarmDeliveryTime;
201 long mStartCurrentDelayTime;
202 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700203 long mLastTimeChangeClockTime;
204 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700205 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800206
Christopher Tatebb9cce52017-04-18 14:19:43 -0700207 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
208
209 /**
210 * This permission must be defined by the canonical System UI package,
211 * with protection level "signature".
212 */
213 private static final String SYSTEM_UI_SELF_PERMISSION =
214 "android.permission.systemui.IDENTITY";
215
216 /**
217 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
218 */
219 int mSystemUiUid;
220
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700221 /**
222 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700223 * used to determine the earliest we can dispatch the next such alarm. Times are in the
224 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700225 */
226 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
227
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800228 /**
229 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
230 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
231 */
232 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
233
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700234 final static class IdleDispatchEntry {
235 int uid;
236 String pkg;
237 String tag;
238 String op;
239 long elapsedRealtime;
240 long argRealtime;
241 }
242 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
243
Suprabh Shukla75edab12018-01-29 14:09:06 -0800244 interface Stats {
245 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800246 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800247 }
248
249 private final StatLogger mStatLogger = new StatLogger(new String[] {
250 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800251 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800252 });
253
Dianne Hackborna750a632015-06-16 17:18:23 -0700254 /**
255 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
256 */
257 Bundle mIdleOptions;
258
Jose Lima235510e2014-08-13 12:50:01 -0700259 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
260 new SparseArray<>();
261 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
262 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200263 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
264 new SparseBooleanArray();
265 private boolean mNextAlarmClockMayChange;
266
267 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700268 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
269 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200270
Makoto Onukie4918212018-02-06 11:30:15 -0800271 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800272 private boolean mAppStandbyParole;
273 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800274
Dianne Hackborna750a632015-06-16 17:18:23 -0700275 /**
276 * All times are in milliseconds. These constants are kept synchronized with the system
277 * global Settings. Any access to this class or its fields should be done while
278 * holding the AlarmManagerService.mLock lock.
279 */
280 private final class Constants extends ContentObserver {
281 // Key names stored in the settings value.
282 private static final String KEY_MIN_FUTURITY = "min_futurity";
283 private static final String KEY_MIN_INTERVAL = "min_interval";
Christopher Tate22e919d2018-02-16 16:16:50 -0800284 private static final String KEY_MAX_INTERVAL = "max_interval";
Dianne Hackborna750a632015-06-16 17:18:23 -0700285 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
286 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
287 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
288 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700289 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700290
Suprabh Shukla75edab12018-01-29 14:09:06 -0800291 // Keys for specifying throttling delay based on app standby bucketing
292 private final String[] KEYS_APP_STANDBY_DELAY = {
293 "standby_active_delay",
294 "standby_working_delay",
295 "standby_frequent_delay",
296 "standby_rare_delay",
297 "standby_never_delay",
298 };
299
Dianne Hackborna750a632015-06-16 17:18:23 -0700300 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
301 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800302 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700303 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700304 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700305 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700306 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800307 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
308 0, // Active
309 6 * 60_000, // Working
310 30 * 60_000, // Frequent
311 2 * 60 * 60_000, // Rare
312 10 * 24 * 60 * 60_000 // Never
313 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700314
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 // Minimum futurity of a new alarm
316 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
317
318 // Minimum alarm recurrence interval
319 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
320
Christopher Tate22e919d2018-02-16 16:16:50 -0800321 // Maximum alarm recurrence interval
322 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
323
Dianne Hackborna750a632015-06-16 17:18:23 -0700324 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
325 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
326
327 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
328 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
329
330 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
331 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
332 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
333
Christopher Tate14a7bb02015-10-01 10:24:31 -0700334 // Direct alarm listener callback timeout
335 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
336
Suprabh Shukla75edab12018-01-29 14:09:06 -0800337 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
338
Dianne Hackborna750a632015-06-16 17:18:23 -0700339 private ContentResolver mResolver;
340 private final KeyValueListParser mParser = new KeyValueListParser(',');
341 private long mLastAllowWhileIdleWhitelistDuration = -1;
342
343 public Constants(Handler handler) {
344 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700345 updateAllowWhileIdleWhitelistDurationLocked();
346 }
347
348 public void start(ContentResolver resolver) {
349 mResolver = resolver;
350 mResolver.registerContentObserver(Settings.Global.getUriFor(
351 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
352 updateConstants();
353 }
354
Dianne Hackborna750a632015-06-16 17:18:23 -0700355 public void updateAllowWhileIdleWhitelistDurationLocked() {
356 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
357 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
358 BroadcastOptions opts = BroadcastOptions.makeBasic();
359 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
360 mIdleOptions = opts.toBundle();
361 }
362 }
363
364 @Override
365 public void onChange(boolean selfChange, Uri uri) {
366 updateConstants();
367 }
368
369 private void updateConstants() {
370 synchronized (mLock) {
371 try {
372 mParser.setString(Settings.Global.getString(mResolver,
373 Settings.Global.ALARM_MANAGER_CONSTANTS));
374 } catch (IllegalArgumentException e) {
375 // Failed to parse the settings string, log this and move on
376 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800377 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700378 }
379
380 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
381 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800382 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700383 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
384 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
385 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
386 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
387 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
388 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
389 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700390 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
391 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700392 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
393 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
394 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
395 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800396 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
397 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
398 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700399 updateAllowWhileIdleWhitelistDurationLocked();
400 }
401 }
402
403 void dump(PrintWriter pw) {
404 pw.println(" Settings:");
405
406 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
407 TimeUtils.formatDuration(MIN_FUTURITY, pw);
408 pw.println();
409
410 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
411 TimeUtils.formatDuration(MIN_INTERVAL, pw);
412 pw.println();
413
Christopher Tate22e919d2018-02-16 16:16:50 -0800414 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
415 TimeUtils.formatDuration(MAX_INTERVAL, pw);
416 pw.println();
417
Christopher Tate14a7bb02015-10-01 10:24:31 -0700418 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
419 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
420 pw.println();
421
Dianne Hackborna750a632015-06-16 17:18:23 -0700422 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
423 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
424 pw.println();
425
426 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
427 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
428 pw.println();
429
430 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
431 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
432 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800433
434 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
435 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
436 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
437 pw.println();
438 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700439 }
Kweku Adams61e03292017-10-19 14:27:12 -0700440
441 void dumpProto(ProtoOutputStream proto, long fieldId) {
442 final long token = proto.start(fieldId);
443
444 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
445 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800446 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700447 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
448 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
449 ALLOW_WHILE_IDLE_SHORT_TIME);
450 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
451 ALLOW_WHILE_IDLE_LONG_TIME);
452 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
453 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
454
455 proto.end(token);
456 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700457 }
458
459 final Constants mConstants;
460
Christopher Tate1590f1e2014-10-02 17:27:57 -0700461 // Alarm delivery ordering bookkeeping
462 static final int PRIO_TICK = 0;
463 static final int PRIO_WAKEUP = 1;
464 static final int PRIO_NORMAL = 2;
465
Dianne Hackborna750a632015-06-16 17:18:23 -0700466 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700467 int seq;
468 int priority;
469
470 PriorityClass() {
471 seq = mCurrentSeq - 1;
472 priority = PRIO_NORMAL;
473 }
474 }
475
Dianne Hackborna750a632015-06-16 17:18:23 -0700476 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700477 int mCurrentSeq = 0;
478
Dianne Hackborna750a632015-06-16 17:18:23 -0700479 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700480 public long when;
481 public int uid;
482 public String action;
483
484 public WakeupEvent(long theTime, int theUid, String theAction) {
485 when = theTime;
486 uid = theUid;
487 action = theAction;
488 }
489 }
490
Adam Lesinski182f73f2013-12-05 16:48:06 -0800491 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
492 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700493
Adrian Roosc42a1e12014-07-07 23:35:53 +0200494 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 long start; // These endpoints are always in ELAPSED
496 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700497 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498
499 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
500
501 Batch() {
502 start = 0;
503 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700504 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700505 }
506
507 Batch(Alarm seed) {
508 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800509 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700510 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700511 alarms.add(seed);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800512 if (seed.operation == mTimeTickSender) {
513 mLastTickAdded = System.currentTimeMillis();
514 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700515 }
516
517 int size() {
518 return alarms.size();
519 }
520
521 Alarm get(int index) {
522 return alarms.get(index);
523 }
524
525 boolean canHold(long whenElapsed, long maxWhen) {
526 return (end >= whenElapsed) && (start <= maxWhen);
527 }
528
529 boolean add(Alarm alarm) {
530 boolean newStart = false;
531 // narrows the batch if necessary; presumes that canHold(alarm) is true
532 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
533 if (index < 0) {
534 index = 0 - index - 1;
535 }
536 alarms.add(index, alarm);
Makoto Onuki5d93b832018-01-10 16:12:39 -0800537 if (alarm.operation == mTimeTickSender) {
538 mLastTickAdded = System.currentTimeMillis();
539 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 if (DEBUG_BATCH) {
541 Slog.v(TAG, "Adding " + alarm + " to " + this);
542 }
543 if (alarm.whenElapsed > start) {
544 start = alarm.whenElapsed;
545 newStart = true;
546 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700547 if (alarm.maxWhenElapsed < end) {
548 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700549 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700550 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700551
552 if (DEBUG_BATCH) {
553 Slog.v(TAG, " => now " + this);
554 }
555 return newStart;
556 }
557
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800558 boolean remove(Alarm alarm) {
559 return remove(a -> (a == alarm));
560 }
561
Christopher Tate1d99c392017-12-07 16:54:04 -0800562 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700563 boolean didRemove = false;
564 long newStart = 0; // recalculate endpoints as we go
565 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700566 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700567 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800569 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700570 alarms.remove(i);
571 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200572 if (alarm.alarmClock != null) {
573 mNextAlarmClockMayChange = true;
574 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800575 if (alarm.operation == mTimeTickSender) {
576 mLastTickRemoved = System.currentTimeMillis();
577 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700578 } else {
579 if (alarm.whenElapsed > newStart) {
580 newStart = alarm.whenElapsed;
581 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700582 if (alarm.maxWhenElapsed < newEnd) {
583 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700584 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700585 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700586 i++;
587 }
588 }
589 if (didRemove) {
590 // commit the new batch bounds
591 start = newStart;
592 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700593 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700594 }
595 return didRemove;
596 }
597
Christopher Tatee0a22b32013-07-11 14:43:13 -0700598 boolean hasPackage(final String packageName) {
599 final int N = alarms.size();
600 for (int i = 0; i < N; i++) {
601 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700602 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700603 return true;
604 }
605 }
606 return false;
607 }
608
609 boolean hasWakeups() {
610 final int N = alarms.size();
611 for (int i = 0; i < N; i++) {
612 Alarm a = alarms.get(i);
613 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
614 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
615 return true;
616 }
617 }
618 return false;
619 }
620
621 @Override
622 public String toString() {
623 StringBuilder b = new StringBuilder(40);
624 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
625 b.append(" num="); b.append(size());
626 b.append(" start="); b.append(start);
627 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700628 if (flags != 0) {
629 b.append(" flgs=0x");
630 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700631 }
632 b.append('}');
633 return b.toString();
634 }
Kweku Adams61e03292017-10-19 14:27:12 -0700635
636 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
637 long nowRTC) {
638 final long token = proto.start(fieldId);
639
640 proto.write(BatchProto.START_REALTIME, start);
641 proto.write(BatchProto.END_REALTIME, end);
642 proto.write(BatchProto.FLAGS, flags);
643 for (Alarm a : alarms) {
644 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
645 }
646
647 proto.end(token);
648 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700649 }
650
651 static class BatchTimeOrder implements Comparator<Batch> {
652 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800653 long when1 = b1.start;
654 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800655 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700656 return 1;
657 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800658 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700659 return -1;
660 }
661 return 0;
662 }
663 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800664
665 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
666 @Override
667 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700668 // priority class trumps everything. TICK < WAKEUP < NORMAL
669 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
670 return -1;
671 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
672 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800673 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700674
675 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800676 if (lhs.whenElapsed < rhs.whenElapsed) {
677 return -1;
678 } else if (lhs.whenElapsed > rhs.whenElapsed) {
679 return 1;
680 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700681
682 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800683 return 0;
684 }
685 };
686
Christopher Tate1590f1e2014-10-02 17:27:57 -0700687 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
688 final int N = alarms.size();
689 for (int i = 0; i < N; i++) {
690 Alarm a = alarms.get(i);
691
692 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700693 if (a.operation != null
694 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700695 alarmPrio = PRIO_TICK;
696 } else if (a.wakeup) {
697 alarmPrio = PRIO_WAKEUP;
698 } else {
699 alarmPrio = PRIO_NORMAL;
700 }
701
702 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800703 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700704 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700705 if (packagePrio == null) {
706 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700707 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700708 }
709 a.priorityClass = packagePrio;
710
711 if (packagePrio.seq != mCurrentSeq) {
712 // first alarm we've seen in the current delivery generation from this package
713 packagePrio.priority = alarmPrio;
714 packagePrio.seq = mCurrentSeq;
715 } else {
716 // Multiple alarms from this package being delivered in this generation;
717 // bump the package's delivery class if it's warranted.
718 // TICK < WAKEUP < NORMAL
719 if (alarmPrio < packagePrio.priority) {
720 packagePrio.priority = alarmPrio;
721 }
722 }
723 }
724 }
725
Christopher Tatee0a22b32013-07-11 14:43:13 -0700726 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800727 static final long MIN_FUZZABLE_INTERVAL = 10000;
728 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700729 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
730
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700731 // set to non-null if in idle mode; while in this mode, any alarms we don't want
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700732 // to run during this time are placed in mPendingWhileIdleAlarms
733 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700734 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700735 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700736
Jeff Brownb880d882014-02-10 19:47:07 -0800737 public AlarmManagerService(Context context) {
738 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700739 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800740
Christopher Tate1d99c392017-12-07 16:54:04 -0800741 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800742 }
743
Christopher Tatee0a22b32013-07-11 14:43:13 -0700744 static long convertToElapsed(long when, int type) {
745 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
746 if (isRtc) {
747 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
748 }
749 return when;
750 }
751
752 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
753 // calculate the end of our nominal delivery window for the alarm.
754 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
755 // Current heuristic: batchable window is 75% of either the recurrence interval
756 // [for a periodic alarm] or of the time from now to the desired delivery time,
757 // with a minimum delay/interval of 10 seconds, under which we will simply not
758 // defer the alarm.
759 long futurity = (interval == 0)
760 ? (triggerAtTime - now)
761 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700762 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 futurity = 0;
764 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800765 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700766 }
767
768 // returns true if the batch was added at the head
769 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
770 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
771 if (index < 0) {
772 index = 0 - index - 1;
773 }
774 list.add(index, newBatch);
775 return (index == 0);
776 }
777
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800778 private void insertAndBatchAlarmLocked(Alarm alarm) {
779 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
780 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
781
782 if (whichBatch < 0) {
783 addBatchLocked(mAlarmBatches, new Batch(alarm));
784 } else {
785 final Batch batch = mAlarmBatches.get(whichBatch);
786 if (batch.add(alarm)) {
787 // The start time of this batch advanced, so batch ordering may
788 // have just been broken. Move it to where it now belongs.
789 mAlarmBatches.remove(whichBatch);
790 addBatchLocked(mAlarmBatches, batch);
791 }
792 }
793 }
794
Christopher Tate385e4982013-07-23 18:22:29 -0700795 // Return the index of the matching batch, or -1 if none found.
796 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700797 final int N = mAlarmBatches.size();
798 for (int i = 0; i < N; i++) {
799 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700800 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700801 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700802 }
803 }
Christopher Tate385e4982013-07-23 18:22:29 -0700804 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700805 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800806 /** @return total count of the alarms in a set of alarm batches. */
807 static int getAlarmCount(ArrayList<Batch> batches) {
808 int ret = 0;
809
810 final int size = batches.size();
811 for (int i = 0; i < size; i++) {
812 ret += batches.get(i).size();
813 }
814 return ret;
815 }
816
817 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
818 if (alarms.size() == 0) {
819 return false;
820 }
821 final int batchSize = alarms.size();
822 for (int j = 0; j < batchSize; j++) {
823 if (alarms.get(j).operation == mTimeTickSender) {
824 return true;
825 }
826 }
827 return false;
828 }
829
830 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
831 final int numBatches = batches.size();
832 for (int i = 0; i < numBatches; i++) {
833 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
834 return true;
835 }
836 }
837 return false;
838 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700839
840 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
841 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700842 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700843 rebatchAllAlarmsLocked(true);
844 }
845 }
846
847 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800848 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800849 final int oldCount =
850 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
851 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
852 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
853
Christopher Tate4cb338d2013-07-26 13:11:31 -0700854 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
855 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700856 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700857 final long nowElapsed = SystemClock.elapsedRealtime();
858 final int oldBatches = oldSet.size();
859 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
860 Batch batch = oldSet.get(batchNum);
861 final int N = batch.size();
862 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700863 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700864 }
865 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700866 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
867 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
868 + " to " + mPendingIdleUntil);
869 if (mPendingIdleUntil == null) {
870 // Somehow we lost this... we need to restore all of the pending alarms.
871 restorePendingWhileIdleAlarmsLocked();
872 }
873 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800874 final int newCount =
875 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
876 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
877 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
878
879 if (oldCount != newCount) {
880 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
881 }
882 if (oldHasTick != newHasTick) {
883 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
884 }
885
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700886 rescheduleKernelAlarmsLocked();
887 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800888 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700889 }
890
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800891 /**
892 * Re-orders the alarm batches based on newly evaluated send times based on the current
893 * app-standby buckets
894 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
895 * null indicates all
896 * @return True if there was any reordering done to the current list.
897 */
898 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
899 final long start = mStatLogger.getTime();
900 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
901
902 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
903 final Batch batch = mAlarmBatches.get(batchIndex);
904 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
905 final Alarm alarm = batch.get(alarmIndex);
906 final Pair<String, Integer> packageUser =
907 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
908 if (targetPackages != null && !targetPackages.contains(packageUser)) {
909 continue;
910 }
911 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
912 batch.remove(alarm);
913 rescheduledAlarms.add(alarm);
914 }
915 }
916 if (batch.size() == 0) {
917 mAlarmBatches.remove(batchIndex);
918 }
919 }
920 for (int i = 0; i < rescheduledAlarms.size(); i++) {
921 final Alarm a = rescheduledAlarms.get(i);
922 insertAndBatchAlarmLocked(a);
923 }
924
925 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
926 return rescheduledAlarms.size() > 0;
927 }
928
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700929 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
930 a.when = a.origWhen;
931 long whenElapsed = convertToElapsed(a.when, a.type);
932 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700933 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700934 // Exact
935 maxElapsed = whenElapsed;
936 } else {
937 // Not exact. Preserve any explicit window, otherwise recalculate
938 // the window based on the alarm's new futurity. Note that this
939 // reflects a policy of preferring timely to deferred delivery.
940 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800941 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700942 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
943 }
944 a.whenElapsed = whenElapsed;
945 a.maxWhenElapsed = maxElapsed;
946 setImplLocked(a, true, doValidate);
947 }
948
Christopher Tate22e919d2018-02-16 16:16:50 -0800949 static long clampPositive(long val) {
950 return (val >= 0) ? val : Long.MAX_VALUE;
951 }
952
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700953 /**
954 * Sends alarms that were blocked due to user applied background restrictions - either because
955 * the user lifted those or the uid came to foreground.
956 *
957 * @param uid uid to filter on
958 * @param packageName package to filter on, or null for all packages in uid
959 */
960 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
961 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
962 if (alarmsForUid == null || alarmsForUid.size() == 0) {
963 return;
964 }
965 final ArrayList<Alarm> alarmsToDeliver;
966 if (packageName != null) {
967 if (DEBUG_BG_LIMIT) {
968 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
969 }
970 alarmsToDeliver = new ArrayList<>();
971 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
972 final Alarm a = alarmsForUid.get(i);
973 if (a.matches(packageName)) {
974 alarmsToDeliver.add(alarmsForUid.remove(i));
975 }
976 }
977 if (alarmsForUid.size() == 0) {
978 mPendingBackgroundAlarms.remove(uid);
979 }
980 } else {
981 if (DEBUG_BG_LIMIT) {
982 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
983 }
984 alarmsToDeliver = alarmsForUid;
985 mPendingBackgroundAlarms.remove(uid);
986 }
987 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
988 }
989
Makoto Onuki2206af32017-11-21 16:25:35 -0800990 /**
991 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
992 * restricted.
993 *
994 * This is only called when the global "force all apps-standby" flag changes or when the
995 * power save whitelist changes, so it's okay to be slow.
996 */
997 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700998 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800999
1000 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1001 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1002
1003 if (alarmsToDeliver.size() > 0) {
1004 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
1005 }
1006 }
1007
1008 @VisibleForTesting
1009 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1010 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1011 Predicate<Alarm> isBackgroundRestricted) {
1012
1013 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1014 final int uid = pendingAlarms.keyAt(uidIndex);
1015 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1016
1017 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1018 final Alarm alarm = alarmsForUid.get(alarmIndex);
1019
1020 if (isBackgroundRestricted.test(alarm)) {
1021 continue;
1022 }
1023
1024 unrestrictedAlarms.add(alarm);
1025 alarmsForUid.remove(alarmIndex);
1026 }
1027
1028 if (alarmsForUid.size() == 0) {
1029 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001030 }
1031 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001032 }
1033
1034 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1035 final int N = alarms.size();
1036 boolean hasWakeup = false;
1037 for (int i = 0; i < N; i++) {
1038 final Alarm alarm = alarms.get(i);
1039 if (alarm.wakeup) {
1040 hasWakeup = true;
1041 }
1042 alarm.count = 1;
1043 // Recurring alarms may have passed several alarm intervals while the
1044 // alarm was kept pending. Send the appropriate trigger count.
1045 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001046 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001047 // Also schedule its next recurrence
1048 final long delta = alarm.count * alarm.repeatInterval;
1049 final long nextElapsed = alarm.whenElapsed + delta;
1050 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1051 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1052 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1053 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1054 // Kernel alarms will be rescheduled as needed in setImplLocked
1055 }
1056 }
1057 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1058 // No need to wakeup for non wakeup alarms
1059 if (mPendingNonWakeupAlarms.size() == 0) {
1060 mStartCurrentDelayTime = nowELAPSED;
1061 mNextNonWakeupDeliveryTime = nowELAPSED
1062 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1063 }
1064 mPendingNonWakeupAlarms.addAll(alarms);
1065 mNumDelayedAlarms += alarms.size();
1066 } else {
1067 if (DEBUG_BG_LIMIT) {
1068 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1069 }
1070 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1071 if (mPendingNonWakeupAlarms.size() > 0) {
1072 alarms.addAll(mPendingNonWakeupAlarms);
1073 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1074 mTotalDelayTime += thisDelayTime;
1075 if (mMaxDelayTime < thisDelayTime) {
1076 mMaxDelayTime = thisDelayTime;
1077 }
1078 mPendingNonWakeupAlarms.clear();
1079 }
1080 calculateDeliveryPriorities(alarms);
1081 Collections.sort(alarms, mAlarmDispatchComparator);
1082 deliverAlarmsLocked(alarms, nowELAPSED);
1083 }
1084 }
1085
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001086 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001087 if (RECORD_DEVICE_IDLE_ALARMS) {
1088 IdleDispatchEntry ent = new IdleDispatchEntry();
1089 ent.uid = 0;
1090 ent.pkg = "FINISH IDLE";
1091 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1092 mAllowWhileIdleDispatches.add(ent);
1093 }
1094
Dianne Hackborn35d54032015-04-23 10:30:43 -07001095 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001096 if (mPendingWhileIdleAlarms.size() > 0) {
1097 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1098 mPendingWhileIdleAlarms = new ArrayList<>();
1099 final long nowElapsed = SystemClock.elapsedRealtime();
1100 for (int i=alarms.size() - 1; i >= 0; i--) {
1101 Alarm a = alarms.get(i);
1102 reAddAlarmLocked(a, nowElapsed, false);
1103 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001104 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001105
1106 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001107 rescheduleKernelAlarmsLocked();
1108 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001109
1110 // And send a TIME_TICK right now, since it is important to get the UI updated.
1111 try {
1112 mTimeTickSender.send();
1113 } catch (PendingIntent.CanceledException e) {
1114 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001115 }
1116
Christopher Tate14a7bb02015-10-01 10:24:31 -07001117 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001118 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001119 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001120 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001121 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001122 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001123 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001124 final BroadcastStats mBroadcastStats;
1125 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001126 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001127
Christopher Tate14a7bb02015-10-01 10:24:31 -07001128 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1129 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1130 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001131 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001132 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001133 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001134 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001135 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001136 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001137 mBroadcastStats = (pendingIntent != null)
1138 ? service.getStatsLocked(pendingIntent)
1139 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001140 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001141 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001142 fs = new FilterStats(mBroadcastStats, mTag);
1143 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001144 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001145 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001146 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001147 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001148 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001149
1150 @Override
1151 public String toString() {
1152 return "InFlight{"
1153 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001154 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001155 + ", workSource=" + mWorkSource
1156 + ", uid=" + mUid
1157 + ", tag=" + mTag
1158 + ", broadcastStats=" + mBroadcastStats
1159 + ", filterStats=" + mFilterStats
1160 + ", alarmType=" + mAlarmType
1161 + "}";
1162 }
Kweku Adams61e03292017-10-19 14:27:12 -07001163
1164 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1165 final long token = proto.start(fieldId);
1166
1167 proto.write(InFlightProto.UID, mUid);
1168 proto.write(InFlightProto.TAG, mTag);
1169 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1170 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1171 if (mPendingIntent != null) {
1172 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1173 }
1174 if (mBroadcastStats != null) {
1175 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1176 }
1177 if (mFilterStats != null) {
1178 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1179 }
1180 if (mWorkSource != null) {
1181 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1182 }
1183
1184 proto.end(token);
1185 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001186 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001187
Adam Lesinski182f73f2013-12-05 16:48:06 -08001188 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001189 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001190 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001191
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001192 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001194 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001195 int numWakeup;
1196 long startTime;
1197 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001198
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001199 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001200 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001201 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001202 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001203
1204 @Override
1205 public String toString() {
1206 return "FilterStats{"
1207 + "tag=" + mTag
1208 + ", lastTime=" + lastTime
1209 + ", aggregateTime=" + aggregateTime
1210 + ", count=" + count
1211 + ", numWakeup=" + numWakeup
1212 + ", startTime=" + startTime
1213 + ", nesting=" + nesting
1214 + "}";
1215 }
Kweku Adams61e03292017-10-19 14:27:12 -07001216
1217 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1218 final long token = proto.start(fieldId);
1219
1220 proto.write(FilterStatsProto.TAG, mTag);
1221 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1222 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1223 proto.write(FilterStatsProto.COUNT, count);
1224 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1225 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1226 proto.write(FilterStatsProto.NESTING, nesting);
1227
1228 proto.end(token);
1229 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001230 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001231
Adam Lesinski182f73f2013-12-05 16:48:06 -08001232 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001233 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001234 final String mPackageName;
1235
1236 long aggregateTime;
1237 int count;
1238 int numWakeup;
1239 long startTime;
1240 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001241 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001242
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001243 BroadcastStats(int uid, String packageName) {
1244 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001245 mPackageName = packageName;
1246 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001247
1248 @Override
1249 public String toString() {
1250 return "BroadcastStats{"
1251 + "uid=" + mUid
1252 + ", packageName=" + mPackageName
1253 + ", aggregateTime=" + aggregateTime
1254 + ", count=" + count
1255 + ", numWakeup=" + numWakeup
1256 + ", startTime=" + startTime
1257 + ", nesting=" + nesting
1258 + "}";
1259 }
Kweku Adams61e03292017-10-19 14:27:12 -07001260
1261 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1262 final long token = proto.start(fieldId);
1263
1264 proto.write(BroadcastStatsProto.UID, mUid);
1265 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1266 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1267 proto.write(BroadcastStatsProto.COUNT, count);
1268 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1269 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1270 proto.write(BroadcastStatsProto.NESTING, nesting);
1271
1272 proto.end(token);
1273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001275
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001276 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1277 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001278
1279 int mNumDelayedAlarms = 0;
1280 long mTotalDelayTime = 0;
1281 long mMaxDelayTime = 0;
1282
Adam Lesinski182f73f2013-12-05 16:48:06 -08001283 @Override
1284 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001285 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001286 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001287
1288 // We have to set current TimeZone info to kernel
1289 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001290 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001291
Christopher Tate247571462017-04-10 11:45:05 -07001292 if (mNativeData != 0) {
Christopher Tatebfbd9882018-12-11 14:55:19 -08001293 // Ensure that we're booting with a halfway sensible current time. Use the
1294 // most recent of Build.TIME, the root file system's timestamp, and the
1295 // value of the ro.build.date.utc system property (which is in seconds).
1296 final long systemBuildTime = Long.max(
1297 1000L * SystemProperties.getLong("ro.build.date.utc", -1L),
1298 Long.max(Environment.getRootDirectory().lastModified(), Build.TIME));
Christopher Tate247571462017-04-10 11:45:05 -07001299 if (System.currentTimeMillis() < systemBuildTime) {
1300 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1301 + ", advancing to build time " + systemBuildTime);
1302 setKernelTime(mNativeData, systemBuildTime);
1303 }
1304 }
1305
Christopher Tatebb9cce52017-04-18 14:19:43 -07001306 // Determine SysUI's uid
1307 final PackageManager packMan = getContext().getPackageManager();
1308 try {
1309 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1310 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1311 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1312 mSystemUiUid = sysUi.uid;
1313 } else {
1314 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1315 + " defined by non-privileged app " + sysUi.packageName
1316 + " - ignoring");
1317 }
1318 } catch (NameNotFoundException e) {
1319 }
1320
1321 if (mSystemUiUid <= 0) {
1322 Slog.wtf(TAG, "SysUI package not found!");
1323 }
1324
Adam Lesinski182f73f2013-12-05 16:48:06 -08001325 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001326 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001327
Adam Lesinski182f73f2013-12-05 16:48:06 -08001328 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001329 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001330 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001331 | Intent.FLAG_RECEIVER_FOREGROUND
1332 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001333 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001334 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001335 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1336 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001337 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001338 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001339
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001340 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001341 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 mClockReceiver.scheduleTimeTickEvent();
1343 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001344 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001346
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001347 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001348 AlarmThread waitThread = new AlarmThread();
1349 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001351 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001352 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001353
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001354 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001355 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001356 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1357 | ActivityManager.UID_OBSERVER_ACTIVE,
1358 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001359 } catch (RemoteException e) {
1360 // ignored; both services live in system_server
1361 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001362 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001364
1365 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001366 public void onBootPhase(int phase) {
1367 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1368 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001369 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001370 mLocalDeviceIdleController
1371 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001372 mUsageStatsManagerInternal = LocalServices.getService(UsageStatsManagerInternal.class);
1373 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001374
1375 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1376 mAppStateTracker.addListener(mForceAppStandbyListener);
Dianne Hackborna750a632015-06-16 17:18:23 -07001377 }
1378 }
1379
1380 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 protected void finalize() throws Throwable {
1382 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001383 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 } finally {
1385 super.finalize();
1386 }
1387 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001388
mswest463f4c99d2018-02-01 10:13:10 -08001389 boolean setTimeImpl(long millis) {
1390 if (mNativeData == 0) {
1391 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1392 return false;
1393 }
1394
1395 synchronized (mLock) {
1396 return setKernelTime(mNativeData, millis) == 0;
1397 }
1398 }
1399
Adam Lesinski182f73f2013-12-05 16:48:06 -08001400 void setTimeZoneImpl(String tz) {
1401 if (TextUtils.isEmpty(tz)) {
1402 return;
David Christieebe51fc2013-07-26 13:23:29 -07001403 }
1404
Adam Lesinski182f73f2013-12-05 16:48:06 -08001405 TimeZone zone = TimeZone.getTimeZone(tz);
1406 // Prevent reentrant calls from stepping on each other when writing
1407 // the time zone property
1408 boolean timeZoneWasChanged = false;
1409 synchronized (this) {
1410 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1411 if (current == null || !current.equals(zone.getID())) {
1412 if (localLOGV) {
1413 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1414 }
1415 timeZoneWasChanged = true;
1416 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1417 }
1418
1419 // Update the kernel timezone information
1420 // Kernel tracks time offsets as 'minutes west of GMT'
1421 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001422 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001423 }
1424
1425 TimeZone.setDefault(null);
1426
1427 if (timeZoneWasChanged) {
1428 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001429 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001430 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001431 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001432 intent.putExtra("time-zone", zone.getID());
1433 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001436
Adam Lesinski182f73f2013-12-05 16:48:06 -08001437 void removeImpl(PendingIntent operation) {
1438 if (operation == null) {
1439 return;
1440 }
1441 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001442 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001443 }
1444 }
1445
1446 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001447 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1448 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1449 int callingUid, String callingPackage) {
1450 // must be *either* PendingIntent or AlarmReceiver, but not both
1451 if ((operation == null && directReceiver == null)
1452 || (operation != null && directReceiver != null)) {
1453 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1454 // NB: previous releases failed silently here, so we are continuing to do the same
1455 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 return;
1457 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001458
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001459 // Sanity check the window length. This will catch people mistakenly
1460 // trying to pass an end-of-window timestamp rather than a duration.
1461 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1462 Slog.w(TAG, "Window length " + windowLength
1463 + "ms suspiciously long; limiting to 1 hour");
1464 windowLength = AlarmManager.INTERVAL_HOUR;
1465 }
1466
Christopher Tate498c6cb2014-11-17 16:09:27 -08001467 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001468 // seconds when the API expects milliseconds, or apps trying shenanigans
1469 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001470 final long minInterval = mConstants.MIN_INTERVAL;
1471 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001472 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001473 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001474 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001475 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001476 } else if (interval > mConstants.MAX_INTERVAL) {
1477 Slog.w(TAG, "Suspiciously long interval " + interval
1478 + " millis; clamping");
1479 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001480 }
1481
Christopher Tatee0a22b32013-07-11 14:43:13 -07001482 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1483 throw new IllegalArgumentException("Invalid alarm type " + type);
1484 }
1485
Christopher Tate5f221e82013-07-30 17:13:15 -07001486 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001487 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001488 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001489 + " pid=" + what);
1490 triggerAtTime = 0;
1491 }
1492
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001493 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001494 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1495 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001496 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001497 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1498
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001499 final long maxElapsed;
1500 if (windowLength == AlarmManager.WINDOW_EXACT) {
1501 maxElapsed = triggerElapsed;
1502 } else if (windowLength < 0) {
1503 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001504 // Fix this window in place, so that as time approaches we don't collapse it.
1505 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001506 } else {
1507 maxElapsed = triggerElapsed + windowLength;
1508 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001511 if (DEBUG_BATCH) {
1512 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001513 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001514 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001515 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001517 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001518 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1519 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001522
Christopher Tate3e04b472013-10-21 17:51:31 -07001523 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001524 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1525 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1526 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001527 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001528 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1529 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001530 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001531 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001532 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1533 + " -- package not allowed to start");
1534 return;
1535 }
1536 } catch (RemoteException e) {
1537 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001538 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001539 setImplLocked(a, false, doValidate);
1540 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001541
Christopher Tatef2159712018-03-27 16:04:14 -07001542 /**
1543 * Return the minimum time that should elapse before an app in the specified bucket
1544 * can receive alarms again
1545 */
Suprabh Shukla75edab12018-01-29 14:09:06 -08001546 private long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001547 // UsageStats bucket values are treated as floors of their behavioral range.
1548 // In other words, a bucket value between WORKING and ACTIVE is treated as
1549 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1550 // values.
1551 final int index;
1552
1553 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1554 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1555 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1556 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1557 else index = ACTIVE_INDEX;
1558
1559 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001560 }
1561
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001562 /**
1563 * Adjusts the alarm delivery time based on the current app standby bucket.
1564 * @param alarm The alarm to adjust
1565 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001566 */
1567 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001568 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001569 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001570 }
1571 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001572 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001573 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001574 alarm.whenElapsed = alarm.expectedWhenElapsed;
1575 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1576 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001577 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001578 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001579 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001580 final long oldWhenElapsed = alarm.whenElapsed;
1581 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1582
Suprabh Shukla75edab12018-01-29 14:09:06 -08001583 final String sourcePackage = alarm.sourcePackage;
1584 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1585 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
1586 sourcePackage, sourceUserId, SystemClock.elapsedRealtime());
1587
1588 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1589 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1590 if (lastElapsed > 0) {
1591 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001592 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001593 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001594 } else {
1595 // app is now eligible to run alarms at the originally requested window.
1596 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001597 alarm.whenElapsed = alarm.expectedWhenElapsed;
1598 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001599 }
1600 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001601 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001602 }
1603
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001604 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1605 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001606 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001607 // The caller has given the time they want this to happen at, however we need
1608 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001609 // bring us out of idle at an earlier time.
1610 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001611 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001612 }
1613 // Add fuzz to make the alarm go off some time before the actual desired time.
1614 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001615 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001616 if (fuzz > 0) {
1617 if (mRandom == null) {
1618 mRandom = new Random();
1619 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001620 final int delta = mRandom.nextInt(fuzz);
1621 a.whenElapsed -= delta;
1622 if (false) {
1623 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1624 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1625 Slog.d(TAG, "Applied fuzz: " + fuzz);
1626 Slog.d(TAG, "Final delta: " + delta);
1627 Slog.d(TAG, "Final when: " + a.whenElapsed);
1628 }
1629 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001630 }
1631
1632 } else if (mPendingIdleUntil != null) {
1633 // We currently have an idle until alarm scheduled; if the new alarm has
1634 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001635 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1636 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1637 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001638 == 0) {
1639 mPendingWhileIdleAlarms.add(a);
1640 return;
1641 }
1642 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001643 if (RECORD_DEVICE_IDLE_ALARMS) {
1644 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1645 IdleDispatchEntry ent = new IdleDispatchEntry();
1646 ent.uid = a.uid;
1647 ent.pkg = a.operation.getCreatorPackage();
1648 ent.tag = a.operation.getTag("");
1649 ent.op = "SET";
1650 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1651 ent.argRealtime = a.whenElapsed;
1652 mAllowWhileIdleDispatches.add(ent);
1653 }
1654 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001655 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001656 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001658 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001659 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001660 }
1661
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001662 boolean needRebatch = false;
1663
1664 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001665 if (RECORD_DEVICE_IDLE_ALARMS) {
1666 if (mPendingIdleUntil == null) {
1667 IdleDispatchEntry ent = new IdleDispatchEntry();
1668 ent.uid = 0;
1669 ent.pkg = "START IDLE";
1670 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1671 mAllowWhileIdleDispatches.add(ent);
1672 }
1673 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001674 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1675 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1676 + " to " + a);
1677 }
1678
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001679 mPendingIdleUntil = a;
1680 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001681 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1682 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1683 mNextWakeFromIdle = a;
1684 // If this wake from idle is earlier than whatever was previously scheduled,
1685 // and we are currently idling, then we need to rebatch alarms in case the idle
1686 // until time needs to be updated.
1687 if (mPendingIdleUntil != null) {
1688 needRebatch = true;
1689 }
1690 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001691 }
1692
1693 if (!rebatching) {
1694 if (DEBUG_VALIDATE) {
1695 if (doValidate && !validateConsistencyLocked()) {
1696 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1697 + " when(hex)=" + Long.toHexString(a.when)
1698 + " whenElapsed=" + a.whenElapsed
1699 + " maxWhenElapsed=" + a.maxWhenElapsed
1700 + " interval=" + a.repeatInterval + " op=" + a.operation
1701 + " flags=0x" + Integer.toHexString(a.flags));
1702 rebatchAllAlarmsLocked(false);
1703 needRebatch = false;
1704 }
1705 }
1706
1707 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001708 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001709 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001710
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001711 rescheduleKernelAlarmsLocked();
1712 updateNextAlarmClockLocked();
1713 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001714 }
1715
Christopher Tate1d99c392017-12-07 16:54:04 -08001716 /**
1717 * System-process internal API
1718 */
1719 private final class LocalService implements AlarmManagerInternal {
1720 @Override
1721 public void removeAlarmsForUid(int uid) {
1722 synchronized (mLock) {
1723 removeLocked(uid);
1724 }
1725 }
1726 }
1727
1728 /**
1729 * Public-facing binder interface
1730 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001731 private final IBinder mService = new IAlarmManager.Stub() {
1732 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001733 public void set(String callingPackage,
1734 int type, long triggerAtTime, long windowLength, long interval, int flags,
1735 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1736 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001737 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001738
1739 // make sure the caller is not lying about which package should be blamed for
1740 // wakelock time spent in alarm delivery
1741 mAppOps.checkPackage(callingUid, callingPackage);
1742
1743 // Repeating alarms must use PendingIntent, not direct listener
1744 if (interval != 0) {
1745 if (directReceiver != null) {
1746 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1747 }
1748 }
1749
Adam Lesinski182f73f2013-12-05 16:48:06 -08001750 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001751 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001752 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001753 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001754 }
1755
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001756 // No incoming callers can request either WAKE_FROM_IDLE or
1757 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1758 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1759 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1760
1761 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1762 // manager when to come out of idle mode, which is only for DeviceIdleController.
1763 if (callingUid != Process.SYSTEM_UID) {
1764 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1765 }
1766
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001767 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001768 if (windowLength == AlarmManager.WINDOW_EXACT) {
1769 flags |= AlarmManager.FLAG_STANDALONE;
1770 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001771
1772 // If this alarm is for an alarm clock, then it must be standalone and we will
1773 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001774 if (alarmClock != null) {
1775 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001776
1777 // If the caller is a core system component or on the user's whitelist, and not calling
1778 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1779 // This means we will allow these alarms to go off as normal even while idle, with no
1780 // timing restrictions.
1781 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001782 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001783 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001784 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001785 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1786 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001787 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001788
Christopher Tate14a7bb02015-10-01 10:24:31 -07001789 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1790 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001791 }
Christopher Tate89779822012-08-31 14:40:03 -07001792
Adam Lesinski182f73f2013-12-05 16:48:06 -08001793 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001794 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001795 getContext().enforceCallingOrSelfPermission(
1796 "android.permission.SET_TIME",
1797 "setTime");
1798
mswest463f4c99d2018-02-01 10:13:10 -08001799 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001800 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001801
1802 @Override
1803 public void setTimeZone(String tz) {
1804 getContext().enforceCallingOrSelfPermission(
1805 "android.permission.SET_TIME_ZONE",
1806 "setTimeZone");
1807
1808 final long oldId = Binder.clearCallingIdentity();
1809 try {
1810 setTimeZoneImpl(tz);
1811 } finally {
1812 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001813 }
1814 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001815
Adam Lesinski182f73f2013-12-05 16:48:06 -08001816 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001817 public void remove(PendingIntent operation, IAlarmListener listener) {
1818 if (operation == null && listener == null) {
1819 Slog.w(TAG, "remove() with no intent or listener");
1820 return;
1821 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001822
Christopher Tate14a7bb02015-10-01 10:24:31 -07001823 synchronized (mLock) {
1824 removeLocked(operation, listener);
1825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001827
Adam Lesinski182f73f2013-12-05 16:48:06 -08001828 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001829 public long getNextWakeFromIdleTime() {
1830 return getNextWakeFromIdleTimeImpl();
1831 }
1832
1833 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001834 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001835 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1836 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1837 "getNextAlarmClock", null);
1838
1839 return getNextAlarmClockImpl(userId);
1840 }
1841
1842 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001843 public long currentNetworkTimeMillis() {
1844 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1845 if (time.hasCache()) {
1846 return time.currentTimeMillis();
1847 } else {
1848 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1849 }
1850 }
1851
1852 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001853 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001854 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001855
1856 if (args.length > 0 && "--proto".equals(args[0])) {
1857 dumpProto(fd);
1858 } else {
1859 dumpImpl(pw);
1860 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001861 }
mswest463f4c99d2018-02-01 10:13:10 -08001862
1863 @Override
1864 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1865 FileDescriptor err, String[] args, ShellCallback callback,
1866 ResultReceiver resultReceiver) {
1867 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1868 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001869 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001870
Adam Lesinski182f73f2013-12-05 16:48:06 -08001871 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 synchronized (mLock) {
1873 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001874 mConstants.dump(pw);
1875 pw.println();
1876
Makoto Onukie4918212018-02-06 11:30:15 -08001877 if (mAppStateTracker != null) {
1878 mAppStateTracker.dump(pw, " ");
1879 pw.println();
1880 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001881
Suprabh Shukla75edab12018-01-29 14:09:06 -08001882 pw.println(" App Standby Parole: " + mAppStandbyParole);
1883 pw.println();
1884
Christopher Tatee0a22b32013-07-11 14:43:13 -07001885 final long nowRTC = System.currentTimeMillis();
1886 final long nowELAPSED = SystemClock.elapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001887 final long nowUPTIME = SystemClock.uptimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001888 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001889
Dianne Hackborna750a632015-06-16 17:18:23 -07001890 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001891 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001892 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001893 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001894 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001895 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001896 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1897 pw.print(" mLastTickIssued=");
Makoto Onuki5d93b832018-01-10 16:12:39 -08001898 pw.println(sdf.format(new Date(nowRTC - (nowELAPSED - mLastTickIssued))));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001899 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1900 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001901 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1902 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001903
1904 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1905 if (ssm != null) {
1906 pw.println();
1907 pw.print(" RuntimeStarted=");
1908 pw.print(sdf.format(
1909 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1910 if (ssm.isRuntimeRestarted()) {
1911 pw.print(" (Runtime restarted)");
1912 }
1913 pw.println();
1914 pw.print(" Runtime uptime (elapsed): ");
1915 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1916 pw.println();
1917 pw.print(" Runtime uptime (uptime): ");
1918 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1919 pw.println();
1920 }
1921
Dianne Hackbornc3527222015-05-13 14:03:20 -07001922 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001923 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001924 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001925 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1926 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001927 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001928 pw.print(" Max wakeup delay: ");
1929 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1930 pw.println();
1931 pw.print(" Time since last dispatch: ");
1932 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1933 pw.println();
1934 pw.print(" Next non-wakeup delivery time: ");
1935 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1936 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001937
1938 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1939 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001940 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001941 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001942 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001943 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001944 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
1945 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001946 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Christopher Tate8b98ade2018-02-09 11:13:19 -08001947 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1948 pw.println();
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001949 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08001950 pw.print(" = "); pw.println(mLastWakeup);
1951 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
1952 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07001953 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001954
John Spurlock604a5ee2015-06-01 12:27:22 -04001955 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001956 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001957 final TreeSet<Integer> users = new TreeSet<>();
1958 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1959 users.add(mNextAlarmClockForUser.keyAt(i));
1960 }
1961 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1962 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1963 }
1964 for (int user : users) {
1965 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1966 final long time = next != null ? next.getTriggerTime() : 0;
1967 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001968 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001969 pw.print(" pendingSend:"); pw.print(pendingSend);
1970 pw.print(" time:"); pw.print(time);
1971 if (time > 0) {
1972 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1973 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1974 }
1975 pw.println();
1976 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001977 if (mAlarmBatches.size() > 0) {
1978 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001979 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001980 pw.println(mAlarmBatches.size());
1981 for (Batch b : mAlarmBatches) {
1982 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001983 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001984 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001986 pw.println();
1987 pw.println(" Pending user blocked background alarms: ");
1988 boolean blocked = false;
1989 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1990 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1991 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1992 blocked = true;
1993 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1994 }
1995 }
1996 if (!blocked) {
1997 pw.println(" none");
1998 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08001999
Suprabh Shukla75edab12018-01-29 14:09:06 -08002000 pw.println(" mLastAlarmDeliveredForPackage:");
2001 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2002 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2003 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2004 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2005 pw.println();
2006 }
2007 pw.println();
2008
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002009 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002010 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002011 pw.println(" Idle mode state:");
2012 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002013 if (mPendingIdleUntil != null) {
2014 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002015 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002016 } else {
2017 pw.println("null");
2018 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002019 pw.println(" Pending alarms:");
2020 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002021 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002022 if (mNextWakeFromIdle != null) {
2023 pw.println();
2024 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002025 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002026 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002027
2028 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002029 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002030 if (mPendingNonWakeupAlarms.size() > 0) {
2031 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002032 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002033 } else {
2034 pw.println("(none)");
2035 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002036 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002037 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2038 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002039 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002040 pw.print(", max non-interactive time: ");
2041 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2042 pw.println();
2043
2044 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002045 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002046 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2047 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2048 pw.print(" Listener send count: "); pw.println(mListenerCount);
2049 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002050 pw.println();
2051
Christopher Tate7f2a0352015-12-08 10:24:33 -08002052 if (mInFlight.size() > 0) {
2053 pw.println("Outstanding deliveries:");
2054 for (int i = 0; i < mInFlight.size(); i++) {
2055 pw.print(" #"); pw.print(i); pw.print(": ");
2056 pw.println(mInFlight.get(i));
2057 }
2058 pw.println();
2059 }
2060
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002061 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002062 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002063 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002064 pw.print(" UID ");
2065 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2066 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002067 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002068 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2069 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2070
2071 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2072 pw.print(" Next allowed:");
2073 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2074 pw.print(" (");
2075 TimeUtils.formatDuration(minInterval, 0, pw);
2076 pw.print(")");
2077
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002078 pw.println();
2079 }
2080 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002081
2082 pw.print(" mUseAllowWhileIdleShortTime: [");
2083 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2084 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2085 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2086 pw.print(" ");
2087 }
2088 }
2089 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002090 pw.println();
2091
Dianne Hackborn81038902012-11-26 17:04:09 -08002092 if (mLog.dump(pw, " Recent problems", " ")) {
2093 pw.println();
2094 }
2095
2096 final FilterStats[] topFilters = new FilterStats[10];
2097 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2098 @Override
2099 public int compare(FilterStats lhs, FilterStats rhs) {
2100 if (lhs.aggregateTime < rhs.aggregateTime) {
2101 return 1;
2102 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2103 return -1;
2104 }
2105 return 0;
2106 }
2107 };
2108 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002109 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002110 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2111 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2112 for (int ip=0; ip<uidStats.size(); ip++) {
2113 BroadcastStats bs = uidStats.valueAt(ip);
2114 for (int is=0; is<bs.filterStats.size(); is++) {
2115 FilterStats fs = bs.filterStats.valueAt(is);
2116 int pos = len > 0
2117 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2118 if (pos < 0) {
2119 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002120 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002121 if (pos < topFilters.length) {
2122 int copylen = topFilters.length - pos - 1;
2123 if (copylen > 0) {
2124 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2125 }
2126 topFilters[pos] = fs;
2127 if (len < topFilters.length) {
2128 len++;
2129 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002130 }
2131 }
2132 }
2133 }
2134 if (len > 0) {
2135 pw.println(" Top Alarms:");
2136 for (int i=0; i<len; i++) {
2137 FilterStats fs = topFilters[i];
2138 pw.print(" ");
2139 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2140 TimeUtils.formatDuration(fs.aggregateTime, pw);
2141 pw.print(" running, "); pw.print(fs.numWakeup);
2142 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002143 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2144 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002145 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002146 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002147 pw.println();
2148 }
2149 }
2150
2151 pw.println(" ");
2152 pw.println(" Alarm Stats:");
2153 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002154 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2155 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2156 for (int ip=0; ip<uidStats.size(); ip++) {
2157 BroadcastStats bs = uidStats.valueAt(ip);
2158 pw.print(" ");
2159 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2160 UserHandle.formatUid(pw, bs.mUid);
2161 pw.print(":");
2162 pw.print(bs.mPackageName);
2163 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2164 pw.print(" running, "); pw.print(bs.numWakeup);
2165 pw.println(" wakeups:");
2166 tmpFilters.clear();
2167 for (int is=0; is<bs.filterStats.size(); is++) {
2168 tmpFilters.add(bs.filterStats.valueAt(is));
2169 }
2170 Collections.sort(tmpFilters, comparator);
2171 for (int i=0; i<tmpFilters.size(); i++) {
2172 FilterStats fs = tmpFilters.get(i);
2173 pw.print(" ");
2174 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2175 TimeUtils.formatDuration(fs.aggregateTime, pw);
2176 pw.print(" "); pw.print(fs.numWakeup);
2177 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002178 pw.print(" alarms, last ");
2179 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2180 pw.println(":");
2181 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002182 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002183 pw.println();
2184 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002185 }
2186 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002187 pw.println();
2188 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002189
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002190 if (RECORD_DEVICE_IDLE_ALARMS) {
2191 pw.println();
2192 pw.println(" Allow while idle dispatches:");
2193 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2194 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2195 pw.print(" ");
2196 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2197 pw.print(": ");
2198 UserHandle.formatUid(pw, ent.uid);
2199 pw.print(":");
2200 pw.println(ent.pkg);
2201 if (ent.op != null) {
2202 pw.print(" ");
2203 pw.print(ent.op);
2204 pw.print(" / ");
2205 pw.print(ent.tag);
2206 if (ent.argRealtime != 0) {
2207 pw.print(" (");
2208 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2209 pw.print(")");
2210 }
2211 pw.println();
2212 }
2213 }
2214 }
2215
Christopher Tate18a75f12013-07-01 18:18:59 -07002216 if (WAKEUP_STATS) {
2217 pw.println();
2218 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002219 long last = -1;
2220 for (WakeupEvent event : mRecentWakeups) {
2221 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2222 pw.print('|');
2223 if (last < 0) {
2224 pw.print('0');
2225 } else {
2226 pw.print(event.when - last);
2227 }
2228 last = event.when;
2229 pw.print('|'); pw.print(event.uid);
2230 pw.print('|'); pw.print(event.action);
2231 pw.println();
2232 }
2233 pw.println();
2234 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002235 }
2236 }
2237
Kweku Adams61e03292017-10-19 14:27:12 -07002238 void dumpProto(FileDescriptor fd) {
2239 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2240
2241 synchronized (mLock) {
2242 final long nowRTC = System.currentTimeMillis();
2243 final long nowElapsed = SystemClock.elapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002244 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2245 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2246 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002247 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002248 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002249 mLastTimeChangeRealtime);
2250
Yi Jin2b30f322018-02-20 15:41:47 -08002251 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002252
Makoto Onukie4918212018-02-06 11:30:15 -08002253 if (mAppStateTracker != null) {
2254 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002255 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002256 }
Kweku Adams61e03292017-10-19 14:27:12 -07002257
Yi Jin2b30f322018-02-20 15:41:47 -08002258 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002259 if (!mInteractive) {
2260 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002261 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002262 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002263 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002264 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002265 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002266 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002267 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002268 nowElapsed - mNextNonWakeupDeliveryTime);
2269 }
2270
Yi Jin2b30f322018-02-20 15:41:47 -08002271 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002272 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002273 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002274 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002275 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002276 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002277 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002278 nowElapsed - mLastWakeupSet);
Yi Jin2b30f322018-02-20 15:41:47 -08002279 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002280
2281 final TreeSet<Integer> users = new TreeSet<>();
2282 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2283 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2284 users.add(mNextAlarmClockForUser.keyAt(i));
2285 }
2286 final int pendingSendNextAlarmClockChangedForUserSize =
2287 mPendingSendNextAlarmClockChangedForUser.size();
2288 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2289 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2290 }
2291 for (int user : users) {
2292 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2293 final long time = next != null ? next.getTriggerTime() : 0;
2294 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002295 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002296 proto.write(AlarmClockMetadataProto.USER, user);
2297 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2298 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2299 proto.end(aToken);
2300 }
2301 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002302 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002303 nowElapsed, nowRTC);
2304 }
2305 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2306 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2307 if (blockedAlarms != null) {
2308 for (Alarm a : blockedAlarms) {
2309 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002310 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002311 nowElapsed, nowRTC);
2312 }
2313 }
2314 }
2315 if (mPendingIdleUntil != null) {
2316 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002317 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002318 }
2319 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002320 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002321 nowElapsed, nowRTC);
2322 }
2323 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002324 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002325 nowElapsed, nowRTC);
2326 }
2327
2328 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002329 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002330 nowElapsed, nowRTC);
2331 }
2332
Yi Jin2b30f322018-02-20 15:41:47 -08002333 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2334 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2335 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2336 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002337 mNonInteractiveTime);
2338
Yi Jin2b30f322018-02-20 15:41:47 -08002339 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2340 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2341 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2342 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2343 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002344
2345 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002346 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002347 }
2348
Kweku Adams61e03292017-10-19 14:27:12 -07002349 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2350 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002351 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002352 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2353 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2354
Yi Jin2b30f322018-02-20 15:41:47 -08002355 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2356 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2357 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002358 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002359 proto.end(token);
2360 }
2361
Makoto Onukiadb50d82018-01-29 16:20:30 -08002362 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2363 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002364 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002365 mUseAllowWhileIdleShortTime.keyAt(i));
2366 }
2367 }
2368
Yi Jin2b30f322018-02-20 15:41:47 -08002369 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002370
2371 final FilterStats[] topFilters = new FilterStats[10];
2372 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2373 @Override
2374 public int compare(FilterStats lhs, FilterStats rhs) {
2375 if (lhs.aggregateTime < rhs.aggregateTime) {
2376 return 1;
2377 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2378 return -1;
2379 }
2380 return 0;
2381 }
2382 };
2383 int len = 0;
2384 // Get the top 10 FilterStats, ordered by aggregateTime.
2385 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2386 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2387 for (int ip = 0; ip < uidStats.size(); ++ip) {
2388 BroadcastStats bs = uidStats.valueAt(ip);
2389 for (int is = 0; is < bs.filterStats.size(); ++is) {
2390 FilterStats fs = bs.filterStats.valueAt(is);
2391 int pos = len > 0
2392 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2393 if (pos < 0) {
2394 pos = -pos - 1;
2395 }
2396 if (pos < topFilters.length) {
2397 int copylen = topFilters.length - pos - 1;
2398 if (copylen > 0) {
2399 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2400 }
2401 topFilters[pos] = fs;
2402 if (len < topFilters.length) {
2403 len++;
2404 }
2405 }
2406 }
2407 }
2408 }
2409 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002410 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002411 FilterStats fs = topFilters[i];
2412
Yi Jin2b30f322018-02-20 15:41:47 -08002413 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2414 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002415 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002416 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002417
2418 proto.end(token);
2419 }
2420
2421 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2422 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2423 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2424 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002425 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002426
2427 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002428 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002429
2430 // uidStats is an ArrayMap, which we can't sort.
2431 tmpFilters.clear();
2432 for (int is = 0; is < bs.filterStats.size(); ++is) {
2433 tmpFilters.add(bs.filterStats.valueAt(is));
2434 }
2435 Collections.sort(tmpFilters, comparator);
2436 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002437 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002438 }
2439
2440 proto.end(token);
2441 }
2442 }
2443
2444 if (RECORD_DEVICE_IDLE_ALARMS) {
2445 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2446 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2447 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002448 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002449
2450 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2451 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2452 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2453 proto.write(IdleDispatchEntryProto.OP, ent.op);
2454 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2455 ent.elapsedRealtime);
2456 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2457
2458 proto.end(token);
2459 }
2460 }
2461
2462 if (WAKEUP_STATS) {
2463 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002464 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002465 proto.write(WakeupEventProto.UID, event.uid);
2466 proto.write(WakeupEventProto.ACTION, event.action);
2467 proto.write(WakeupEventProto.WHEN, event.when);
2468 proto.end(token);
2469 }
2470 }
2471 }
2472
2473 proto.flush();
2474 }
2475
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002476 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002477 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2478 PrintWriter pw = new PrintWriter(bs);
2479 final long nowRTC = System.currentTimeMillis();
2480 final long nowELAPSED = SystemClock.elapsedRealtime();
2481 final int NZ = mAlarmBatches.size();
2482 for (int iz = 0; iz < NZ; iz++) {
2483 Batch bz = mAlarmBatches.get(iz);
2484 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002485 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002486 pw.flush();
2487 Slog.v(TAG, bs.toString());
2488 bs.reset();
2489 }
2490 }
2491
2492 private boolean validateConsistencyLocked() {
2493 if (DEBUG_VALIDATE) {
2494 long lastTime = Long.MIN_VALUE;
2495 final int N = mAlarmBatches.size();
2496 for (int i = 0; i < N; i++) {
2497 Batch b = mAlarmBatches.get(i);
2498 if (b.start >= lastTime) {
2499 // duplicate start times are okay because of standalone batches
2500 lastTime = b.start;
2501 } else {
2502 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002503 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2504 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002505 return false;
2506 }
2507 }
2508 }
2509 return true;
2510 }
2511
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002512 private Batch findFirstWakeupBatchLocked() {
2513 final int N = mAlarmBatches.size();
2514 for (int i = 0; i < N; i++) {
2515 Batch b = mAlarmBatches.get(i);
2516 if (b.hasWakeups()) {
2517 return b;
2518 }
2519 }
2520 return null;
2521 }
2522
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002523 long getNextWakeFromIdleTimeImpl() {
2524 synchronized (mLock) {
2525 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2526 }
2527 }
2528
2529 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002530 synchronized (mLock) {
2531 return mNextAlarmClockForUser.get(userId);
2532 }
2533 }
2534
2535 /**
2536 * Recomputes the next alarm clock for all users.
2537 */
2538 private void updateNextAlarmClockLocked() {
2539 if (!mNextAlarmClockMayChange) {
2540 return;
2541 }
2542 mNextAlarmClockMayChange = false;
2543
Jose Lima235510e2014-08-13 12:50:01 -07002544 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002545 nextForUser.clear();
2546
2547 final int N = mAlarmBatches.size();
2548 for (int i = 0; i < N; i++) {
2549 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2550 final int M = alarms.size();
2551
2552 for (int j = 0; j < M; j++) {
2553 Alarm a = alarms.get(j);
2554 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002555 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002556 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002557
2558 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002559 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002560 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002561 " for user " + userId);
2562 }
2563
2564 // Alarms and batches are sorted by time, no need to compare times here.
2565 if (nextForUser.get(userId) == null) {
2566 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002567 } else if (a.alarmClock.equals(current)
2568 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2569 // same/earlier time and it's the one we cited before, so stick with it
2570 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002571 }
2572 }
2573 }
2574 }
2575
2576 // Update mNextAlarmForUser with new values.
2577 final int NN = nextForUser.size();
2578 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002579 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002580 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002581 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002582 if (!newAlarm.equals(currentAlarm)) {
2583 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2584 }
2585 }
2586
2587 // Remove users without any alarm clocks scheduled.
2588 final int NNN = mNextAlarmClockForUser.size();
2589 for (int i = NNN - 1; i >= 0; i--) {
2590 int userId = mNextAlarmClockForUser.keyAt(i);
2591 if (nextForUser.get(userId) == null) {
2592 updateNextAlarmInfoForUserLocked(userId, null);
2593 }
2594 }
2595 }
2596
Jose Lima235510e2014-08-13 12:50:01 -07002597 private void updateNextAlarmInfoForUserLocked(int userId,
2598 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002599 if (alarmClock != null) {
2600 if (DEBUG_ALARM_CLOCK) {
2601 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002602 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002603 }
2604 mNextAlarmClockForUser.put(userId, alarmClock);
2605 } else {
2606 if (DEBUG_ALARM_CLOCK) {
2607 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2608 }
2609 mNextAlarmClockForUser.remove(userId);
2610 }
2611
2612 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2613 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2614 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2615 }
2616
2617 /**
2618 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2619 * for which alarm clocks have changed since the last call to this.
2620 *
2621 * Do not call with a lock held. Only call from mHandler's thread.
2622 *
2623 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2624 */
2625 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002626 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002627 pendingUsers.clear();
2628
2629 synchronized (mLock) {
2630 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2631 for (int i = 0; i < N; i++) {
2632 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2633 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2634 }
2635 mPendingSendNextAlarmClockChangedForUser.clear();
2636 }
2637
2638 final int N = pendingUsers.size();
2639 for (int i = 0; i < N; i++) {
2640 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002641 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002642 Settings.System.putStringForUser(getContext().getContentResolver(),
2643 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002644 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002645 userId);
2646
2647 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2648 new UserHandle(userId));
2649 }
2650 }
2651
2652 /**
2653 * Formats an alarm like platform/packages/apps/DeskClock used to.
2654 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002655 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2656 int userId) {
2657 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002658 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2659 return (info == null) ? "" :
2660 DateFormat.format(pattern, info.getTriggerTime()).toString();
2661 }
2662
Adam Lesinski182f73f2013-12-05 16:48:06 -08002663 void rescheduleKernelAlarmsLocked() {
2664 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2665 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002666 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002667 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002668 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002669 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002670 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002671 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002672 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002673 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002674 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002675 if (firstBatch != firstWakeup) {
2676 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002677 }
2678 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002679 if (mPendingNonWakeupAlarms.size() > 0) {
2680 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2681 nextNonWakeup = mNextNonWakeupDeliveryTime;
2682 }
2683 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002684 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002685 mNextNonWakeup = nextNonWakeup;
2686 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2687 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002688 }
2689
Christopher Tate14a7bb02015-10-01 10:24:31 -07002690 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002691 if (operation == null && directReceiver == null) {
2692 if (localLOGV) {
2693 Slog.w(TAG, "requested remove() of null operation",
2694 new RuntimeException("here"));
2695 }
2696 return;
2697 }
2698
Adam Lesinski182f73f2013-12-05 16:48:06 -08002699 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002700 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002701 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2702 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002703 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002704 if (b.size() == 0) {
2705 mAlarmBatches.remove(i);
2706 }
2707 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002708 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002709 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002710 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2711 mPendingWhileIdleAlarms.remove(i);
2712 }
2713 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002714 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2715 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2716 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2717 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2718 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2719 alarmsForUid.remove(j);
2720 }
2721 }
2722 if (alarmsForUid.size() == 0) {
2723 mPendingBackgroundAlarms.removeAt(i);
2724 }
2725 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002726 if (didRemove) {
2727 if (DEBUG_BATCH) {
2728 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2729 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002730 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002731 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002732 mPendingIdleUntil = null;
2733 restorePending = true;
2734 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002735 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002736 mNextWakeFromIdle = null;
2737 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002738 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002739 if (restorePending) {
2740 restorePendingWhileIdleAlarmsLocked();
2741 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002742 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002743 }
2744 }
2745
Christopher Tate1d99c392017-12-07 16:54:04 -08002746 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002747 if (uid == Process.SYSTEM_UID) {
2748 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2749 return;
2750 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002751 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002752 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002753 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2754 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002755 didRemove |= b.remove(whichAlarms);
2756 if (b.size() == 0) {
2757 mAlarmBatches.remove(i);
2758 }
2759 }
2760 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2761 final Alarm a = mPendingWhileIdleAlarms.get(i);
2762 if (a.uid == uid) {
2763 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2764 mPendingWhileIdleAlarms.remove(i);
2765 }
2766 }
2767 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2768 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2769 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2770 if (alarmsForUid.get(j).uid == uid) {
2771 alarmsForUid.remove(j);
2772 }
2773 }
2774 if (alarmsForUid.size() == 0) {
2775 mPendingBackgroundAlarms.removeAt(i);
2776 }
2777 }
2778 if (didRemove) {
2779 if (DEBUG_BATCH) {
2780 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2781 }
2782 rebatchAllAlarmsLocked(true);
2783 rescheduleKernelAlarmsLocked();
2784 updateNextAlarmClockLocked();
2785 }
2786 }
2787
2788 void removeLocked(final String packageName) {
2789 if (packageName == null) {
2790 if (localLOGV) {
2791 Slog.w(TAG, "requested remove() of null packageName",
2792 new RuntimeException("here"));
2793 }
2794 return;
2795 }
2796
2797 boolean didRemove = false;
2798 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002799 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002800 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2801 Batch b = mAlarmBatches.get(i);
2802 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002803 if (b.size() == 0) {
2804 mAlarmBatches.remove(i);
2805 }
2806 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002807 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2808 if (oldHasTick != newHasTick) {
2809 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2810 }
2811
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002812 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002813 final Alarm a = mPendingWhileIdleAlarms.get(i);
2814 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002815 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2816 mPendingWhileIdleAlarms.remove(i);
2817 }
2818 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002819 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2820 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2821 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2822 if (alarmsForUid.get(j).matches(packageName)) {
2823 alarmsForUid.remove(j);
2824 }
2825 }
2826 if (alarmsForUid.size() == 0) {
2827 mPendingBackgroundAlarms.removeAt(i);
2828 }
2829 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002830 if (didRemove) {
2831 if (DEBUG_BATCH) {
2832 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2833 }
2834 rebatchAllAlarmsLocked(true);
2835 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002836 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002837 }
2838 }
2839
Christopher Tate1d99c392017-12-07 16:54:04 -08002840 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002841 if (uid == Process.SYSTEM_UID) {
2842 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2843 return;
2844 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002845 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002846 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2847 try {
2848 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2849 uid, a.packageName)) {
2850 return true;
2851 }
2852 } catch (RemoteException e) { /* fall through */}
2853 return false;
2854 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002855 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2856 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002857 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002858 if (b.size() == 0) {
2859 mAlarmBatches.remove(i);
2860 }
2861 }
2862 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2863 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002864 if (a.uid == uid) {
2865 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2866 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002867 }
2868 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002869 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2870 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2871 mPendingBackgroundAlarms.removeAt(i);
2872 }
2873 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002874 if (didRemove) {
2875 if (DEBUG_BATCH) {
2876 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2877 }
2878 rebatchAllAlarmsLocked(true);
2879 rescheduleKernelAlarmsLocked();
2880 updateNextAlarmClockLocked();
2881 }
2882 }
2883
Adam Lesinski182f73f2013-12-05 16:48:06 -08002884 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002885 if (userHandle == UserHandle.USER_SYSTEM) {
2886 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2887 return;
2888 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002889 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002890 final Predicate<Alarm> whichAlarms =
2891 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002892 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2893 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002894 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002895 if (b.size() == 0) {
2896 mAlarmBatches.remove(i);
2897 }
2898 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002899 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002900 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002901 == userHandle) {
2902 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2903 mPendingWhileIdleAlarms.remove(i);
2904 }
2905 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002906 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2907 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2908 mPendingBackgroundAlarms.removeAt(i);
2909 }
2910 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002911 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2912 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2913 mLastAllowWhileIdleDispatch.removeAt(i);
2914 }
2915 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002916
2917 if (didRemove) {
2918 if (DEBUG_BATCH) {
2919 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2920 }
2921 rebatchAllAlarmsLocked(true);
2922 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002923 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002924 }
2925 }
2926
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002927 void interactiveStateChangedLocked(boolean interactive) {
2928 if (mInteractive != interactive) {
2929 mInteractive = interactive;
2930 final long nowELAPSED = SystemClock.elapsedRealtime();
2931 if (interactive) {
2932 if (mPendingNonWakeupAlarms.size() > 0) {
2933 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2934 mTotalDelayTime += thisDelayTime;
2935 if (mMaxDelayTime < thisDelayTime) {
2936 mMaxDelayTime = thisDelayTime;
2937 }
2938 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2939 mPendingNonWakeupAlarms.clear();
2940 }
2941 if (mNonInteractiveStartTime > 0) {
2942 long dur = nowELAPSED - mNonInteractiveStartTime;
2943 if (dur > mNonInteractiveTime) {
2944 mNonInteractiveTime = dur;
2945 }
2946 }
2947 } else {
2948 mNonInteractiveStartTime = nowELAPSED;
2949 }
2950 }
2951 }
2952
Adam Lesinski182f73f2013-12-05 16:48:06 -08002953 boolean lookForPackageLocked(String packageName) {
2954 for (int i = 0; i < mAlarmBatches.size(); i++) {
2955 Batch b = mAlarmBatches.get(i);
2956 if (b.hasPackage(packageName)) {
2957 return true;
2958 }
2959 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002960 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002961 final Alarm a = mPendingWhileIdleAlarms.get(i);
2962 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002963 return true;
2964 }
2965 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002966 return false;
2967 }
2968
2969 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002970 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002971 // The kernel never triggers alarms with negative wakeup times
2972 // so we ensure they are positive.
2973 long alarmSeconds, alarmNanoseconds;
2974 if (when < 0) {
2975 alarmSeconds = 0;
2976 alarmNanoseconds = 0;
2977 } else {
2978 alarmSeconds = when / 1000;
2979 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2980 }
Kweku Adams61e03292017-10-19 14:27:12 -07002981
Christopher Tate8b98ade2018-02-09 11:13:19 -08002982 final int result = set(mNativeData, type, alarmSeconds, alarmNanoseconds);
2983 if (result != 0) {
2984 final long nowElapsed = SystemClock.elapsedRealtime();
2985 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
2986 + " type=" + type + " when=" + when
2987 + " @ (" + alarmSeconds + "," + alarmNanoseconds
2988 + "), ret = " + result + " = " + Os.strerror(result));
2989 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002990 } else {
2991 Message msg = Message.obtain();
2992 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002993
Adam Lesinski182f73f2013-12-05 16:48:06 -08002994 mHandler.removeMessages(ALARM_EVENT);
2995 mHandler.sendMessageAtTime(msg, when);
2996 }
2997 }
2998
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002999 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003000 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003001 for (int i=list.size()-1; i>=0; i--) {
3002 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003003 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3004 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003005 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003006 }
3007 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003008
3009 private static final String labelForType(int type) {
3010 switch (type) {
3011 case RTC: return "RTC";
3012 case RTC_WAKEUP : return "RTC_WAKEUP";
3013 case ELAPSED_REALTIME : return "ELAPSED";
3014 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003015 }
3016 return "--unknown--";
3017 }
3018
3019 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003020 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003021 for (int i=list.size()-1; i>=0; i--) {
3022 Alarm a = list.get(i);
3023 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003024 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3025 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003026 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003027 }
3028 }
3029
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003030 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003031 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003032 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003033 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003034 return false;
3035 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003036 if (alarm.operation != null) {
3037 if (alarm.operation.isActivity()) {
3038 // Don't defer starting actual UI
3039 return false;
3040 }
3041 if (alarm.operation.isForegroundService()) {
3042 // FG service alarms are nearly as important; consult AST policy
3043 exemptOnBatterySaver = true;
3044 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003045 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003046 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003047 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003048 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003049 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3050 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003051 }
3052
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003053 private native long init();
3054 private native void close(long nativeData);
Christopher Tate8b98ade2018-02-09 11:13:19 -08003055 private native int set(long nativeData, int type, long seconds, long nanoseconds);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003056 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08003057 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003058 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003059
Makoto Onukiadb50d82018-01-29 16:20:30 -08003060 private long getWhileIdleMinIntervalLocked(int uid) {
3061 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003062 final boolean ebs = (mAppStateTracker != null)
3063 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003064 if (!dozing && !ebs) {
3065 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3066 }
3067 if (dozing) {
3068 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3069 }
3070 if (mUseAllowWhileIdleShortTime.get(uid)) {
3071 // if the last allow-while-idle went off while uid was fg, or the uid
3072 // recently came into fg, don't block the alarm for long.
3073 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3074 }
3075 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3076 }
3077
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003078 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003079 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003080 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003081 // batches are temporally sorted, so we need only pull from the
3082 // start of the list until we either empty it or hit a batch
3083 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003084 while (mAlarmBatches.size() > 0) {
3085 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003086 if (batch.start > nowELAPSED) {
3087 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003088 break;
3089 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003090
Christopher Tatee0a22b32013-07-11 14:43:13 -07003091 // We will (re)schedule some alarms now; don't let that interfere
3092 // with delivery of this current batch
3093 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003094
Christopher Tatee0a22b32013-07-11 14:43:13 -07003095 final int N = batch.size();
3096 for (int i = 0; i < N; i++) {
3097 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003098
3099 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3100 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003101 // schedule such alarms. The first such alarm from an app is always delivered.
3102 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003103 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003104 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003105 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3106 // alarm went off for this app. Reschedule the alarm to be in the
3107 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003108 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003109 if (alarm.maxWhenElapsed < minTime) {
3110 alarm.maxWhenElapsed = minTime;
3111 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003112 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003113 if (RECORD_DEVICE_IDLE_ALARMS) {
3114 IdleDispatchEntry ent = new IdleDispatchEntry();
3115 ent.uid = alarm.uid;
3116 ent.pkg = alarm.operation.getCreatorPackage();
3117 ent.tag = alarm.operation.getTag("");
3118 ent.op = "RESCHEDULE";
3119 ent.elapsedRealtime = nowELAPSED;
3120 ent.argRealtime = lastTime;
3121 mAllowWhileIdleDispatches.add(ent);
3122 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003123 setImplLocked(alarm, true, false);
3124 continue;
3125 }
3126 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003127 if (isBackgroundRestricted(alarm)) {
3128 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3129 if (DEBUG_BG_LIMIT) {
3130 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3131 }
3132 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3133 if (alarmsForUid == null) {
3134 alarmsForUid = new ArrayList<>();
3135 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3136 }
3137 alarmsForUid.add(alarm);
3138 continue;
3139 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003140
Christopher Tatee0a22b32013-07-11 14:43:13 -07003141 alarm.count = 1;
3142 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003143 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3144 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003145 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003146 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003147 if (mPendingIdleUntil == alarm) {
3148 mPendingIdleUntil = null;
3149 rebatchAllAlarmsLocked(false);
3150 restorePendingWhileIdleAlarmsLocked();
3151 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003152 if (mNextWakeFromIdle == alarm) {
3153 mNextWakeFromIdle = null;
3154 rebatchAllAlarmsLocked(false);
3155 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003156
3157 // Recurring alarms may have passed several alarm intervals while the
3158 // phone was asleep or off, so pass a trigger count when sending them.
3159 if (alarm.repeatInterval > 0) {
3160 // this adjustment will be zero if we're late by
3161 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003162 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003163
3164 // Also schedule its next recurrence
3165 final long delta = alarm.count * alarm.repeatInterval;
3166 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003167 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003168 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003169 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3170 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003171 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003172
Christopher Tate864d42e2014-12-02 11:48:53 -08003173 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003174 hasWakeup = true;
3175 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003176
3177 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3178 if (alarm.alarmClock != null) {
3179 mNextAlarmClockMayChange = true;
3180 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003183
Christopher Tate1590f1e2014-10-02 17:27:57 -07003184 // This is a new alarm delivery set; bump the sequence number to indicate that
3185 // all apps' alarm delivery classes should be recalculated.
3186 mCurrentSeq++;
3187 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003188 Collections.sort(triggerList, mAlarmDispatchComparator);
3189
3190 if (localLOGV) {
3191 for (int i=0; i<triggerList.size(); i++) {
3192 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3193 }
3194 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003195
3196 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003197 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003198
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003199 /**
3200 * This Comparator sorts Alarms into increasing time order.
3201 */
3202 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3203 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003204 long when1 = a1.whenElapsed;
3205 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003206 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003207 return 1;
3208 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003209 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003210 return -1;
3211 }
3212 return 0;
3213 }
3214 }
Kweku Adams61e03292017-10-19 14:27:12 -07003215
Makoto Onuki2206af32017-11-21 16:25:35 -08003216 @VisibleForTesting
3217 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003218 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003219 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003220 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003221 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003222 public final IAlarmListener listener;
3223 public final String listenerTag;
3224 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003225 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003226 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003227 public final AlarmManager.AlarmClockInfo alarmClock;
3228 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003229 public final int creatorUid;
3230 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003231 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003232 public int count;
3233 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003234 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003235 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003236 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003237 // Expected alarm expiry time before app standby deferring is applied.
3238 public long expectedWhenElapsed;
3239 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003240 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003241 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003242
Christopher Tate3e04b472013-10-21 17:51:31 -07003243 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003244 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3245 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3246 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003247 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003248 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003249 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3250 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003251 when = _when;
3252 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003253 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003254 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003255 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003256 repeatInterval = _interval;
3257 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003258 listener = _rec;
3259 listenerTag = _listenerTag;
3260 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003261 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003262 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003263 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003264 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003265 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003266 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003267 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003268 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003269
Christopher Tate14a7bb02015-10-01 10:24:31 -07003270 public static String makeTag(PendingIntent pi, String tag, int type) {
3271 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3272 ? "*walarm*:" : "*alarm*:";
3273 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3274 }
3275
3276 public WakeupEvent makeWakeupEvent(long nowRTC) {
3277 return new WakeupEvent(nowRTC, creatorUid,
3278 (operation != null)
3279 ? operation.getIntent().getAction()
3280 : ("<listener>:" + listenerTag));
3281 }
3282
3283 // Returns true if either matches
3284 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3285 return (operation != null)
3286 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003287 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003288 }
3289
3290 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003291 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003292 }
3293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003294 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003295 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003296 StringBuilder sb = new StringBuilder(128);
3297 sb.append("Alarm{");
3298 sb.append(Integer.toHexString(System.identityHashCode(this)));
3299 sb.append(" type ");
3300 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003301 sb.append(" when ");
3302 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003303 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003304 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003305 sb.append('}');
3306 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003307 }
3308
Kweku Adams61e03292017-10-19 14:27:12 -07003309 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003310 SimpleDateFormat sdf) {
3311 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003312 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003313 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003314 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3315 expectedWhenElapsed, nowELAPSED, pw);
3316 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3317 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003318 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3319 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003320 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3321 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003322 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003323 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003324 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003325 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003326 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003327 }
3328 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003329 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003330 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003331 pw.print(" count="); pw.print(count);
3332 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003333 if (alarmClock != null) {
3334 pw.print(prefix); pw.println("Alarm clock:");
3335 pw.print(prefix); pw.print(" triggerTime=");
3336 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3337 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3338 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003339 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003340 if (listener != null) {
3341 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3342 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 }
Kweku Adams61e03292017-10-19 14:27:12 -07003344
3345 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3346 long nowRTC) {
3347 final long token = proto.start(fieldId);
3348
3349 proto.write(AlarmProto.TAG, statsTag);
3350 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003351 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003352 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3353 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3354 proto.write(AlarmProto.COUNT, count);
3355 proto.write(AlarmProto.FLAGS, flags);
3356 if (alarmClock != null) {
3357 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3358 }
3359 if (operation != null) {
3360 operation.writeToProto(proto, AlarmProto.OPERATION);
3361 }
3362 if (listener != null) {
3363 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3364 }
3365
3366 proto.end(token);
3367 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003369
Christopher Tatee0a22b32013-07-11 14:43:13 -07003370 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3371 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003372 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3373 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003374 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003375 break;
3376 }
3377
Christopher Tatee0a22b32013-07-11 14:43:13 -07003378 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003379 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3380 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003381 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003382 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003383 }
3384 }
3385
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003386 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3387 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3388 if (timeSinceOn < 5*60*1000) {
3389 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3390 return 2*60*1000;
3391 } else if (timeSinceOn < 30*60*1000) {
3392 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3393 return 15*60*1000;
3394 } else {
3395 // Otherwise, we will delay by at most an hour.
3396 return 60*60*1000;
3397 }
3398 }
3399
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003400 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003401 if (duration < 15*60*1000) {
3402 // If the duration until the time is less than 15 minutes, the maximum fuzz
3403 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003404 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003405 } else if (duration < 90*60*1000) {
3406 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3407 return 15*60*1000;
3408 } else {
3409 // Otherwise, we will fuzz by at most half an hour.
3410 return 30*60*1000;
3411 }
3412 }
3413
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003414 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3415 if (mInteractive) {
3416 return false;
3417 }
3418 if (mLastAlarmDeliveryTime <= 0) {
3419 return false;
3420 }
minho.choo649acab2014-12-12 16:13:55 +09003421 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003422 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3423 // and the next delivery time is in the past, then just deliver them all. This
3424 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3425 return false;
3426 }
3427 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3428 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3429 }
3430
3431 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3432 mLastAlarmDeliveryTime = nowELAPSED;
3433 for (int i=0; i<triggerList.size(); i++) {
3434 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003435 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003436 if (alarm.wakeup) {
3437 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3438 } else {
3439 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3440 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003441 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003442 if (localLOGV) {
3443 Slog.v(TAG, "sending alarm " + alarm);
3444 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003445 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003446 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3447 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003448 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003449 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003450 } catch (RuntimeException e) {
3451 Slog.w(TAG, "Failure sending alarm.", e);
3452 }
Tim Murray175c0f92017-11-28 15:01:04 -08003453 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003454 }
3455 }
3456
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003457 private boolean isExemptFromAppStandby(Alarm a) {
3458 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3459 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3460 }
3461
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003462 private class AlarmThread extends Thread
3463 {
3464 public AlarmThread()
3465 {
3466 super("AlarmManager");
3467 }
Kweku Adams61e03292017-10-19 14:27:12 -07003468
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003469 public void run()
3470 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003471 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3472
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003473 while (true)
3474 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003475 int result = waitForAlarm(mNativeData);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003476
Dianne Hackbornc3527222015-05-13 14:03:20 -07003477 final long nowRTC = System.currentTimeMillis();
3478 final long nowELAPSED = SystemClock.elapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003479 synchronized (mLock) {
3480 mLastWakeup = nowELAPSED;
3481 }
3482
3483 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003484
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003485 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003486 // The kernel can give us spurious time change notifications due to
3487 // small adjustments it makes internally; we want to filter those out.
3488 final long lastTimeChangeClockTime;
3489 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003490 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003491 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3492 expectedClockTime = lastTimeChangeClockTime
3493 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003494 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003495 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3496 || nowRTC > (expectedClockTime+1000)) {
3497 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003498 // let's do it!
3499 if (DEBUG_BATCH) {
3500 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3501 }
3502 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003503 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003504 rebatchAllAlarms();
3505 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003506 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003507 synchronized (mLock) {
3508 mNumTimeChanged++;
3509 mLastTimeChangeClockTime = nowRTC;
3510 mLastTimeChangeRealtime = nowELAPSED;
3511 }
3512 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3513 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003514 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003515 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3516 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003517 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3518
3519 // The world has changed on us, so we need to re-evaluate alarms
3520 // regardless of whether the kernel has told us one went off.
3521 result |= IS_WAKEUP_MASK;
3522 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003524
Dianne Hackbornc3527222015-05-13 14:03:20 -07003525 if (result != TIME_CHANGED_MASK) {
3526 // If this was anything besides just a time change, then figure what if
3527 // anything to do about alarms.
3528 synchronized (mLock) {
3529 if (localLOGV) Slog.v(
3530 TAG, "Checking for alarms... rtc=" + nowRTC
3531 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003532
Dianne Hackbornc3527222015-05-13 14:03:20 -07003533 if (WAKEUP_STATS) {
3534 if ((result & IS_WAKEUP_MASK) != 0) {
3535 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3536 int n = 0;
3537 for (WakeupEvent event : mRecentWakeups) {
3538 if (event.when > newEarliest) break;
3539 n++; // number of now-stale entries at the list head
3540 }
3541 for (int i = 0; i < n; i++) {
3542 mRecentWakeups.remove();
3543 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003544
Dianne Hackbornc3527222015-05-13 14:03:20 -07003545 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003546 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003547 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003548
Christopher Tate8b98ade2018-02-09 11:13:19 -08003549 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003550 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3551 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3552 // if there are no wakeup alarms and the screen is off, we can
3553 // delay what we have so far until the future.
3554 if (mPendingNonWakeupAlarms.size() == 0) {
3555 mStartCurrentDelayTime = nowELAPSED;
3556 mNextNonWakeupDeliveryTime = nowELAPSED
3557 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3558 }
3559 mPendingNonWakeupAlarms.addAll(triggerList);
3560 mNumDelayedAlarms += triggerList.size();
3561 rescheduleKernelAlarmsLocked();
3562 updateNextAlarmClockLocked();
3563 } else {
3564 // now deliver the alarm intents; if there are pending non-wakeup
3565 // alarms, we need to merge them in to the list. note we don't
3566 // just deliver them first because we generally want non-wakeup
3567 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003568 if (mPendingNonWakeupAlarms.size() > 0) {
3569 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3570 triggerList.addAll(mPendingNonWakeupAlarms);
3571 Collections.sort(triggerList, mAlarmDispatchComparator);
3572 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3573 mTotalDelayTime += thisDelayTime;
3574 if (mMaxDelayTime < thisDelayTime) {
3575 mMaxDelayTime = thisDelayTime;
3576 }
3577 mPendingNonWakeupAlarms.clear();
3578 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003579 final ArraySet<Pair<String, Integer>> triggerPackages =
3580 new ArraySet<>();
3581 for (int i = 0; i < triggerList.size(); i++) {
3582 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003583 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003584 triggerPackages.add(Pair.create(
3585 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003586 }
3587 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003588 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003589 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3590 rescheduleKernelAlarmsLocked();
3591 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003592 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003593 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003594
3595 } else {
3596 // Just in case -- even though no wakeup flag was set, make sure
3597 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003598 synchronized (mLock) {
3599 rescheduleKernelAlarmsLocked();
3600 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003601 }
3602 }
3603 }
3604 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003605
David Christieebe51fc2013-07-26 13:23:29 -07003606 /**
3607 * Attribute blame for a WakeLock.
3608 * @param pi PendingIntent to attribute blame to if ws is null.
3609 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003610 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003611 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003612 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003613 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003614 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003615 final boolean unimportant = pi == mTimeTickSender;
3616 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003617 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003618 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003619 } else {
3620 mWakeLock.setHistoryTag(null);
3621 }
3622 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003623 if (ws != null) {
3624 mWakeLock.setWorkSource(ws);
3625 return;
3626 }
3627
Christopher Tate14a7bb02015-10-01 10:24:31 -07003628 final int uid = (knownUid >= 0)
3629 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003630 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003631 if (uid >= 0) {
3632 mWakeLock.setWorkSource(new WorkSource(uid));
3633 return;
3634 }
3635 } catch (Exception e) {
3636 }
3637
3638 // Something went wrong; fall back to attributing the lock to the OS
3639 mWakeLock.setWorkSource(null);
3640 }
3641
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 private class AlarmHandler extends Handler {
3643 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003644 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3645 public static final int LISTENER_TIMEOUT = 3;
3646 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003647 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3648 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003649 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 public AlarmHandler() {
3652 }
Kweku Adams61e03292017-10-19 14:27:12 -07003653
Makoto Onuki4d298b52018-02-05 10:54:58 -08003654 public void postRemoveForStopped(int uid) {
3655 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3656 }
3657
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003658 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003659 switch (msg.what) {
3660 case ALARM_EVENT: {
3661 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3662 synchronized (mLock) {
3663 final long nowRTC = System.currentTimeMillis();
3664 final long nowELAPSED = SystemClock.elapsedRealtime();
3665 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3666 updateNextAlarmClockLocked();
3667 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003668
Christopher Tate14a7bb02015-10-01 10:24:31 -07003669 // now trigger the alarms without the lock held
3670 for (int i=0; i<triggerList.size(); i++) {
3671 Alarm alarm = triggerList.get(i);
3672 try {
3673 alarm.operation.send();
3674 } catch (PendingIntent.CanceledException e) {
3675 if (alarm.repeatInterval > 0) {
3676 // This IntentSender is no longer valid, but this
3677 // is a repeating alarm, so toss the hoser.
3678 removeImpl(alarm.operation);
3679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 }
3681 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003682 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003683 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003684
3685 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3686 sendNextAlarmClockChanged();
3687 break;
3688
3689 case LISTENER_TIMEOUT:
3690 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3691 break;
3692
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003693 case REPORT_ALARMS_ACTIVE:
3694 if (mLocalDeviceIdleController != null) {
3695 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3696 }
3697 break;
3698
Suprabh Shukla75edab12018-01-29 14:09:06 -08003699 case APP_STANDBY_PAROLE_CHANGED:
3700 synchronized (mLock) {
3701 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003702 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3703 rescheduleKernelAlarmsLocked();
3704 updateNextAlarmClockLocked();
3705 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003706 }
3707 break;
3708
3709 case APP_STANDBY_BUCKET_CHANGED:
3710 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003711 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3712 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3713 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3714 rescheduleKernelAlarmsLocked();
3715 updateNextAlarmClockLocked();
3716 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003717 }
3718 break;
3719
Makoto Onuki4d298b52018-02-05 10:54:58 -08003720 case REMOVE_FOR_STOPPED:
3721 synchronized (mLock) {
3722 removeForStoppedLocked(msg.arg1);
3723 }
3724 break;
3725
Christopher Tate14a7bb02015-10-01 10:24:31 -07003726 default:
3727 // nope, just ignore it
3728 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003729 }
3730 }
3731 }
Kweku Adams61e03292017-10-19 14:27:12 -07003732
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003733 class ClockReceiver extends BroadcastReceiver {
3734 public ClockReceiver() {
3735 IntentFilter filter = new IntentFilter();
3736 filter.addAction(Intent.ACTION_TIME_TICK);
3737 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003738 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003739 }
Kweku Adams61e03292017-10-19 14:27:12 -07003740
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003741 @Override
3742 public void onReceive(Context context, Intent intent) {
3743 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003744 if (DEBUG_BATCH) {
3745 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3746 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003747 synchronized (mLock) {
3748 mLastTickReceived = System.currentTimeMillis();
3749 }
Christopher Tate385e4982013-07-23 18:22:29 -07003750 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003751 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3752 // Since the kernel does not keep track of DST, we need to
3753 // reset the TZ information at the beginning of each day
3754 // based off of the current Zone gmt offset + userspace tracked
3755 // daylight savings information.
3756 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003757 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003758 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003759 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003760 }
3761 }
Kweku Adams61e03292017-10-19 14:27:12 -07003762
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003764 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003765 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003766
3767 // Schedule this event for the amount of time that it would take to get to
3768 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003769 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003770
David Christieebe51fc2013-07-26 13:23:29 -07003771 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003772 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003773 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3774 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003775
3776 // Finally, remember when we set the tick alarm
3777 synchronized (mLock) {
3778 mLastTickSet = currentTime;
3779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003780 }
Christopher Tate385e4982013-07-23 18:22:29 -07003781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003782 public void scheduleDateChangedEvent() {
3783 Calendar calendar = Calendar.getInstance();
3784 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003785 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003786 calendar.set(Calendar.MINUTE, 0);
3787 calendar.set(Calendar.SECOND, 0);
3788 calendar.set(Calendar.MILLISECOND, 0);
3789 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003790
3791 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003792 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3793 AlarmManager.FLAG_STANDALONE, workSource, null,
3794 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003795 }
3796 }
Kweku Adams61e03292017-10-19 14:27:12 -07003797
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003798 class InteractiveStateReceiver extends BroadcastReceiver {
3799 public InteractiveStateReceiver() {
3800 IntentFilter filter = new IntentFilter();
3801 filter.addAction(Intent.ACTION_SCREEN_OFF);
3802 filter.addAction(Intent.ACTION_SCREEN_ON);
3803 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3804 getContext().registerReceiver(this, filter);
3805 }
3806
3807 @Override
3808 public void onReceive(Context context, Intent intent) {
3809 synchronized (mLock) {
3810 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3811 }
3812 }
3813 }
3814
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003815 class UninstallReceiver extends BroadcastReceiver {
3816 public UninstallReceiver() {
3817 IntentFilter filter = new IntentFilter();
3818 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3819 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003820 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003821 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003822 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003823 // Register for events related to sdcard installation.
3824 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003825 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003826 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003827 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003828 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003829 }
Kweku Adams61e03292017-10-19 14:27:12 -07003830
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003831 @Override
3832 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003833 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003835 String action = intent.getAction();
3836 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003837 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3838 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3839 for (String packageName : pkgList) {
3840 if (lookForPackageLocked(packageName)) {
3841 setResultCode(Activity.RESULT_OK);
3842 return;
3843 }
3844 }
3845 return;
3846 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003847 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003848 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3849 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3850 if (userHandle >= 0) {
3851 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08003852 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3853 final Pair<String, Integer> packageUser =
3854 mLastAlarmDeliveredForPackage.keyAt(i);
3855 if (packageUser.second == userHandle) {
3856 mLastAlarmDeliveredForPackage.removeAt(i);
3857 }
3858 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003859 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003860 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003861 if (uid >= 0) {
3862 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003863 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003864 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003865 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003866 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3867 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3868 // This package is being updated; don't kill its alarms.
3869 return;
3870 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003871 Uri data = intent.getData();
3872 if (data != null) {
3873 String pkg = data.getSchemeSpecificPart();
3874 if (pkg != null) {
3875 pkgList = new String[]{pkg};
3876 }
3877 }
3878 }
3879 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003880 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
3881 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
3882 if (ArrayUtils.contains(pkgList, packageUser.first)
3883 && packageUser.second == UserHandle.getUserId(uid)) {
3884 mLastAlarmDeliveredForPackage.removeAt(i);
3885 }
3886 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003887 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003888 if (uid >= 0) {
3889 // package-removed case
3890 removeLocked(uid);
3891 } else {
3892 // external-applications-unavailable etc case
3893 removeLocked(pkg);
3894 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003895 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003896 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3897 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3898 if (uidStats.remove(pkg) != null) {
3899 if (uidStats.size() <= 0) {
3900 mBroadcastStats.removeAt(i);
3901 }
3902 }
3903 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003904 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003905 }
3906 }
3907 }
3908 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003909
3910 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003911 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003912 }
3913
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003914 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003915 if (disabled) {
3916 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003917 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003918 }
3919
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003920 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003921 }
3922
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003923 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08003924 if (disabled) {
3925 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003926 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003927 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003928
3929 @Override public void onUidCachedChanged(int uid, boolean cached) {
3930 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003931 };
3932
Suprabh Shukla75edab12018-01-29 14:09:06 -08003933 /**
3934 * Tracking of app assignments to standby buckets
3935 */
3936 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
3937 @Override
3938 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08003939 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003940 if (DEBUG_STANDBY) {
3941 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
3942 bucket);
3943 }
3944 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003945 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
3946 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08003947 }
3948
3949 @Override
3950 public void onParoleStateChanged(boolean isParoleOn) {
3951 if (DEBUG_STANDBY) {
3952 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
3953 }
3954 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
3955 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
3956 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
3957 Boolean.valueOf(isParoleOn)).sendToTarget();
3958 }
3959 };
3960
Makoto Onuki2206af32017-11-21 16:25:35 -08003961 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003962 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003963 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003964 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003965 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003966 }
3967 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003968
3969 @Override
3970 public void unblockAlarmsForUid(int uid) {
3971 synchronized (mLock) {
3972 sendPendingBackgroundAlarmsLocked(uid, null);
3973 }
3974 }
3975
3976 @Override
3977 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3978 synchronized (mLock) {
3979 sendPendingBackgroundAlarmsLocked(uid, packageName);
3980 }
3981 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08003982
3983 @Override
3984 public void onUidForeground(int uid, boolean foreground) {
3985 synchronized (mLock) {
3986 if (foreground) {
3987 mUseAllowWhileIdleShortTime.put(uid, true);
3988
3989 // Note we don't have to drain the pending while-idle alarms here, because
3990 // this event should coincide with unblockAlarmsForUid().
3991 }
3992 }
3993 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003994 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003995
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003996 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003997 String pkg = pi.getCreatorPackage();
3998 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003999 return getStatsLocked(uid, pkg);
4000 }
4001
4002 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004003 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4004 if (uidStats == null) {
4005 uidStats = new ArrayMap<String, BroadcastStats>();
4006 mBroadcastStats.put(uid, uidStats);
4007 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004008 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004009 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004010 bs = new BroadcastStats(uid, pkgName);
4011 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004012 }
4013 return bs;
4014 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004015
Christopher Tate21e9f192017-08-08 13:49:11 -07004016 /**
4017 * Canonical count of (operation.send() - onSendFinished()) and
4018 * listener send/complete/timeout invocations.
4019 * Guarded by the usual lock.
4020 */
4021 @GuardedBy("mLock")
4022 private int mSendCount = 0;
4023 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004024 private int mSendFinishCount = 0;
4025 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004026 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004027 @GuardedBy("mLock")
4028 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004029
Christopher Tate14a7bb02015-10-01 10:24:31 -07004030 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004031
Christopher Tate14a7bb02015-10-01 10:24:31 -07004032 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4033 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004034 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004035 return mInFlight.remove(i);
4036 }
4037 }
4038 mLog.w("No in-flight alarm for " + pi + " " + intent);
4039 return null;
4040 }
4041
4042 private InFlight removeLocked(IBinder listener) {
4043 for (int i = 0; i < mInFlight.size(); i++) {
4044 if (mInFlight.get(i).mListener == listener) {
4045 return mInFlight.remove(i);
4046 }
4047 }
4048 mLog.w("No in-flight alarm for listener " + listener);
4049 return null;
4050 }
4051
4052 private void updateStatsLocked(InFlight inflight) {
4053 final long nowELAPSED = SystemClock.elapsedRealtime();
4054 BroadcastStats bs = inflight.mBroadcastStats;
4055 bs.nesting--;
4056 if (bs.nesting <= 0) {
4057 bs.nesting = 0;
4058 bs.aggregateTime += nowELAPSED - bs.startTime;
4059 }
4060 FilterStats fs = inflight.mFilterStats;
4061 fs.nesting--;
4062 if (fs.nesting <= 0) {
4063 fs.nesting = 0;
4064 fs.aggregateTime += nowELAPSED - fs.startTime;
4065 }
4066 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004067 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4068 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004069 }
4070 }
4071
4072 private void updateTrackingLocked(InFlight inflight) {
4073 if (inflight != null) {
4074 updateStatsLocked(inflight);
4075 }
4076 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004077 if (DEBUG_WAKELOCK) {
4078 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4079 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004080 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004081 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004082 mWakeLock.release();
4083 if (mInFlight.size() > 0) {
4084 mLog.w("Finished all dispatches with " + mInFlight.size()
4085 + " remaining inflights");
4086 for (int i=0; i<mInFlight.size(); i++) {
4087 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4088 }
4089 mInFlight.clear();
4090 }
4091 } else {
4092 // the next of our alarms is now in flight. reattribute the wakelock.
4093 if (mInFlight.size() > 0) {
4094 InFlight inFlight = mInFlight.get(0);
4095 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
4096 inFlight.mAlarmType, inFlight.mTag, -1, false);
4097 } else {
4098 // should never happen
4099 mLog.w("Alarm wakelock still held but sent queue empty");
4100 mWakeLock.setWorkSource(null);
4101 }
4102 }
4103 }
4104
4105 /**
4106 * Callback that arrives when a direct-call alarm reports that delivery has finished
4107 */
4108 @Override
4109 public void alarmComplete(IBinder who) {
4110 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004111 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004112 + " pid=" + Binder.getCallingPid());
4113 return;
4114 }
4115
4116 final long ident = Binder.clearCallingIdentity();
4117 try {
4118 synchronized (mLock) {
4119 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4120 InFlight inflight = removeLocked(who);
4121 if (inflight != null) {
4122 if (DEBUG_LISTENER_CALLBACK) {
4123 Slog.i(TAG, "alarmComplete() from " + who);
4124 }
4125 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004126 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004127 } else {
4128 // Delivery timed out, and the timeout handling already took care of
4129 // updating our tracking here, so we needn't do anything further.
4130 if (DEBUG_LISTENER_CALLBACK) {
4131 Slog.i(TAG, "Late alarmComplete() from " + who);
4132 }
4133 }
4134 }
4135 } finally {
4136 Binder.restoreCallingIdentity(ident);
4137 }
4138 }
4139
4140 /**
4141 * Callback that arrives when a PendingIntent alarm has finished delivery
4142 */
4143 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004144 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4145 String resultData, Bundle resultExtras) {
4146 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004147 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004148 updateTrackingLocked(removeLocked(pi, intent));
4149 }
4150 }
4151
4152 /**
4153 * Timeout of a direct-call alarm delivery
4154 */
4155 public void alarmTimedOut(IBinder who) {
4156 synchronized (mLock) {
4157 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004158 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004159 // TODO: implement ANR policy for the target
4160 if (DEBUG_LISTENER_CALLBACK) {
4161 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004162 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004163 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004164 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004165 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004166 if (DEBUG_LISTENER_CALLBACK) {
4167 Slog.i(TAG, "Spurious timeout of listener " + who);
4168 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004169 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004170 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004171 }
4172 }
4173
4174 /**
4175 * Deliver an alarm and set up the post-delivery handling appropriately
4176 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004177 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004178 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
4179 if (alarm.operation != null) {
4180 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004181 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004182
4183 if (alarm.priorityClass.priority == PRIO_TICK) {
4184 mLastTickIssued = nowELAPSED;
4185 }
4186
Christopher Tate14a7bb02015-10-01 10:24:31 -07004187 try {
4188 alarm.operation.send(getContext(), 0,
4189 mBackgroundIntent.putExtra(
4190 Intent.EXTRA_ALARM_COUNT, alarm.count),
4191 mDeliveryTracker, mHandler, null,
4192 allowWhileIdle ? mIdleOptions : null);
4193 } catch (PendingIntent.CanceledException e) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08004194 if (alarm.operation == mTimeTickSender) {
4195 Slog.wtf(TAG, "mTimeTickSender canceled");
4196 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004197 if (alarm.repeatInterval > 0) {
4198 // This IntentSender is no longer valid, but this
4199 // is a repeating alarm, so toss it
4200 removeImpl(alarm.operation);
4201 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004202 // No actual delivery was possible, so the delivery tracker's
4203 // 'finished' callback won't be invoked. We also don't need
4204 // to do any wakelock or stats tracking, so we have nothing
4205 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07004206 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004207 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004208 }
4209 } else {
4210 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07004211 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004212 try {
4213 if (DEBUG_LISTENER_CALLBACK) {
4214 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4215 + " listener=" + alarm.listener.asBinder());
4216 }
4217 alarm.listener.doAlarm(this);
4218 mHandler.sendMessageDelayed(
4219 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4220 alarm.listener.asBinder()),
4221 mConstants.LISTENER_TIMEOUT);
4222 } catch (Exception e) {
4223 if (DEBUG_LISTENER_CALLBACK) {
4224 Slog.i(TAG, "Alarm undeliverable to listener "
4225 + alarm.listener.asBinder(), e);
4226 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08004227 // As in the PendingIntent.CanceledException case, delivery of the
4228 // alarm was not possible, so we have no wakelock or timeout or
4229 // stats management to do. It threw before we posted the delayed
4230 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07004231 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08004232 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004233 }
4234 }
4235
4236 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004237 if (DEBUG_WAKELOCK) {
4238 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4239 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004240 if (mBroadcastRefCount == 0) {
4241 setWakelockWorkSource(alarm.operation, alarm.workSource,
4242 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
4243 true);
4244 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004245 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004246 }
4247 final InFlight inflight = new InFlight(AlarmManagerService.this,
4248 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
4249 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
4250 mInFlight.add(inflight);
4251 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004252 if (allowWhileIdle) {
4253 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004254 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004255 if ((mAppStateTracker == null)
4256 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004257 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4258 } else {
4259 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4260 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004261 if (RECORD_DEVICE_IDLE_ALARMS) {
4262 IdleDispatchEntry ent = new IdleDispatchEntry();
4263 ent.uid = alarm.uid;
4264 ent.pkg = alarm.packageName;
4265 ent.tag = alarm.statsTag;
4266 ent.op = "DELIVER";
4267 ent.elapsedRealtime = nowELAPSED;
4268 mAllowWhileIdleDispatches.add(ent);
4269 }
4270 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004271 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004272 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4273 UserHandle.getUserId(alarm.creatorUid));
4274 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4275 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004276
4277 final BroadcastStats bs = inflight.mBroadcastStats;
4278 bs.count++;
4279 if (bs.nesting == 0) {
4280 bs.nesting = 1;
4281 bs.startTime = nowELAPSED;
4282 } else {
4283 bs.nesting++;
4284 }
4285 final FilterStats fs = inflight.mFilterStats;
4286 fs.count++;
4287 if (fs.nesting == 0) {
4288 fs.nesting = 1;
4289 fs.startTime = nowELAPSED;
4290 } else {
4291 fs.nesting++;
4292 }
4293 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4294 || alarm.type == RTC_WAKEUP) {
4295 bs.numWakeup++;
4296 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004297 ActivityManager.noteWakeupAlarm(
4298 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4299 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004300 }
4301 }
4302 }
mswest463f4c99d2018-02-01 10:13:10 -08004303
4304 private class ShellCmd extends ShellCommand {
4305
4306 IAlarmManager getBinderService() {
4307 return IAlarmManager.Stub.asInterface(mService);
4308 }
4309
4310 @Override
4311 public int onCommand(String cmd) {
4312 if (cmd == null) {
4313 return handleDefaultCommands(cmd);
4314 }
4315
4316 final PrintWriter pw = getOutPrintWriter();
4317 try {
4318 switch (cmd) {
4319 case "set-time":
4320 final long millis = Long.parseLong(getNextArgRequired());
4321 return (getBinderService().setTime(millis)) ? 0 : -1;
4322 case "set-timezone":
4323 final String tz = getNextArgRequired();
4324 getBinderService().setTimeZone(tz);
4325 return 0;
4326 default:
4327 return handleDefaultCommands(cmd);
4328 }
4329 } catch (Exception e) {
4330 pw.println(e);
4331 }
4332 return -1;
4333 }
4334
4335 @Override
4336 public void onHelp() {
4337 PrintWriter pw = getOutPrintWriter();
4338 pw.println("Alarm manager service (alarm) commands:");
4339 pw.println(" help");
4340 pw.println(" Print this help text.");
4341 pw.println(" set-time TIME");
4342 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4343 pw.println(" since the Epoch.");
4344 pw.println(" set-timezone TZ");
4345 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4346 }
4347 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004348}