blob: fcd136c651696723adc23eb3827c406763ef2790 [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 Tate3d65d4d2018-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;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -070056import android.os.Looper;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.os.Message;
Jeff Sharkey9911a282018-02-14 22:29:11 -070058import android.os.ParcelableException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070060import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070061import android.os.RemoteException;
mswest463f4c99d2018-02-01 10:13:10 -080062import android.os.ResultReceiver;
63import android.os.ShellCallback;
64import android.os.ShellCommand;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.os.SystemClock;
66import android.os.SystemProperties;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +000067import android.os.ThreadLocalWorkSource;
Tim Murray175c0f92017-11-28 15:01:04 -080068import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070069import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070070import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020071import android.provider.Settings;
Christopher Tate8b98ade2018-02-09 11:13:19 -080072import android.system.Os;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020074import android.text.format.DateFormat;
Christopher Tate22e919d2018-02-16 16:16:50 -080075import android.text.format.DateUtils;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080076import android.util.ArrayMap;
Suprabh Shukla92994ab2018-01-31 17:39:30 -080077import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070078import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020079import android.util.Log;
Jeff Sharkey9911a282018-02-14 22:29:11 -070080import android.util.NtpTrustedTime;
Suprabh Shukla75edab12018-01-29 14:09:06 -080081import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080082import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080083import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020084import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070085import android.util.SparseLongArray;
Bookatz7948c872018-09-04 12:58:33 -070086import android.util.StatsLog;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070087import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070088import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089
Jeff Sharkey9911a282018-02-14 22:29:11 -070090import com.android.internal.annotations.GuardedBy;
91import com.android.internal.annotations.VisibleForTesting;
92import com.android.internal.util.ArrayUtils;
93import com.android.internal.util.DumpUtils;
94import com.android.internal.util.LocalLog;
Makoto Onuki49392d32018-04-11 13:51:02 -070095import com.android.internal.util.StatLogger;
Jeff Sharkey9911a282018-02-14 22:29:11 -070096import com.android.server.AppStateTracker.Listener;
97
Christopher Tate4cb338d2013-07-26 13:11:31 -070098import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import java.io.FileDescriptor;
100import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -0700101import java.text.SimpleDateFormat;
Jeff Sharkey9911a282018-02-14 22:29:11 -0700102import java.time.DateTimeException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -0800104import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import java.util.Calendar;
106import java.util.Collections;
107import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -0500108import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -0700109import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -0700110import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200111import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700112import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800113import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -0400114import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -0800115import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Makoto Onuki2206af32017-11-21 16:25:35 -0800117/**
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700118 * Alarm manager implementation.
Makoto Onuki2206af32017-11-21 16:25:35 -0800119 *
120 * Unit test:
121 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
122 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700124 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
125 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800126 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700127 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800128 static final int TIME_CHANGED_MASK = 1 << 16;
129 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800130
Christopher Tatee0a22b32013-07-11 14:43:13 -0700131 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800133
Adam Lesinski182f73f2013-12-05 16:48:06 -0800134 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800135 static final boolean localLOGV = false;
136 static final boolean DEBUG_BATCH = localLOGV || false;
137 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200138 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700139 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800140 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700141 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800142 static final boolean DEBUG_STANDBY = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700143 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700144 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800145 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200146
Christopher Tatec8b7f432018-09-28 16:23:10 -0700147 static final int TICK_HISTORY_DEPTH = 10;
148
Christopher Tatef2159712018-03-27 16:04:14 -0700149 // Indices into the APP_STANDBY_MIN_DELAYS and KEYS_APP_STANDBY_DELAY arrays
150 static final int ACTIVE_INDEX = 0;
151 static final int WORKING_INDEX = 1;
152 static final int FREQUENT_INDEX = 2;
153 static final int RARE_INDEX = 3;
154 static final int NEVER_INDEX = 4;
155
Christopher Tate14a7bb02015-10-01 10:24:31 -0700156 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800158 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700159
Adam Lesinski182f73f2013-12-05 16:48:06 -0800160 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700161
Christopher Tate24cd46f2016-02-02 14:28:01 -0800162 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
163 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700164 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
165 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200166
Adam Lesinski182f73f2013-12-05 16:48:06 -0800167 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800168
Christopher Tate14a7bb02015-10-01 10:24:31 -0700169 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800170 DeviceIdleController.LocalService mLocalDeviceIdleController;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800171 private UsageStatsManagerInternal mUsageStatsManagerInternal;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700172
Adam Lesinski182f73f2013-12-05 16:48:06 -0800173 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800174
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700175 // List of alarms per uid deferred due to user applied background restrictions on the source app
176 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800177 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700178 private long mNextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -0700179 private long mNextWakeUpSetAt;
180 private long mNextNonWakeUpSetAt;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700181 private long mLastWakeup;
Christopher Tate8b98ade2018-02-09 11:13:19 -0800182 private long mLastTrigger;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700183
Christopher Tate12cf0b62018-01-05 18:40:14 -0800184 private long mLastTickSet;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800185 private long mLastTickReceived;
Makoto Onuki5d93b832018-01-10 16:12:39 -0800186 private long mLastTickAdded;
187 private long mLastTickRemoved;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700188 // ring buffer of recent TIME_TICK issuance, in the elapsed timebase
189 private final long[] mTickHistory = new long[TICK_HISTORY_DEPTH];
190 private int mNextTickHistory;
191
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700192 private final Injector mInjector;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800193 int mBroadcastRefCount = 0;
194 PowerManager.WakeLock mWakeLock;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700195 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
196 ArrayList<InFlight> mInFlight = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700197 AlarmHandler mHandler;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800198 ClockReceiver mClockReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700199 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Christopher Tatec8b7f432018-09-28 16:23:10 -0700200 Intent mTimeTickIntent;
201 IAlarmListener mTimeTickTrigger;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800202 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700203 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700204 boolean mInteractive = true;
205 long mNonInteractiveStartTime;
206 long mNonInteractiveTime;
207 long mLastAlarmDeliveryTime;
208 long mStartCurrentDelayTime;
209 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700210 long mLastTimeChangeClockTime;
211 long mLastTimeChangeRealtime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700212 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800213
Christopher Tatebb9cce52017-04-18 14:19:43 -0700214 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
215
216 /**
217 * This permission must be defined by the canonical System UI package,
218 * with protection level "signature".
219 */
220 private static final String SYSTEM_UI_SELF_PERMISSION =
221 "android.permission.systemui.IDENTITY";
222
223 /**
224 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
225 */
226 int mSystemUiUid;
227
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700228 /**
229 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700230 * used to determine the earliest we can dispatch the next such alarm. Times are in the
231 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700232 */
233 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
234
Suprabh Shuklac25447d2018-01-19 16:43:35 -0800235 /**
236 * For each uid, we store whether the last allow-while-idle alarm was dispatched while
237 * the uid was in foreground or not. We will use the allow_while_idle_short_time in such cases.
238 */
239 final SparseBooleanArray mUseAllowWhileIdleShortTime = new SparseBooleanArray();
240
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700241 final static class IdleDispatchEntry {
242 int uid;
243 String pkg;
244 String tag;
245 String op;
246 long elapsedRealtime;
247 long argRealtime;
248 }
249 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
250
Suprabh Shukla75edab12018-01-29 14:09:06 -0800251 interface Stats {
252 int REBATCH_ALL_ALARMS = 0;
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800253 int REORDER_ALARMS_FOR_STANDBY = 1;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800254 }
255
256 private final StatLogger mStatLogger = new StatLogger(new String[] {
257 "REBATCH_ALL_ALARMS",
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800258 "REORDER_ALARMS_FOR_STANDBY",
Suprabh Shukla75edab12018-01-29 14:09:06 -0800259 });
260
Dianne Hackborna750a632015-06-16 17:18:23 -0700261 /**
262 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
263 */
264 Bundle mIdleOptions;
265
Jose Lima235510e2014-08-13 12:50:01 -0700266 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
267 new SparseArray<>();
268 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
269 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200270 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
271 new SparseBooleanArray();
272 private boolean mNextAlarmClockMayChange;
273
274 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700275 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
276 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200277
Makoto Onukie4918212018-02-06 11:30:15 -0800278 private AppStateTracker mAppStateTracker;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800279 private boolean mAppStandbyParole;
280 private ArrayMap<Pair<String, Integer>, Long> mLastAlarmDeliveredForPackage = new ArrayMap<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800281
Dianne Hackborna750a632015-06-16 17:18:23 -0700282 /**
283 * All times are in milliseconds. These constants are kept synchronized with the system
284 * global Settings. Any access to this class or its fields should be done while
285 * holding the AlarmManagerService.mLock lock.
286 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700287 @VisibleForTesting
288 final class Constants extends ContentObserver {
Dianne Hackborna750a632015-06-16 17:18:23 -0700289 // Key names stored in the settings value.
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700290 @VisibleForTesting
291 static final String KEY_MIN_FUTURITY = "min_futurity";
292 @VisibleForTesting
293 static final String KEY_MIN_INTERVAL = "min_interval";
294 @VisibleForTesting
295 static final String KEY_MAX_INTERVAL = "max_interval";
296 @VisibleForTesting
297 static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
298 @VisibleForTesting
299 static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
300 @VisibleForTesting
301 static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
Dianne Hackborna750a632015-06-16 17:18:23 -0700302 = "allow_while_idle_whitelist_duration";
Suprabh Shuklaadfa6e82018-10-19 17:32:08 -0700303 @VisibleForTesting
304 static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Dianne Hackborna750a632015-06-16 17:18:23 -0700305
Suprabh Shukla75edab12018-01-29 14:09:06 -0800306 // Keys for specifying throttling delay based on app standby bucketing
307 private final String[] KEYS_APP_STANDBY_DELAY = {
308 "standby_active_delay",
309 "standby_working_delay",
310 "standby_frequent_delay",
311 "standby_rare_delay",
312 "standby_never_delay",
313 };
314
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
316 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tate22e919d2018-02-16 16:16:50 -0800317 private static final long DEFAULT_MAX_INTERVAL = 365 * DateUtils.DAY_IN_MILLIS;
Christopher Tateaa244da2015-08-27 15:57:57 -0700318 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700319 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700320 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700321 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800322 private final long[] DEFAULT_APP_STANDBY_DELAYS = {
323 0, // Active
324 6 * 60_000, // Working
325 30 * 60_000, // Frequent
326 2 * 60 * 60_000, // Rare
327 10 * 24 * 60 * 60_000 // Never
328 };
Christopher Tate14a7bb02015-10-01 10:24:31 -0700329
Dianne Hackborna750a632015-06-16 17:18:23 -0700330 // Minimum futurity of a new alarm
331 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
332
333 // Minimum alarm recurrence interval
334 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
335
Christopher Tate22e919d2018-02-16 16:16:50 -0800336 // Maximum alarm recurrence interval
337 public long MAX_INTERVAL = DEFAULT_MAX_INTERVAL;
338
Dianne Hackborna750a632015-06-16 17:18:23 -0700339 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
340 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
341
342 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
343 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
344
345 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
346 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
347 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
348
Christopher Tate14a7bb02015-10-01 10:24:31 -0700349 // Direct alarm listener callback timeout
350 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
351
Suprabh Shukla75edab12018-01-29 14:09:06 -0800352 public long[] APP_STANDBY_MIN_DELAYS = new long[DEFAULT_APP_STANDBY_DELAYS.length];
353
Dianne Hackborna750a632015-06-16 17:18:23 -0700354 private ContentResolver mResolver;
355 private final KeyValueListParser mParser = new KeyValueListParser(',');
356 private long mLastAllowWhileIdleWhitelistDuration = -1;
357
358 public Constants(Handler handler) {
359 super(handler);
Dianne Hackborna750a632015-06-16 17:18:23 -0700360 updateAllowWhileIdleWhitelistDurationLocked();
361 }
362
363 public void start(ContentResolver resolver) {
364 mResolver = resolver;
365 mResolver.registerContentObserver(Settings.Global.getUriFor(
366 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
367 updateConstants();
368 }
369
Dianne Hackborna750a632015-06-16 17:18:23 -0700370 public void updateAllowWhileIdleWhitelistDurationLocked() {
371 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
372 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
373 BroadcastOptions opts = BroadcastOptions.makeBasic();
374 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
375 mIdleOptions = opts.toBundle();
376 }
377 }
378
379 @Override
380 public void onChange(boolean selfChange, Uri uri) {
381 updateConstants();
382 }
383
384 private void updateConstants() {
385 synchronized (mLock) {
386 try {
387 mParser.setString(Settings.Global.getString(mResolver,
388 Settings.Global.ALARM_MANAGER_CONSTANTS));
389 } catch (IllegalArgumentException e) {
390 // Failed to parse the settings string, log this and move on
391 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800392 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700393 }
394
395 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
396 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800397 MAX_INTERVAL = mParser.getLong(KEY_MAX_INTERVAL, DEFAULT_MAX_INTERVAL);
Dianne Hackborna750a632015-06-16 17:18:23 -0700398 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
399 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
400 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
401 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
402 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
403 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
404 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700405 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
406 DEFAULT_LISTENER_TIMEOUT);
Christopher Tatef2159712018-03-27 16:04:14 -0700407 APP_STANDBY_MIN_DELAYS[ACTIVE_INDEX] = mParser.getDurationMillis(
408 KEYS_APP_STANDBY_DELAY[ACTIVE_INDEX],
409 DEFAULT_APP_STANDBY_DELAYS[ACTIVE_INDEX]);
410 for (int i = WORKING_INDEX; i < KEYS_APP_STANDBY_DELAY.length; i++) {
Suprabh Shukla75edab12018-01-29 14:09:06 -0800411 APP_STANDBY_MIN_DELAYS[i] = mParser.getDurationMillis(KEYS_APP_STANDBY_DELAY[i],
412 Math.max(APP_STANDBY_MIN_DELAYS[i-1], DEFAULT_APP_STANDBY_DELAYS[i]));
413 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700414 updateAllowWhileIdleWhitelistDurationLocked();
415 }
416 }
417
418 void dump(PrintWriter pw) {
419 pw.println(" Settings:");
420
421 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
422 TimeUtils.formatDuration(MIN_FUTURITY, pw);
423 pw.println();
424
425 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
426 TimeUtils.formatDuration(MIN_INTERVAL, pw);
427 pw.println();
428
Christopher Tate22e919d2018-02-16 16:16:50 -0800429 pw.print(" "); pw.print(KEY_MAX_INTERVAL); pw.print("=");
430 TimeUtils.formatDuration(MAX_INTERVAL, pw);
431 pw.println();
432
Christopher Tate14a7bb02015-10-01 10:24:31 -0700433 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
434 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
435 pw.println();
436
Dianne Hackborna750a632015-06-16 17:18:23 -0700437 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
438 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
439 pw.println();
440
441 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
442 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
443 pw.println();
444
445 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
446 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
447 pw.println();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800448
449 for (int i = 0; i < KEYS_APP_STANDBY_DELAY.length; i++) {
450 pw.print(" "); pw.print(KEYS_APP_STANDBY_DELAY[i]); pw.print("=");
451 TimeUtils.formatDuration(APP_STANDBY_MIN_DELAYS[i], pw);
452 pw.println();
453 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700454 }
Kweku Adams61e03292017-10-19 14:27:12 -0700455
456 void dumpProto(ProtoOutputStream proto, long fieldId) {
457 final long token = proto.start(fieldId);
458
459 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
460 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
Christopher Tate22e919d2018-02-16 16:16:50 -0800461 proto.write(ConstantsProto.MAX_INTERVAL_DURATION_MS, MAX_INTERVAL);
Kweku Adams61e03292017-10-19 14:27:12 -0700462 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
463 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
464 ALLOW_WHILE_IDLE_SHORT_TIME);
465 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
466 ALLOW_WHILE_IDLE_LONG_TIME);
467 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
468 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
469
470 proto.end(token);
471 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700472 }
473
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700474 Constants mConstants;
Dianne Hackborna750a632015-06-16 17:18:23 -0700475
Christopher Tate1590f1e2014-10-02 17:27:57 -0700476 // Alarm delivery ordering bookkeeping
477 static final int PRIO_TICK = 0;
478 static final int PRIO_WAKEUP = 1;
479 static final int PRIO_NORMAL = 2;
480
Dianne Hackborna750a632015-06-16 17:18:23 -0700481 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700482 int seq;
483 int priority;
484
485 PriorityClass() {
486 seq = mCurrentSeq - 1;
487 priority = PRIO_NORMAL;
488 }
489 }
490
Dianne Hackborna750a632015-06-16 17:18:23 -0700491 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700492 int mCurrentSeq = 0;
493
Dianne Hackborna750a632015-06-16 17:18:23 -0700494 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700495 public long when;
496 public int uid;
497 public String action;
498
499 public WakeupEvent(long theTime, int theUid, String theAction) {
500 when = theTime;
501 uid = theUid;
502 action = theAction;
503 }
504 }
505
Adam Lesinski182f73f2013-12-05 16:48:06 -0800506 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
507 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700508
Adrian Roosc42a1e12014-07-07 23:35:53 +0200509 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700510 long start; // These endpoints are always in ELAPSED
511 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700512 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700513
514 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
515
516 Batch() {
517 start = 0;
518 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700519 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520 }
521
522 Batch(Alarm seed) {
523 start = seed.whenElapsed;
Christopher Tate22e919d2018-02-16 16:16:50 -0800524 end = clampPositive(seed.maxWhenElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700525 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700526 alarms.add(seed);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700527 if (seed.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700528 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800529 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700530 }
531
532 int size() {
533 return alarms.size();
534 }
535
536 Alarm get(int index) {
537 return alarms.get(index);
538 }
539
540 boolean canHold(long whenElapsed, long maxWhen) {
541 return (end >= whenElapsed) && (start <= maxWhen);
542 }
543
544 boolean add(Alarm alarm) {
545 boolean newStart = false;
546 // narrows the batch if necessary; presumes that canHold(alarm) is true
547 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
548 if (index < 0) {
549 index = 0 - index - 1;
550 }
551 alarms.add(index, alarm);
Christopher Tatec8b7f432018-09-28 16:23:10 -0700552 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700553 mLastTickAdded = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800554 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 if (DEBUG_BATCH) {
556 Slog.v(TAG, "Adding " + alarm + " to " + this);
557 }
558 if (alarm.whenElapsed > start) {
559 start = alarm.whenElapsed;
560 newStart = true;
561 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700562 if (alarm.maxWhenElapsed < end) {
563 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700564 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700565 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700566
567 if (DEBUG_BATCH) {
568 Slog.v(TAG, " => now " + this);
569 }
570 return newStart;
571 }
572
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800573 boolean remove(Alarm alarm) {
574 return remove(a -> (a == alarm));
575 }
576
Christopher Tate1d99c392017-12-07 16:54:04 -0800577 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700578 boolean didRemove = false;
579 long newStart = 0; // recalculate endpoints as we go
580 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700581 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700582 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700583 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800584 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700585 alarms.remove(i);
586 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200587 if (alarm.alarmClock != null) {
588 mNextAlarmClockMayChange = true;
589 }
Christopher Tatec8b7f432018-09-28 16:23:10 -0700590 if (alarm.listener == mTimeTickTrigger) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700591 mLastTickRemoved = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800592 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700593 } else {
594 if (alarm.whenElapsed > newStart) {
595 newStart = alarm.whenElapsed;
596 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700597 if (alarm.maxWhenElapsed < newEnd) {
598 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700600 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700601 i++;
602 }
603 }
604 if (didRemove) {
605 // commit the new batch bounds
606 start = newStart;
607 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700608 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700609 }
610 return didRemove;
611 }
612
Christopher Tatee0a22b32013-07-11 14:43:13 -0700613 boolean hasPackage(final String packageName) {
614 final int N = alarms.size();
615 for (int i = 0; i < N; i++) {
616 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700617 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700618 return true;
619 }
620 }
621 return false;
622 }
623
624 boolean hasWakeups() {
625 final int N = alarms.size();
626 for (int i = 0; i < N; i++) {
627 Alarm a = alarms.get(i);
628 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
629 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
630 return true;
631 }
632 }
633 return false;
634 }
635
636 @Override
637 public String toString() {
638 StringBuilder b = new StringBuilder(40);
639 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
640 b.append(" num="); b.append(size());
641 b.append(" start="); b.append(start);
642 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700643 if (flags != 0) {
644 b.append(" flgs=0x");
645 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700646 }
647 b.append('}');
648 return b.toString();
649 }
Kweku Adams61e03292017-10-19 14:27:12 -0700650
651 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
652 long nowRTC) {
653 final long token = proto.start(fieldId);
654
655 proto.write(BatchProto.START_REALTIME, start);
656 proto.write(BatchProto.END_REALTIME, end);
657 proto.write(BatchProto.FLAGS, flags);
658 for (Alarm a : alarms) {
659 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
660 }
661
662 proto.end(token);
663 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700664 }
665
666 static class BatchTimeOrder implements Comparator<Batch> {
667 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800668 long when1 = b1.start;
669 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800670 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700671 return 1;
672 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800673 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700674 return -1;
675 }
676 return 0;
677 }
678 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800679
680 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
681 @Override
682 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700683 // priority class trumps everything. TICK < WAKEUP < NORMAL
684 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
685 return -1;
686 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
687 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800688 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700689
690 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800691 if (lhs.whenElapsed < rhs.whenElapsed) {
692 return -1;
693 } else if (lhs.whenElapsed > rhs.whenElapsed) {
694 return 1;
695 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700696
697 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800698 return 0;
699 }
700 };
701
Christopher Tate1590f1e2014-10-02 17:27:57 -0700702 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
703 final int N = alarms.size();
704 for (int i = 0; i < N; i++) {
705 Alarm a = alarms.get(i);
706
707 final int alarmPrio;
Christopher Tatec8b7f432018-09-28 16:23:10 -0700708 if (a.listener == mTimeTickTrigger) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700709 alarmPrio = PRIO_TICK;
710 } else if (a.wakeup) {
711 alarmPrio = PRIO_WAKEUP;
712 } else {
713 alarmPrio = PRIO_NORMAL;
714 }
715
716 PriorityClass packagePrio = a.priorityClass;
Suprabh Shukla75edab12018-01-29 14:09:06 -0800717 String alarmPackage = a.sourcePackage;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700718 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700719 if (packagePrio == null) {
720 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700721 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700722 }
723 a.priorityClass = packagePrio;
724
725 if (packagePrio.seq != mCurrentSeq) {
726 // first alarm we've seen in the current delivery generation from this package
727 packagePrio.priority = alarmPrio;
728 packagePrio.seq = mCurrentSeq;
729 } else {
730 // Multiple alarms from this package being delivered in this generation;
731 // bump the package's delivery class if it's warranted.
732 // TICK < WAKEUP < NORMAL
733 if (alarmPrio < packagePrio.priority) {
734 packagePrio.priority = alarmPrio;
735 }
736 }
737 }
738 }
739
Christopher Tatee0a22b32013-07-11 14:43:13 -0700740 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800741 static final long MIN_FUZZABLE_INTERVAL = 10000;
742 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700743 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
744
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700745 // 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 -0700746 // to run during this time are placed in mPendingWhileIdleAlarms
747 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700748 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700749 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700750
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700751 @VisibleForTesting
752 AlarmManagerService(Context context, Injector injector) {
Jeff Brownb880d882014-02-10 19:47:07 -0800753 super(context);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700754 mInjector = injector;
Jeff Brownb880d882014-02-10 19:47:07 -0800755 }
756
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700757 AlarmManagerService(Context context) {
758 this(context, new Injector(context));
759 }
760
761 private long convertToElapsed(long when, int type) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700762 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
763 if (isRtc) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700764 when -= mInjector.getCurrentTimeMillis() - mInjector.getElapsedRealtime();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700765 }
766 return when;
767 }
768
769 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
770 // calculate the end of our nominal delivery window for the alarm.
771 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
772 // Current heuristic: batchable window is 75% of either the recurrence interval
773 // [for a periodic alarm] or of the time from now to the desired delivery time,
774 // with a minimum delay/interval of 10 seconds, under which we will simply not
775 // defer the alarm.
776 long futurity = (interval == 0)
777 ? (triggerAtTime - now)
778 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700779 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700780 futurity = 0;
781 }
Christopher Tate22e919d2018-02-16 16:16:50 -0800782 return clampPositive(triggerAtTime + (long)(.75 * futurity));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700783 }
784
785 // returns true if the batch was added at the head
786 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
787 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
788 if (index < 0) {
789 index = 0 - index - 1;
790 }
791 list.add(index, newBatch);
792 return (index == 0);
793 }
794
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800795 private void insertAndBatchAlarmLocked(Alarm alarm) {
796 final int whichBatch = ((alarm.flags & AlarmManager.FLAG_STANDALONE) != 0) ? -1
797 : attemptCoalesceLocked(alarm.whenElapsed, alarm.maxWhenElapsed);
798
799 if (whichBatch < 0) {
800 addBatchLocked(mAlarmBatches, new Batch(alarm));
801 } else {
802 final Batch batch = mAlarmBatches.get(whichBatch);
803 if (batch.add(alarm)) {
804 // The start time of this batch advanced, so batch ordering may
805 // have just been broken. Move it to where it now belongs.
806 mAlarmBatches.remove(whichBatch);
807 addBatchLocked(mAlarmBatches, batch);
808 }
809 }
810 }
811
Christopher Tate385e4982013-07-23 18:22:29 -0700812 // Return the index of the matching batch, or -1 if none found.
813 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700814 final int N = mAlarmBatches.size();
815 for (int i = 0; i < N; i++) {
816 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700817 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700818 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700819 }
820 }
Christopher Tate385e4982013-07-23 18:22:29 -0700821 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700822 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800823 /** @return total count of the alarms in a set of alarm batches. */
824 static int getAlarmCount(ArrayList<Batch> batches) {
825 int ret = 0;
826
827 final int size = batches.size();
828 for (int i = 0; i < size; i++) {
829 ret += batches.get(i).size();
830 }
831 return ret;
832 }
833
834 boolean haveAlarmsTimeTickAlarm(ArrayList<Alarm> alarms) {
835 if (alarms.size() == 0) {
836 return false;
837 }
838 final int batchSize = alarms.size();
839 for (int j = 0; j < batchSize; j++) {
Christopher Tatec8b7f432018-09-28 16:23:10 -0700840 if (alarms.get(j).listener == mTimeTickTrigger) {
Makoto Onuki5d93b832018-01-10 16:12:39 -0800841 return true;
842 }
843 }
844 return false;
845 }
846
847 boolean haveBatchesTimeTickAlarm(ArrayList<Batch> batches) {
848 final int numBatches = batches.size();
849 for (int i = 0; i < numBatches; i++) {
850 if (haveAlarmsTimeTickAlarm(batches.get(i).alarms)) {
851 return true;
852 }
853 }
854 return false;
855 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700856
857 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
858 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700859 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700860 rebatchAllAlarmsLocked(true);
861 }
862 }
863
864 void rebatchAllAlarmsLocked(boolean doValidate) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800865 final long start = mStatLogger.getTime();
Makoto Onuki5d93b832018-01-10 16:12:39 -0800866 final int oldCount =
867 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
868 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
869 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
870
Christopher Tate4cb338d2013-07-26 13:11:31 -0700871 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
872 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700873 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -0700874 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate4cb338d2013-07-26 13:11:31 -0700875 final int oldBatches = oldSet.size();
876 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
877 Batch batch = oldSet.get(batchNum);
878 final int N = batch.size();
879 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700880 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700881 }
882 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700883 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
884 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
885 + " to " + mPendingIdleUntil);
886 if (mPendingIdleUntil == null) {
887 // Somehow we lost this... we need to restore all of the pending alarms.
888 restorePendingWhileIdleAlarmsLocked();
889 }
890 }
Makoto Onuki5d93b832018-01-10 16:12:39 -0800891 final int newCount =
892 getAlarmCount(mAlarmBatches) + ArrayUtils.size(mPendingWhileIdleAlarms);
893 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches)
894 || haveAlarmsTimeTickAlarm(mPendingWhileIdleAlarms);
895
896 if (oldCount != newCount) {
897 Slog.wtf(TAG, "Rebatching: total count changed from " + oldCount + " to " + newCount);
898 }
899 if (oldHasTick != newHasTick) {
900 Slog.wtf(TAG, "Rebatching: hasTick changed from " + oldHasTick + " to " + newHasTick);
901 }
902
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700903 rescheduleKernelAlarmsLocked();
904 updateNextAlarmClockLocked();
Suprabh Shukla75edab12018-01-29 14:09:06 -0800905 mStatLogger.logDurationStat(Stats.REBATCH_ALL_ALARMS, start);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700906 }
907
Suprabh Shukla92994ab2018-01-31 17:39:30 -0800908 /**
909 * Re-orders the alarm batches based on newly evaluated send times based on the current
910 * app-standby buckets
911 * @param targetPackages [Package, User] pairs for which alarms need to be re-evaluated,
912 * null indicates all
913 * @return True if there was any reordering done to the current list.
914 */
915 boolean reorderAlarmsBasedOnStandbyBuckets(ArraySet<Pair<String, Integer>> targetPackages) {
916 final long start = mStatLogger.getTime();
917 final ArrayList<Alarm> rescheduledAlarms = new ArrayList<>();
918
919 for (int batchIndex = mAlarmBatches.size() - 1; batchIndex >= 0; batchIndex--) {
920 final Batch batch = mAlarmBatches.get(batchIndex);
921 for (int alarmIndex = batch.size() - 1; alarmIndex >= 0; alarmIndex--) {
922 final Alarm alarm = batch.get(alarmIndex);
923 final Pair<String, Integer> packageUser =
924 Pair.create(alarm.sourcePackage, UserHandle.getUserId(alarm.creatorUid));
925 if (targetPackages != null && !targetPackages.contains(packageUser)) {
926 continue;
927 }
928 if (adjustDeliveryTimeBasedOnStandbyBucketLocked(alarm)) {
929 batch.remove(alarm);
930 rescheduledAlarms.add(alarm);
931 }
932 }
933 if (batch.size() == 0) {
934 mAlarmBatches.remove(batchIndex);
935 }
936 }
937 for (int i = 0; i < rescheduledAlarms.size(); i++) {
938 final Alarm a = rescheduledAlarms.get(i);
939 insertAndBatchAlarmLocked(a);
940 }
941
942 mStatLogger.logDurationStat(Stats.REORDER_ALARMS_FOR_STANDBY, start);
943 return rescheduledAlarms.size() > 0;
944 }
945
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700946 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
947 a.when = a.origWhen;
948 long whenElapsed = convertToElapsed(a.when, a.type);
949 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700950 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700951 // Exact
952 maxElapsed = whenElapsed;
953 } else {
954 // Not exact. Preserve any explicit window, otherwise recalculate
955 // the window based on the alarm's new futurity. Note that this
956 // reflects a policy of preferring timely to deferred delivery.
957 maxElapsed = (a.windowLength > 0)
Christopher Tate22e919d2018-02-16 16:16:50 -0800958 ? clampPositive(whenElapsed + a.windowLength)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700959 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
960 }
961 a.whenElapsed = whenElapsed;
962 a.maxWhenElapsed = maxElapsed;
963 setImplLocked(a, true, doValidate);
964 }
965
Christopher Tate22e919d2018-02-16 16:16:50 -0800966 static long clampPositive(long val) {
967 return (val >= 0) ? val : Long.MAX_VALUE;
968 }
969
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700970 /**
971 * Sends alarms that were blocked due to user applied background restrictions - either because
972 * the user lifted those or the uid came to foreground.
973 *
974 * @param uid uid to filter on
975 * @param packageName package to filter on, or null for all packages in uid
976 */
977 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
978 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
979 if (alarmsForUid == null || alarmsForUid.size() == 0) {
980 return;
981 }
982 final ArrayList<Alarm> alarmsToDeliver;
983 if (packageName != null) {
984 if (DEBUG_BG_LIMIT) {
985 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
986 }
987 alarmsToDeliver = new ArrayList<>();
988 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
989 final Alarm a = alarmsForUid.get(i);
990 if (a.matches(packageName)) {
991 alarmsToDeliver.add(alarmsForUid.remove(i));
992 }
993 }
994 if (alarmsForUid.size() == 0) {
995 mPendingBackgroundAlarms.remove(uid);
996 }
997 } else {
998 if (DEBUG_BG_LIMIT) {
999 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
1000 }
1001 alarmsToDeliver = alarmsForUid;
1002 mPendingBackgroundAlarms.remove(uid);
1003 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001004 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001005 }
1006
Makoto Onuki2206af32017-11-21 16:25:35 -08001007 /**
1008 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
1009 * restricted.
1010 *
1011 * This is only called when the global "force all apps-standby" flag changes or when the
1012 * power save whitelist changes, so it's okay to be slow.
1013 */
1014 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001015 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -08001016
1017 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1018 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
1019
1020 if (alarmsToDeliver.size() > 0) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001021 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, mInjector.getElapsedRealtime());
Makoto Onuki2206af32017-11-21 16:25:35 -08001022 }
1023 }
1024
1025 @VisibleForTesting
1026 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
1027 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
1028 Predicate<Alarm> isBackgroundRestricted) {
1029
1030 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
1031 final int uid = pendingAlarms.keyAt(uidIndex);
1032 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
1033
1034 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
1035 final Alarm alarm = alarmsForUid.get(alarmIndex);
1036
1037 if (isBackgroundRestricted.test(alarm)) {
1038 continue;
1039 }
1040
1041 unrestrictedAlarms.add(alarm);
1042 alarmsForUid.remove(alarmIndex);
1043 }
1044
1045 if (alarmsForUid.size() == 0) {
1046 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001047 }
1048 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001049 }
1050
1051 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
1052 final int N = alarms.size();
1053 boolean hasWakeup = false;
1054 for (int i = 0; i < N; i++) {
1055 final Alarm alarm = alarms.get(i);
1056 if (alarm.wakeup) {
1057 hasWakeup = true;
1058 }
1059 alarm.count = 1;
1060 // Recurring alarms may have passed several alarm intervals while the
1061 // alarm was kept pending. Send the appropriate trigger count.
1062 if (alarm.repeatInterval > 0) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001063 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001064 // Also schedule its next recurrence
1065 final long delta = alarm.count * alarm.repeatInterval;
1066 final long nextElapsed = alarm.whenElapsed + delta;
1067 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
1068 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
1069 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
1070 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
1071 // Kernel alarms will be rescheduled as needed in setImplLocked
1072 }
1073 }
1074 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
1075 // No need to wakeup for non wakeup alarms
1076 if (mPendingNonWakeupAlarms.size() == 0) {
1077 mStartCurrentDelayTime = nowELAPSED;
1078 mNextNonWakeupDeliveryTime = nowELAPSED
1079 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
1080 }
1081 mPendingNonWakeupAlarms.addAll(alarms);
1082 mNumDelayedAlarms += alarms.size();
1083 } else {
1084 if (DEBUG_BG_LIMIT) {
1085 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
1086 }
1087 // Since we are waking up, also deliver any pending non wakeup alarms we have.
1088 if (mPendingNonWakeupAlarms.size() > 0) {
1089 alarms.addAll(mPendingNonWakeupAlarms);
1090 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
1091 mTotalDelayTime += thisDelayTime;
1092 if (mMaxDelayTime < thisDelayTime) {
1093 mMaxDelayTime = thisDelayTime;
1094 }
1095 mPendingNonWakeupAlarms.clear();
1096 }
1097 calculateDeliveryPriorities(alarms);
1098 Collections.sort(alarms, mAlarmDispatchComparator);
1099 deliverAlarmsLocked(alarms, nowELAPSED);
1100 }
1101 }
1102
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001103 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001104 if (RECORD_DEVICE_IDLE_ALARMS) {
1105 IdleDispatchEntry ent = new IdleDispatchEntry();
1106 ent.uid = 0;
1107 ent.pkg = "FINISH IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001108 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001109 mAllowWhileIdleDispatches.add(ent);
1110 }
1111
Dianne Hackborn35d54032015-04-23 10:30:43 -07001112 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001113 if (mPendingWhileIdleAlarms.size() > 0) {
1114 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
1115 mPendingWhileIdleAlarms = new ArrayList<>();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001116 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001117 for (int i=alarms.size() - 1; i >= 0; i--) {
1118 Alarm a = alarms.get(i);
1119 reAddAlarmLocked(a, nowElapsed, false);
1120 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001121 }
Dianne Hackborn35d54032015-04-23 10:30:43 -07001122
1123 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001124 rescheduleKernelAlarmsLocked();
1125 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -07001126
Christopher Tatee0a22b32013-07-11 14:43:13 -07001127 }
1128
Christopher Tate14a7bb02015-10-01 10:24:31 -07001129 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -08001130 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001131 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001132 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001133 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001134 final int mUid;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001135 final int mCreatorUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001136 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001137 final BroadcastStats mBroadcastStats;
1138 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001139 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001140
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001141 InFlight(AlarmManagerService service, Alarm alarm, long nowELAPSED) {
1142 mPendingIntent = alarm.operation;
Christopher Tateeabba732017-08-17 17:12:52 -07001143 mWhenElapsed = nowELAPSED;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001144 mListener = alarm.listener != null ? alarm.listener.asBinder() : null;
1145 mWorkSource = alarm.workSource;
1146 mUid = alarm.uid;
1147 mCreatorUid = alarm.creatorUid;
1148 mTag = alarm.statsTag;
1149 mBroadcastStats = (alarm.operation != null)
1150 ? service.getStatsLocked(alarm.operation)
1151 : service.getStatsLocked(alarm.uid, alarm.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001152 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001153 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001154 fs = new FilterStats(mBroadcastStats, mTag);
1155 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001156 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001157 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001158 mFilterStats = fs;
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001159 mAlarmType = alarm.type;
Dianne Hackborn81038902012-11-26 17:04:09 -08001160 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001161
1162 @Override
1163 public String toString() {
1164 return "InFlight{"
1165 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001166 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001167 + ", workSource=" + mWorkSource
1168 + ", uid=" + mUid
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00001169 + ", creatorUid=" + mCreatorUid
Makoto Onuki33955e12017-03-01 18:11:00 -08001170 + ", tag=" + mTag
1171 + ", broadcastStats=" + mBroadcastStats
1172 + ", filterStats=" + mFilterStats
1173 + ", alarmType=" + mAlarmType
1174 + "}";
1175 }
Kweku Adams61e03292017-10-19 14:27:12 -07001176
1177 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1178 final long token = proto.start(fieldId);
1179
1180 proto.write(InFlightProto.UID, mUid);
1181 proto.write(InFlightProto.TAG, mTag);
1182 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1183 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1184 if (mPendingIntent != null) {
1185 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1186 }
1187 if (mBroadcastStats != null) {
1188 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1189 }
1190 if (mFilterStats != null) {
1191 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1192 }
1193 if (mWorkSource != null) {
1194 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1195 }
1196
1197 proto.end(token);
1198 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001200
Adam Lesinski182f73f2013-12-05 16:48:06 -08001201 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001202 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001203 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001204
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001205 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001207 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001208 int numWakeup;
1209 long startTime;
1210 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001211
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001212 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001213 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001214 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001215 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001216
1217 @Override
1218 public String toString() {
1219 return "FilterStats{"
1220 + "tag=" + mTag
1221 + ", lastTime=" + lastTime
1222 + ", aggregateTime=" + aggregateTime
1223 + ", count=" + count
1224 + ", numWakeup=" + numWakeup
1225 + ", startTime=" + startTime
1226 + ", nesting=" + nesting
1227 + "}";
1228 }
Kweku Adams61e03292017-10-19 14:27:12 -07001229
1230 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1231 final long token = proto.start(fieldId);
1232
1233 proto.write(FilterStatsProto.TAG, mTag);
1234 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1235 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1236 proto.write(FilterStatsProto.COUNT, count);
1237 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1238 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1239 proto.write(FilterStatsProto.NESTING, nesting);
1240
1241 proto.end(token);
1242 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001243 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001244
Adam Lesinski182f73f2013-12-05 16:48:06 -08001245 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001246 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001247 final String mPackageName;
1248
1249 long aggregateTime;
1250 int count;
1251 int numWakeup;
1252 long startTime;
1253 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001254 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001255
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001256 BroadcastStats(int uid, String packageName) {
1257 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001258 mPackageName = packageName;
1259 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001260
1261 @Override
1262 public String toString() {
1263 return "BroadcastStats{"
1264 + "uid=" + mUid
1265 + ", packageName=" + mPackageName
1266 + ", aggregateTime=" + aggregateTime
1267 + ", count=" + count
1268 + ", numWakeup=" + numWakeup
1269 + ", startTime=" + startTime
1270 + ", nesting=" + nesting
1271 + "}";
1272 }
Kweku Adams61e03292017-10-19 14:27:12 -07001273
1274 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1275 final long token = proto.start(fieldId);
1276
1277 proto.write(BroadcastStatsProto.UID, mUid);
1278 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1279 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1280 proto.write(BroadcastStatsProto.COUNT, count);
1281 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1282 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1283 proto.write(BroadcastStatsProto.NESTING, nesting);
1284
1285 proto.end(token);
1286 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001288
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001289 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1290 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001291
1292 int mNumDelayedAlarms = 0;
1293 long mTotalDelayTime = 0;
1294 long mMaxDelayTime = 0;
1295
Adam Lesinski182f73f2013-12-05 16:48:06 -08001296 @Override
1297 public void onStart() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001298 mInjector.init();
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001299
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001300 synchronized (mLock) {
Suprabh Shukla12bd0162018-11-12 18:00:18 -08001301 mHandler = new AlarmHandler();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001302 mConstants = new Constants(mHandler);
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001303
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001304 mNextWakeup = mNextNonWakeup = 0;
1305
1306 // We have to set current TimeZone info to kernel
1307 // because kernel doesn't keep this after reboot
1308 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
1309
Christopher Tate3d65d4d2018-12-11 14:55:19 -08001310 // Ensure that we're booting with a halfway sensible current time. Use the
1311 // most recent of Build.TIME, the root file system's timestamp, and the
1312 // value of the ro.build.date.utc system property (which is in seconds).
1313 final long systemBuildTime = Long.max(
1314 1000L * SystemProperties.getLong("ro.build.date.utc", -1L),
1315 Long.max(Environment.getRootDirectory().lastModified(), Build.TIME));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001316 if (mInjector.getCurrentTimeMillis() < systemBuildTime) {
1317 Slog.i(TAG, "Current time only " + mInjector.getCurrentTimeMillis()
Christopher Tate247571462017-04-10 11:45:05 -07001318 + ", advancing to build time " + systemBuildTime);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001319 mInjector.setKernelTime(systemBuildTime);
Christopher Tate247571462017-04-10 11:45:05 -07001320 }
Christopher Tate247571462017-04-10 11:45:05 -07001321
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001322 // Determine SysUI's uid
1323 mSystemUiUid = mInjector.getSystemUiUid();
1324 if (mSystemUiUid <= 0) {
1325 Slog.wtf(TAG, "SysUI package not found!");
1326 }
1327 mWakeLock = mInjector.getAlarmWakeLock();
1328
Christopher Tatec8b7f432018-09-28 16:23:10 -07001329 mTimeTickIntent = new Intent(Intent.ACTION_TIME_TICK).addFlags(
1330 Intent.FLAG_RECEIVER_REGISTERED_ONLY
1331 | Intent.FLAG_RECEIVER_FOREGROUND
1332 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1333
1334 mTimeTickTrigger = new IAlarmListener.Stub() {
1335 @Override
1336 public void doAlarm(final IAlarmCompleteListener callback) throws RemoteException {
1337 if (DEBUG_BATCH) {
1338 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
1339 }
1340
1341 // Via handler because dispatch invokes this within its lock. OnAlarmListener
1342 // takes care of this automatically, but we're using the direct internal
1343 // interface here rather than that client-side wrapper infrastructure.
1344 mHandler.post(() -> {
1345 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL);
1346
1347 try {
1348 callback.alarmComplete(this);
1349 } catch (RemoteException e) { /* local method call */ }
1350 });
1351
1352 synchronized (mLock) {
1353 mLastTickReceived = mInjector.getCurrentTimeMillis();
1354 }
1355 mClockReceiver.scheduleTimeTickEvent();
1356 }
1357 };
1358
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001359 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
1360 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1361 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
1362 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
1363 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
1364
1365 mClockReceiver = mInjector.getClockReceiver(this);
1366 new InteractiveStateReceiver();
1367 new UninstallReceiver();
1368
1369 if (mInjector.isAlarmDriverPresent()) {
1370 AlarmThread waitThread = new AlarmThread();
1371 waitThread.start();
Christopher Tatebb9cce52017-04-18 14:19:43 -07001372 } else {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001373 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
Christopher Tatebb9cce52017-04-18 14:19:43 -07001374 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001375
1376 try {
1377 ActivityManager.getService().registerUidObserver(new UidObserver(),
1378 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1379 | ActivityManager.UID_OBSERVER_ACTIVE,
1380 ActivityManager.PROCESS_STATE_UNKNOWN, null);
1381 } catch (RemoteException e) {
1382 // ignored; both services live in system_server
1383 }
Christopher Tatebb9cce52017-04-18 14:19:43 -07001384 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001385 publishLocalService(AlarmManagerInternal.class, new LocalService());
Adam Lesinski182f73f2013-12-05 16:48:06 -08001386 publishBinderService(Context.ALARM_SERVICE, mService);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001388
1389 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001390 public void onBootPhase(int phase) {
1391 if (phase == PHASE_SYSTEM_SERVICES_READY) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001392 synchronized (mLock) {
1393 mConstants.start(getContext().getContentResolver());
1394 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
1395 mLocalDeviceIdleController =
1396 LocalServices.getService(DeviceIdleController.LocalService.class);
1397 mUsageStatsManagerInternal =
1398 LocalServices.getService(UsageStatsManagerInternal.class);
1399 mUsageStatsManagerInternal.addAppIdleStateChangeListener(new AppStandbyTracker());
Makoto Onukie4918212018-02-06 11:30:15 -08001400
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001401 mAppStateTracker = LocalServices.getService(AppStateTracker.class);
1402 mAppStateTracker.addListener(mForceAppStandbyListener);
1403
1404 mClockReceiver.scheduleTimeTickEvent();
1405 mClockReceiver.scheduleDateChangedEvent();
1406 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001407 }
1408 }
1409
1410 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 protected void finalize() throws Throwable {
1412 try {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001413 mInjector.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 } finally {
1415 super.finalize();
1416 }
1417 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001418
mswest463f4c99d2018-02-01 10:13:10 -08001419 boolean setTimeImpl(long millis) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001420 if (!mInjector.isAlarmDriverPresent()) {
mswest463f4c99d2018-02-01 10:13:10 -08001421 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1422 return false;
1423 }
1424
1425 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001426 final long currentTimeMillis = mInjector.getCurrentTimeMillis();
1427 mInjector.setKernelTime(millis);
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001428 final TimeZone timeZone = TimeZone.getDefault();
1429 final int currentTzOffset = timeZone.getOffset(currentTimeMillis);
1430 final int newTzOffset = timeZone.getOffset(millis);
1431 if (currentTzOffset != newTzOffset) {
1432 Slog.i(TAG, "Timezone offset has changed, updating kernel timezone");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001433 mInjector.setKernelTimezone(-(newTzOffset / 60000));
Christine Hallstromf5d585a2018-05-21 14:27:23 -07001434 }
1435 // The native implementation of setKernelTime can return -1 even when the kernel
1436 // time was set correctly, so assume setting kernel time was successful and always
1437 // return true.
1438 return true;
mswest463f4c99d2018-02-01 10:13:10 -08001439 }
1440 }
1441
Adam Lesinski182f73f2013-12-05 16:48:06 -08001442 void setTimeZoneImpl(String tz) {
1443 if (TextUtils.isEmpty(tz)) {
1444 return;
David Christieebe51fc2013-07-26 13:23:29 -07001445 }
1446
Adam Lesinski182f73f2013-12-05 16:48:06 -08001447 TimeZone zone = TimeZone.getTimeZone(tz);
1448 // Prevent reentrant calls from stepping on each other when writing
1449 // the time zone property
1450 boolean timeZoneWasChanged = false;
1451 synchronized (this) {
1452 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1453 if (current == null || !current.equals(zone.getID())) {
1454 if (localLOGV) {
1455 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1456 }
1457 timeZoneWasChanged = true;
1458 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1459 }
1460
1461 // Update the kernel timezone information
1462 // Kernel tracks time offsets as 'minutes west of GMT'
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001463 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
1464 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001465 }
1466
1467 TimeZone.setDefault(null);
1468
1469 if (timeZoneWasChanged) {
Christopher Tatea4618b02018-10-11 16:22:55 -07001470 // Don't wait for broadcasts to update our midnight alarm
1471 mClockReceiver.scheduleDateChangedEvent();
1472
1473 // And now let everyone else know
Adam Lesinski182f73f2013-12-05 16:48:06 -08001474 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001475 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001476 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001477 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001478 intent.putExtra("time-zone", zone.getID());
1479 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1480 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001481 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001482
Christopher Tatec8b7f432018-09-28 16:23:10 -07001483 void removeImpl(PendingIntent operation, IAlarmListener listener) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001484 synchronized (mLock) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07001485 removeLocked(operation, listener);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001486 }
1487 }
1488
1489 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001490 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1491 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1492 int callingUid, String callingPackage) {
1493 // must be *either* PendingIntent or AlarmReceiver, but not both
1494 if ((operation == null && directReceiver == null)
1495 || (operation != null && directReceiver != null)) {
1496 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1497 // NB: previous releases failed silently here, so we are continuing to do the same
1498 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001499 return;
1500 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001501
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001502 // Sanity check the window length. This will catch people mistakenly
1503 // trying to pass an end-of-window timestamp rather than a duration.
1504 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1505 Slog.w(TAG, "Window length " + windowLength
1506 + "ms suspiciously long; limiting to 1 hour");
1507 windowLength = AlarmManager.INTERVAL_HOUR;
1508 }
1509
Christopher Tate498c6cb2014-11-17 16:09:27 -08001510 // Sanity check the recurrence interval. This will catch people who supply
Christopher Tate22e919d2018-02-16 16:16:50 -08001511 // seconds when the API expects milliseconds, or apps trying shenanigans
1512 // around intentional period overflow, etc.
Dianne Hackborna750a632015-06-16 17:18:23 -07001513 final long minInterval = mConstants.MIN_INTERVAL;
1514 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001515 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001516 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001517 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001518 interval = minInterval;
Christopher Tate22e919d2018-02-16 16:16:50 -08001519 } else if (interval > mConstants.MAX_INTERVAL) {
1520 Slog.w(TAG, "Suspiciously long interval " + interval
1521 + " millis; clamping");
1522 interval = mConstants.MAX_INTERVAL;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001523 }
1524
Christopher Tatee0a22b32013-07-11 14:43:13 -07001525 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1526 throw new IllegalArgumentException("Invalid alarm type " + type);
1527 }
1528
Christopher Tate5f221e82013-07-30 17:13:15 -07001529 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001530 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001531 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001532 + " pid=" + what);
1533 triggerAtTime = 0;
1534 }
1535
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001536 final long nowElapsed = mInjector.getElapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001537 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1538 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001539 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001540 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1541
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001542 final long maxElapsed;
1543 if (windowLength == AlarmManager.WINDOW_EXACT) {
1544 maxElapsed = triggerElapsed;
1545 } else if (windowLength < 0) {
1546 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001547 // Fix this window in place, so that as time approaches we don't collapse it.
1548 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001549 } else {
1550 maxElapsed = triggerElapsed + windowLength;
1551 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001552
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001553 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001554 if (DEBUG_BATCH) {
1555 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001556 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001557 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001558 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001559 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001560 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001561 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1562 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 }
1564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001565
Christopher Tate3e04b472013-10-21 17:51:31 -07001566 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001567 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1568 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1569 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001570 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001571 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1572 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001573 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001574 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001575 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1576 + " -- package not allowed to start");
1577 return;
1578 }
1579 } catch (RemoteException e) {
1580 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001581 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001582 setImplLocked(a, false, doValidate);
1583 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001584
Christopher Tatef2159712018-03-27 16:04:14 -07001585 /**
1586 * Return the minimum time that should elapse before an app in the specified bucket
1587 * can receive alarms again
1588 */
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001589 @VisibleForTesting
1590 long getMinDelayForBucketLocked(int bucket) {
Christopher Tatef2159712018-03-27 16:04:14 -07001591 // UsageStats bucket values are treated as floors of their behavioral range.
1592 // In other words, a bucket value between WORKING and ACTIVE is treated as
1593 // WORKING, not as ACTIVE. The ACTIVE and NEVER bucket apply only at specific
1594 // values.
1595 final int index;
1596
1597 if (bucket == UsageStatsManager.STANDBY_BUCKET_NEVER) index = NEVER_INDEX;
1598 else if (bucket > UsageStatsManager.STANDBY_BUCKET_FREQUENT) index = RARE_INDEX;
1599 else if (bucket > UsageStatsManager.STANDBY_BUCKET_WORKING_SET) index = FREQUENT_INDEX;
1600 else if (bucket > UsageStatsManager.STANDBY_BUCKET_ACTIVE) index = WORKING_INDEX;
1601 else index = ACTIVE_INDEX;
1602
1603 return mConstants.APP_STANDBY_MIN_DELAYS[index];
Suprabh Shukla75edab12018-01-29 14:09:06 -08001604 }
1605
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001606 /**
1607 * Adjusts the alarm delivery time based on the current app standby bucket.
1608 * @param alarm The alarm to adjust
1609 * @return true if the alarm delivery time was updated.
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001610 */
1611 private boolean adjustDeliveryTimeBasedOnStandbyBucketLocked(Alarm alarm) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001612 if (isExemptFromAppStandby(alarm)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001613 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001614 }
1615 if (mAppStandbyParole) {
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001616 if (alarm.whenElapsed > alarm.expectedWhenElapsed) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001617 // We did defer this alarm earlier, restore original requirements
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001618 alarm.whenElapsed = alarm.expectedWhenElapsed;
1619 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
1620 return true;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001621 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001622 return false;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001623 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001624 final long oldWhenElapsed = alarm.whenElapsed;
1625 final long oldMaxWhenElapsed = alarm.maxWhenElapsed;
1626
Suprabh Shukla75edab12018-01-29 14:09:06 -08001627 final String sourcePackage = alarm.sourcePackage;
1628 final int sourceUserId = UserHandle.getUserId(alarm.creatorUid);
1629 final int standbyBucket = mUsageStatsManagerInternal.getAppStandbyBucket(
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001630 sourcePackage, sourceUserId, mInjector.getElapsedRealtime());
Suprabh Shukla75edab12018-01-29 14:09:06 -08001631
1632 final Pair<String, Integer> packageUser = Pair.create(sourcePackage, sourceUserId);
1633 final long lastElapsed = mLastAlarmDeliveredForPackage.getOrDefault(packageUser, 0L);
1634 if (lastElapsed > 0) {
1635 final long minElapsed = lastElapsed + getMinDelayForBucketLocked(standbyBucket);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001636 if (alarm.expectedWhenElapsed < minElapsed) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08001637 alarm.whenElapsed = alarm.maxWhenElapsed = minElapsed;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001638 } else {
1639 // app is now eligible to run alarms at the originally requested window.
1640 // Restore original requirements in case they were changed earlier.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001641 alarm.whenElapsed = alarm.expectedWhenElapsed;
1642 alarm.maxWhenElapsed = alarm.expectedMaxWhenElapsed;
Suprabh Shukla75edab12018-01-29 14:09:06 -08001643 }
1644 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001645 return (oldWhenElapsed != alarm.whenElapsed || oldMaxWhenElapsed != alarm.maxWhenElapsed);
Suprabh Shukla75edab12018-01-29 14:09:06 -08001646 }
1647
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001648 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1649 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001650 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001651 // The caller has given the time they want this to happen at, however we need
1652 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001653 // bring us out of idle at an earlier time.
1654 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001655 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001656 }
1657 // Add fuzz to make the alarm go off some time before the actual desired time.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001658 final long nowElapsed = mInjector.getElapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001659 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001660 if (fuzz > 0) {
1661 if (mRandom == null) {
1662 mRandom = new Random();
1663 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001664 final int delta = mRandom.nextInt(fuzz);
1665 a.whenElapsed -= delta;
1666 if (false) {
1667 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1668 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1669 Slog.d(TAG, "Applied fuzz: " + fuzz);
1670 Slog.d(TAG, "Final delta: " + delta);
1671 Slog.d(TAG, "Final when: " + a.whenElapsed);
1672 }
1673 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001674 }
1675
1676 } else if (mPendingIdleUntil != null) {
1677 // We currently have an idle until alarm scheduled; if the new alarm has
1678 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001679 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1680 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1681 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001682 == 0) {
1683 mPendingWhileIdleAlarms.add(a);
1684 return;
1685 }
1686 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001687 if (RECORD_DEVICE_IDLE_ALARMS) {
1688 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1689 IdleDispatchEntry ent = new IdleDispatchEntry();
1690 ent.uid = a.uid;
1691 ent.pkg = a.operation.getCreatorPackage();
1692 ent.tag = a.operation.getTag("");
1693 ent.op = "SET";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001694 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001695 ent.argRealtime = a.whenElapsed;
1696 mAllowWhileIdleDispatches.add(ent);
1697 }
1698 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08001699 adjustDeliveryTimeBasedOnStandbyBucketLocked(a);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08001700 insertAndBatchAlarmLocked(a);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001702 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001703 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001704 }
1705
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001706 boolean needRebatch = false;
1707
1708 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001709 if (RECORD_DEVICE_IDLE_ALARMS) {
1710 if (mPendingIdleUntil == null) {
1711 IdleDispatchEntry ent = new IdleDispatchEntry();
1712 ent.uid = 0;
1713 ent.pkg = "START IDLE";
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001714 ent.elapsedRealtime = mInjector.getElapsedRealtime();
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001715 mAllowWhileIdleDispatches.add(ent);
1716 }
1717 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001718 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1719 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1720 + " to " + a);
1721 }
1722
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001723 mPendingIdleUntil = a;
1724 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001725 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1726 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1727 mNextWakeFromIdle = a;
1728 // If this wake from idle is earlier than whatever was previously scheduled,
1729 // and we are currently idling, then we need to rebatch alarms in case the idle
1730 // until time needs to be updated.
1731 if (mPendingIdleUntil != null) {
1732 needRebatch = true;
1733 }
1734 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001735 }
1736
1737 if (!rebatching) {
1738 if (DEBUG_VALIDATE) {
1739 if (doValidate && !validateConsistencyLocked()) {
1740 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1741 + " when(hex)=" + Long.toHexString(a.when)
1742 + " whenElapsed=" + a.whenElapsed
1743 + " maxWhenElapsed=" + a.maxWhenElapsed
1744 + " interval=" + a.repeatInterval + " op=" + a.operation
1745 + " flags=0x" + Integer.toHexString(a.flags));
1746 rebatchAllAlarmsLocked(false);
1747 needRebatch = false;
1748 }
1749 }
1750
1751 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001752 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001753 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001754
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001755 rescheduleKernelAlarmsLocked();
1756 updateNextAlarmClockLocked();
1757 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001758 }
1759
Christopher Tate1d99c392017-12-07 16:54:04 -08001760 /**
1761 * System-process internal API
1762 */
1763 private final class LocalService implements AlarmManagerInternal {
1764 @Override
1765 public void removeAlarmsForUid(int uid) {
1766 synchronized (mLock) {
1767 removeLocked(uid);
1768 }
1769 }
1770 }
1771
1772 /**
1773 * Public-facing binder interface
1774 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001775 private final IBinder mService = new IAlarmManager.Stub() {
1776 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001777 public void set(String callingPackage,
1778 int type, long triggerAtTime, long windowLength, long interval, int flags,
1779 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1780 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001781 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001782
1783 // make sure the caller is not lying about which package should be blamed for
1784 // wakelock time spent in alarm delivery
1785 mAppOps.checkPackage(callingUid, callingPackage);
1786
1787 // Repeating alarms must use PendingIntent, not direct listener
1788 if (interval != 0) {
1789 if (directReceiver != null) {
1790 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1791 }
1792 }
1793
Adam Lesinski182f73f2013-12-05 16:48:06 -08001794 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001795 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001796 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001797 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001798 }
1799
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001800 // No incoming callers can request either WAKE_FROM_IDLE or
1801 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1802 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1803 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1804
1805 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1806 // manager when to come out of idle mode, which is only for DeviceIdleController.
1807 if (callingUid != Process.SYSTEM_UID) {
1808 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1809 }
1810
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001811 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001812 if (windowLength == AlarmManager.WINDOW_EXACT) {
1813 flags |= AlarmManager.FLAG_STANDALONE;
1814 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001815
1816 // If this alarm is for an alarm clock, then it must be standalone and we will
1817 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001818 if (alarmClock != null) {
1819 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001820
1821 // If the caller is a core system component or on the user's whitelist, and not calling
1822 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1823 // This means we will allow these alarms to go off as normal even while idle, with no
1824 // timing restrictions.
1825 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08001826 || UserHandle.isSameApp(callingUid, mSystemUiUid)
Makoto Onukie4918212018-02-06 11:30:15 -08001827 || ((mAppStateTracker != null)
Suprabh Shukla5bf49812018-05-24 18:38:50 -07001828 && mAppStateTracker.isUidPowerSaveUserWhitelisted(callingUid)))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001829 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1830 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001831 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001832
Christopher Tate14a7bb02015-10-01 10:24:31 -07001833 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1834 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001835 }
Christopher Tate89779822012-08-31 14:40:03 -07001836
Adam Lesinski182f73f2013-12-05 16:48:06 -08001837 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001838 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001839 getContext().enforceCallingOrSelfPermission(
1840 "android.permission.SET_TIME",
1841 "setTime");
1842
mswest463f4c99d2018-02-01 10:13:10 -08001843 return setTimeImpl(millis);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001845
1846 @Override
1847 public void setTimeZone(String tz) {
1848 getContext().enforceCallingOrSelfPermission(
1849 "android.permission.SET_TIME_ZONE",
1850 "setTimeZone");
1851
1852 final long oldId = Binder.clearCallingIdentity();
1853 try {
1854 setTimeZoneImpl(tz);
1855 } finally {
1856 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001857 }
1858 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001859
Adam Lesinski182f73f2013-12-05 16:48:06 -08001860 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001861 public void remove(PendingIntent operation, IAlarmListener listener) {
1862 if (operation == null && listener == null) {
1863 Slog.w(TAG, "remove() with no intent or listener");
1864 return;
1865 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001866
Christopher Tate14a7bb02015-10-01 10:24:31 -07001867 synchronized (mLock) {
1868 removeLocked(operation, listener);
1869 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001870 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001871
Adam Lesinski182f73f2013-12-05 16:48:06 -08001872 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001873 public long getNextWakeFromIdleTime() {
1874 return getNextWakeFromIdleTimeImpl();
1875 }
1876
1877 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001878 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001879 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1880 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1881 "getNextAlarmClock", null);
1882
1883 return getNextAlarmClockImpl(userId);
1884 }
1885
1886 @Override
Jeff Sharkey9911a282018-02-14 22:29:11 -07001887 public long currentNetworkTimeMillis() {
1888 final NtpTrustedTime time = NtpTrustedTime.getInstance(getContext());
1889 if (time.hasCache()) {
1890 return time.currentTimeMillis();
1891 } else {
1892 throw new ParcelableException(new DateTimeException("Missing NTP fix"));
1893 }
1894 }
1895
1896 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001897 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001898 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001899
1900 if (args.length > 0 && "--proto".equals(args[0])) {
1901 dumpProto(fd);
1902 } else {
1903 dumpImpl(pw);
1904 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001905 }
mswest463f4c99d2018-02-01 10:13:10 -08001906
1907 @Override
1908 public void onShellCommand(FileDescriptor in, FileDescriptor out,
1909 FileDescriptor err, String[] args, ShellCallback callback,
1910 ResultReceiver resultReceiver) {
1911 (new ShellCmd()).exec(this, in, out, err, args, callback, resultReceiver);
1912 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001913 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001914
Adam Lesinski182f73f2013-12-05 16:48:06 -08001915 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001916 synchronized (mLock) {
1917 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001918 mConstants.dump(pw);
1919 pw.println();
1920
Makoto Onukie4918212018-02-06 11:30:15 -08001921 if (mAppStateTracker != null) {
1922 mAppStateTracker.dump(pw, " ");
1923 pw.println();
1924 }
Makoto Onuki2206af32017-11-21 16:25:35 -08001925
Suprabh Shukla75edab12018-01-29 14:09:06 -08001926 pw.println(" App Standby Parole: " + mAppStandbyParole);
1927 pw.println();
1928
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07001929 final long nowELAPSED = mInjector.getElapsedRealtime();
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001930 final long nowUPTIME = SystemClock.uptimeMillis();
Christopher Tatec8b7f432018-09-28 16:23:10 -07001931 final long nowRTC = mInjector.getCurrentTimeMillis();
Makoto Onuki5d93b832018-01-10 16:12:39 -08001932 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001933
Dianne Hackborna750a632015-06-16 17:18:23 -07001934 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001935 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001936 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001937 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001938 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001939 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001940 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
Christopher Tate12cf0b62018-01-05 18:40:14 -08001941 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1942 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Makoto Onuki5d93b832018-01-10 16:12:39 -08001943 pw.print(" mLastTickAdded="); pw.println(sdf.format(new Date(mLastTickAdded)));
1944 pw.print(" mLastTickRemoved="); pw.println(sdf.format(new Date(mLastTickRemoved)));
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001945
Christopher Tatec8b7f432018-09-28 16:23:10 -07001946 if (RECORD_ALARMS_IN_HISTORY) {
1947 pw.println();
1948 pw.println(" Recent TIME_TICK history:");
1949 int i = mNextTickHistory;
1950 do {
1951 i--;
1952 if (i < 0) i = TICK_HISTORY_DEPTH - 1;
1953 final long time = mTickHistory[i];
1954 pw.print(" ");
1955 pw.println((time > 0)
1956 ? sdf.format(new Date(nowRTC - (nowELAPSED - time)))
1957 : "-");
1958 } while (i != mNextTickHistory);
1959 pw.println();
1960 }
1961
Makoto Onukie8edbcf2018-03-02 16:49:29 -08001962 SystemServiceManager ssm = LocalServices.getService(SystemServiceManager.class);
1963 if (ssm != null) {
1964 pw.println();
1965 pw.print(" RuntimeStarted=");
1966 pw.print(sdf.format(
1967 new Date(nowRTC - nowELAPSED + ssm.getRuntimeStartElapsedTime())));
1968 if (ssm.isRuntimeRestarted()) {
1969 pw.print(" (Runtime restarted)");
1970 }
1971 pw.println();
1972 pw.print(" Runtime uptime (elapsed): ");
1973 TimeUtils.formatDuration(nowELAPSED, ssm.getRuntimeStartElapsedTime(), pw);
1974 pw.println();
1975 pw.print(" Runtime uptime (uptime): ");
1976 TimeUtils.formatDuration(nowUPTIME, ssm.getRuntimeStartUptime(), pw);
1977 pw.println();
1978 }
1979
Dianne Hackbornc3527222015-05-13 14:03:20 -07001980 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001981 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001982 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001983 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1984 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001985 }
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001986 pw.print(" Max wakeup delay: ");
1987 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1988 pw.println();
1989 pw.print(" Time since last dispatch: ");
1990 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1991 pw.println();
1992 pw.print(" Next non-wakeup delivery time: ");
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07001993 TimeUtils.formatDuration(mNextNonWakeupDeliveryTime, nowELAPSED, pw);
Makoto Onuki0b05aa62018-02-09 16:14:26 -08001994 pw.println();
Christopher Tatee0a22b32013-07-11 14:43:13 -07001995
1996 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1997 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001998 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001999 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002000 pw.print(" = "); pw.print(mNextNonWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002001 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002002 pw.print(" set at "); TimeUtils.formatDuration(mNextNonWakeUpSetAt, nowELAPSED, pw);
2003 pw.println();
Christopher Tate8b98ade2018-02-09 11:13:19 -08002004 pw.print(" Next wakeup alarm: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
2005 pw.print(" = "); pw.print(mNextWakeup);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002006 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002007 pw.print(" set at "); TimeUtils.formatDuration(mNextWakeUpSetAt, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002008 pw.println();
Suprabh Shukla2324e982018-06-05 21:06:22 -07002009
2010 pw.print(" Next kernel non-wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002011 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002012 pw.println();
2013 pw.print(" Next kernel wakeup alarm: ");
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002014 TimeUtils.formatDuration(mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP), pw);
Suprabh Shukla2324e982018-06-05 21:06:22 -07002015 pw.println();
2016
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002017 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
Christopher Tate8b98ade2018-02-09 11:13:19 -08002018 pw.print(" = "); pw.println(mLastWakeup);
2019 pw.print(" Last trigger: "); TimeUtils.formatDuration(mLastTrigger, nowELAPSED, pw);
2020 pw.print(" = "); pw.println(mLastTrigger);
Dianne Hackborna750a632015-06-16 17:18:23 -07002021 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002022
John Spurlock604a5ee2015-06-01 12:27:22 -04002023 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002024 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04002025 final TreeSet<Integer> users = new TreeSet<>();
2026 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
2027 users.add(mNextAlarmClockForUser.keyAt(i));
2028 }
2029 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
2030 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2031 }
2032 for (int user : users) {
2033 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2034 final long time = next != null ? next.getTriggerTime() : 0;
2035 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07002036 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04002037 pw.print(" pendingSend:"); pw.print(pendingSend);
2038 pw.print(" time:"); pw.print(time);
2039 if (time > 0) {
2040 pw.print(" = "); pw.print(sdf.format(new Date(time)));
2041 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
2042 }
2043 pw.println();
2044 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002045 if (mAlarmBatches.size() > 0) {
2046 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002047 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07002048 pw.println(mAlarmBatches.size());
2049 for (Batch b : mAlarmBatches) {
2050 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07002051 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002052 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002053 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002054 pw.println();
2055 pw.println(" Pending user blocked background alarms: ");
2056 boolean blocked = false;
2057 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2058 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2059 if (blockedAlarms != null && blockedAlarms.size() > 0) {
2060 blocked = true;
2061 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
2062 }
2063 }
2064 if (!blocked) {
2065 pw.println(" none");
2066 }
Suprabh Shuklac25447d2018-01-19 16:43:35 -08002067
Suprabh Shukla75edab12018-01-29 14:09:06 -08002068 pw.println(" mLastAlarmDeliveredForPackage:");
2069 for (int i = 0; i < mLastAlarmDeliveredForPackage.size(); i++) {
2070 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
2071 pw.print(" Package " + packageUser.first + ", User " + packageUser.second + ":");
2072 TimeUtils.formatDuration(mLastAlarmDeliveredForPackage.valueAt(i), nowELAPSED, pw);
2073 pw.println();
2074 }
2075 pw.println();
2076
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002077 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002078 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002079 pw.println(" Idle mode state:");
2080 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002081 if (mPendingIdleUntil != null) {
2082 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07002083 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07002084 } else {
2085 pw.println("null");
2086 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002087 pw.println(" Pending alarms:");
2088 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002089 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002090 if (mNextWakeFromIdle != null) {
2091 pw.println();
2092 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07002093 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002094 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002095
2096 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002097 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002098 if (mPendingNonWakeupAlarms.size() > 0) {
2099 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07002100 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002101 } else {
2102 pw.println("(none)");
2103 }
Dianne Hackborna750a632015-06-16 17:18:23 -07002104 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002105 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
2106 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07002107 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002108 pw.print(", max non-interactive time: ");
2109 TimeUtils.formatDuration(mNonInteractiveTime, pw);
2110 pw.println();
2111
2112 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002113 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07002114 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
2115 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
2116 pw.print(" Listener send count: "); pw.println(mListenerCount);
2117 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08002118 pw.println();
2119
Christopher Tate7f2a0352015-12-08 10:24:33 -08002120 if (mInFlight.size() > 0) {
2121 pw.println("Outstanding deliveries:");
2122 for (int i = 0; i < mInFlight.size(); i++) {
2123 pw.print(" #"); pw.print(i); pw.print(": ");
2124 pw.println(mInFlight.get(i));
2125 }
2126 pw.println();
2127 }
2128
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002129 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07002130 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002131 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
Makoto Onukiadb50d82018-01-29 16:20:30 -08002132 pw.print(" UID ");
2133 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2134 UserHandle.formatUid(pw, uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002135 pw.print(": ");
Makoto Onukiadb50d82018-01-29 16:20:30 -08002136 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2137 TimeUtils.formatDuration(lastTime, nowELAPSED, pw);
2138
2139 final long minInterval = getWhileIdleMinIntervalLocked(uid);
2140 pw.print(" Next allowed:");
2141 TimeUtils.formatDuration(lastTime + minInterval, nowELAPSED, pw);
2142 pw.print(" (");
2143 TimeUtils.formatDuration(minInterval, 0, pw);
2144 pw.print(")");
2145
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002146 pw.println();
2147 }
2148 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08002149
2150 pw.print(" mUseAllowWhileIdleShortTime: [");
2151 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2152 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
2153 UserHandle.formatUid(pw, mUseAllowWhileIdleShortTime.keyAt(i));
2154 pw.print(" ");
2155 }
2156 }
2157 pw.println("]");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002158 pw.println();
2159
Dianne Hackborn81038902012-11-26 17:04:09 -08002160 if (mLog.dump(pw, " Recent problems", " ")) {
2161 pw.println();
2162 }
2163
2164 final FilterStats[] topFilters = new FilterStats[10];
2165 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2166 @Override
2167 public int compare(FilterStats lhs, FilterStats rhs) {
2168 if (lhs.aggregateTime < rhs.aggregateTime) {
2169 return 1;
2170 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2171 return -1;
2172 }
2173 return 0;
2174 }
2175 };
2176 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07002177 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002178 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2179 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2180 for (int ip=0; ip<uidStats.size(); ip++) {
2181 BroadcastStats bs = uidStats.valueAt(ip);
2182 for (int is=0; is<bs.filterStats.size(); is++) {
2183 FilterStats fs = bs.filterStats.valueAt(is);
2184 int pos = len > 0
2185 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2186 if (pos < 0) {
2187 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08002188 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002189 if (pos < topFilters.length) {
2190 int copylen = topFilters.length - pos - 1;
2191 if (copylen > 0) {
2192 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2193 }
2194 topFilters[pos] = fs;
2195 if (len < topFilters.length) {
2196 len++;
2197 }
Dianne Hackborn81038902012-11-26 17:04:09 -08002198 }
2199 }
2200 }
2201 }
2202 if (len > 0) {
2203 pw.println(" Top Alarms:");
2204 for (int i=0; i<len; i++) {
2205 FilterStats fs = topFilters[i];
2206 pw.print(" ");
2207 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2208 TimeUtils.formatDuration(fs.aggregateTime, pw);
2209 pw.print(" running, "); pw.print(fs.numWakeup);
2210 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002211 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
2212 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08002213 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002214 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08002215 pw.println();
2216 }
2217 }
2218
2219 pw.println(" ");
2220 pw.println(" Alarm Stats:");
2221 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002222 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
2223 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2224 for (int ip=0; ip<uidStats.size(); ip++) {
2225 BroadcastStats bs = uidStats.valueAt(ip);
2226 pw.print(" ");
2227 if (bs.nesting > 0) pw.print("*ACTIVE* ");
2228 UserHandle.formatUid(pw, bs.mUid);
2229 pw.print(":");
2230 pw.print(bs.mPackageName);
2231 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
2232 pw.print(" running, "); pw.print(bs.numWakeup);
2233 pw.println(" wakeups:");
2234 tmpFilters.clear();
2235 for (int is=0; is<bs.filterStats.size(); is++) {
2236 tmpFilters.add(bs.filterStats.valueAt(is));
2237 }
2238 Collections.sort(tmpFilters, comparator);
2239 for (int i=0; i<tmpFilters.size(); i++) {
2240 FilterStats fs = tmpFilters.get(i);
2241 pw.print(" ");
2242 if (fs.nesting > 0) pw.print("*ACTIVE* ");
2243 TimeUtils.formatDuration(fs.aggregateTime, pw);
2244 pw.print(" "); pw.print(fs.numWakeup);
2245 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002246 pw.print(" alarms, last ");
2247 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
2248 pw.println(":");
2249 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002250 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002251 pw.println();
2252 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002253 }
2254 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08002255 pw.println();
2256 mStatLogger.dump(pw, " ");
Christopher Tate18a75f12013-07-01 18:18:59 -07002257
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002258 if (RECORD_DEVICE_IDLE_ALARMS) {
2259 pw.println();
2260 pw.println(" Allow while idle dispatches:");
2261 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2262 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2263 pw.print(" ");
2264 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
2265 pw.print(": ");
2266 UserHandle.formatUid(pw, ent.uid);
2267 pw.print(":");
2268 pw.println(ent.pkg);
2269 if (ent.op != null) {
2270 pw.print(" ");
2271 pw.print(ent.op);
2272 pw.print(" / ");
2273 pw.print(ent.tag);
2274 if (ent.argRealtime != 0) {
2275 pw.print(" (");
2276 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
2277 pw.print(")");
2278 }
2279 pw.println();
2280 }
2281 }
2282 }
2283
Christopher Tate18a75f12013-07-01 18:18:59 -07002284 if (WAKEUP_STATS) {
2285 pw.println();
2286 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07002287 long last = -1;
2288 for (WakeupEvent event : mRecentWakeups) {
2289 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
2290 pw.print('|');
2291 if (last < 0) {
2292 pw.print('0');
2293 } else {
2294 pw.print(event.when - last);
2295 }
2296 last = event.when;
2297 pw.print('|'); pw.print(event.uid);
2298 pw.print('|'); pw.print(event.action);
2299 pw.println();
2300 }
2301 pw.println();
2302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002303 }
2304 }
2305
Kweku Adams61e03292017-10-19 14:27:12 -07002306 void dumpProto(FileDescriptor fd) {
2307 final ProtoOutputStream proto = new ProtoOutputStream(fd);
2308
2309 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002310 final long nowRTC = mInjector.getCurrentTimeMillis();
2311 final long nowElapsed = mInjector.getElapsedRealtime();
Yi Jin2b30f322018-02-20 15:41:47 -08002312 proto.write(AlarmManagerServiceDumpProto.CURRENT_TIME, nowRTC);
2313 proto.write(AlarmManagerServiceDumpProto.ELAPSED_REALTIME, nowElapsed);
2314 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_CLOCK_TIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002315 mLastTimeChangeClockTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002316 proto.write(AlarmManagerServiceDumpProto.LAST_TIME_CHANGE_REALTIME,
Kweku Adams61e03292017-10-19 14:27:12 -07002317 mLastTimeChangeRealtime);
2318
Yi Jin2b30f322018-02-20 15:41:47 -08002319 mConstants.dumpProto(proto, AlarmManagerServiceDumpProto.SETTINGS);
Kweku Adams61e03292017-10-19 14:27:12 -07002320
Makoto Onukie4918212018-02-06 11:30:15 -08002321 if (mAppStateTracker != null) {
2322 mAppStateTracker.dumpProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002323 AlarmManagerServiceDumpProto.FORCE_APP_STANDBY_TRACKER);
Makoto Onukie4918212018-02-06 11:30:15 -08002324 }
Kweku Adams61e03292017-10-19 14:27:12 -07002325
Yi Jin2b30f322018-02-20 15:41:47 -08002326 proto.write(AlarmManagerServiceDumpProto.IS_INTERACTIVE, mInteractive);
Kweku Adams61e03292017-10-19 14:27:12 -07002327 if (!mInteractive) {
2328 // Durations
Yi Jin2b30f322018-02-20 15:41:47 -08002329 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_NON_INTERACTIVE_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002330 nowElapsed - mNonInteractiveStartTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002331 proto.write(AlarmManagerServiceDumpProto.MAX_WAKEUP_DELAY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002332 currentNonWakeupFuzzLocked(nowElapsed));
Yi Jin2b30f322018-02-20 15:41:47 -08002333 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_DISPATCH_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002334 nowElapsed - mLastAlarmDeliveryTime);
Yi Jin2b30f322018-02-20 15:41:47 -08002335 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002336 nowElapsed - mNextNonWakeupDeliveryTime);
2337 }
2338
Yi Jin2b30f322018-02-20 15:41:47 -08002339 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002340 mNextNonWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002341 proto.write(AlarmManagerServiceDumpProto.TIME_UNTIL_NEXT_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002342 mNextWakeup - nowElapsed);
Yi Jin2b30f322018-02-20 15:41:47 -08002343 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002344 nowElapsed - mLastWakeup);
Yi Jin2b30f322018-02-20 15:41:47 -08002345 proto.write(AlarmManagerServiceDumpProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002346 nowElapsed - mNextWakeUpSetAt);
Yi Jin2b30f322018-02-20 15:41:47 -08002347 proto.write(AlarmManagerServiceDumpProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07002348
2349 final TreeSet<Integer> users = new TreeSet<>();
2350 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2351 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2352 users.add(mNextAlarmClockForUser.keyAt(i));
2353 }
2354 final int pendingSendNextAlarmClockChangedForUserSize =
2355 mPendingSendNextAlarmClockChangedForUser.size();
2356 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2357 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2358 }
2359 for (int user : users) {
2360 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2361 final long time = next != null ? next.getTriggerTime() : 0;
2362 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Yi Jin2b30f322018-02-20 15:41:47 -08002363 final long aToken = proto.start(AlarmManagerServiceDumpProto.NEXT_ALARM_CLOCK_METADATA);
Kweku Adams61e03292017-10-19 14:27:12 -07002364 proto.write(AlarmClockMetadataProto.USER, user);
2365 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2366 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2367 proto.end(aToken);
2368 }
2369 for (Batch b : mAlarmBatches) {
Yi Jin2b30f322018-02-20 15:41:47 -08002370 b.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_ALARM_BATCHES,
Kweku Adams61e03292017-10-19 14:27:12 -07002371 nowElapsed, nowRTC);
2372 }
2373 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2374 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2375 if (blockedAlarms != null) {
2376 for (Alarm a : blockedAlarms) {
2377 a.writeToProto(proto,
Yi Jin2b30f322018-02-20 15:41:47 -08002378 AlarmManagerServiceDumpProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002379 nowElapsed, nowRTC);
2380 }
2381 }
2382 }
2383 if (mPendingIdleUntil != null) {
2384 mPendingIdleUntil.writeToProto(
Yi Jin2b30f322018-02-20 15:41:47 -08002385 proto, AlarmManagerServiceDumpProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
Kweku Adams61e03292017-10-19 14:27:12 -07002386 }
2387 for (Alarm a : mPendingWhileIdleAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002388 a.writeToProto(proto, AlarmManagerServiceDumpProto.PENDING_WHILE_IDLE_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002389 nowElapsed, nowRTC);
2390 }
2391 if (mNextWakeFromIdle != null) {
Yi Jin2b30f322018-02-20 15:41:47 -08002392 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceDumpProto.NEXT_WAKE_FROM_IDLE,
Kweku Adams61e03292017-10-19 14:27:12 -07002393 nowElapsed, nowRTC);
2394 }
2395
2396 for (Alarm a : mPendingNonWakeupAlarms) {
Yi Jin2b30f322018-02-20 15:41:47 -08002397 a.writeToProto(proto, AlarmManagerServiceDumpProto.PAST_DUE_NON_WAKEUP_ALARMS,
Kweku Adams61e03292017-10-19 14:27:12 -07002398 nowElapsed, nowRTC);
2399 }
2400
Yi Jin2b30f322018-02-20 15:41:47 -08002401 proto.write(AlarmManagerServiceDumpProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2402 proto.write(AlarmManagerServiceDumpProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2403 proto.write(AlarmManagerServiceDumpProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2404 proto.write(AlarmManagerServiceDumpProto.MAX_NON_INTERACTIVE_DURATION_MS,
Kweku Adams61e03292017-10-19 14:27:12 -07002405 mNonInteractiveTime);
2406
Yi Jin2b30f322018-02-20 15:41:47 -08002407 proto.write(AlarmManagerServiceDumpProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2408 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2409 proto.write(AlarmManagerServiceDumpProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2410 proto.write(AlarmManagerServiceDumpProto.LISTENER_SEND_COUNT, mListenerCount);
2411 proto.write(AlarmManagerServiceDumpProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
Kweku Adams61e03292017-10-19 14:27:12 -07002412
2413 for (InFlight f : mInFlight) {
Yi Jin2b30f322018-02-20 15:41:47 -08002414 f.writeToProto(proto, AlarmManagerServiceDumpProto.OUTSTANDING_DELIVERIES);
Kweku Adams61e03292017-10-19 14:27:12 -07002415 }
2416
Kweku Adams61e03292017-10-19 14:27:12 -07002417 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2418 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002419 AlarmManagerServiceDumpProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
Makoto Onukiadb50d82018-01-29 16:20:30 -08002420 final int uid = mLastAllowWhileIdleDispatch.keyAt(i);
2421 final long lastTime = mLastAllowWhileIdleDispatch.valueAt(i);
2422
Yi Jin2b30f322018-02-20 15:41:47 -08002423 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.UID, uid);
2424 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.TIME_MS, lastTime);
2425 proto.write(AlarmManagerServiceDumpProto.LastAllowWhileIdleDispatch.NEXT_ALLOWED_MS,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002426 lastTime + getWhileIdleMinIntervalLocked(uid));
Kweku Adams61e03292017-10-19 14:27:12 -07002427 proto.end(token);
2428 }
2429
Makoto Onukiadb50d82018-01-29 16:20:30 -08002430 for (int i = 0; i < mUseAllowWhileIdleShortTime.size(); i++) {
2431 if (mUseAllowWhileIdleShortTime.valueAt(i)) {
Yi Jin2b30f322018-02-20 15:41:47 -08002432 proto.write(AlarmManagerServiceDumpProto.USE_ALLOW_WHILE_IDLE_SHORT_TIME,
Makoto Onukiadb50d82018-01-29 16:20:30 -08002433 mUseAllowWhileIdleShortTime.keyAt(i));
2434 }
2435 }
2436
Yi Jin2b30f322018-02-20 15:41:47 -08002437 mLog.writeToProto(proto, AlarmManagerServiceDumpProto.RECENT_PROBLEMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002438
2439 final FilterStats[] topFilters = new FilterStats[10];
2440 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2441 @Override
2442 public int compare(FilterStats lhs, FilterStats rhs) {
2443 if (lhs.aggregateTime < rhs.aggregateTime) {
2444 return 1;
2445 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2446 return -1;
2447 }
2448 return 0;
2449 }
2450 };
2451 int len = 0;
2452 // Get the top 10 FilterStats, ordered by aggregateTime.
2453 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2454 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2455 for (int ip = 0; ip < uidStats.size(); ++ip) {
2456 BroadcastStats bs = uidStats.valueAt(ip);
2457 for (int is = 0; is < bs.filterStats.size(); ++is) {
2458 FilterStats fs = bs.filterStats.valueAt(is);
2459 int pos = len > 0
2460 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2461 if (pos < 0) {
2462 pos = -pos - 1;
2463 }
2464 if (pos < topFilters.length) {
2465 int copylen = topFilters.length - pos - 1;
2466 if (copylen > 0) {
2467 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2468 }
2469 topFilters[pos] = fs;
2470 if (len < topFilters.length) {
2471 len++;
2472 }
2473 }
2474 }
2475 }
2476 }
2477 for (int i = 0; i < len; ++i) {
Yi Jin2b30f322018-02-20 15:41:47 -08002478 final long token = proto.start(AlarmManagerServiceDumpProto.TOP_ALARMS);
Kweku Adams61e03292017-10-19 14:27:12 -07002479 FilterStats fs = topFilters[i];
2480
Yi Jin2b30f322018-02-20 15:41:47 -08002481 proto.write(AlarmManagerServiceDumpProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2482 proto.write(AlarmManagerServiceDumpProto.TopAlarm.PACKAGE_NAME,
Kweku Adams61e03292017-10-19 14:27:12 -07002483 fs.mBroadcastStats.mPackageName);
Yi Jin2b30f322018-02-20 15:41:47 -08002484 fs.writeToProto(proto, AlarmManagerServiceDumpProto.TopAlarm.FILTER);
Kweku Adams61e03292017-10-19 14:27:12 -07002485
2486 proto.end(token);
2487 }
2488
2489 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2490 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2491 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2492 for (int ip = 0; ip < uidStats.size(); ++ip) {
Yi Jin2b30f322018-02-20 15:41:47 -08002493 final long token = proto.start(AlarmManagerServiceDumpProto.ALARM_STATS);
Kweku Adams61e03292017-10-19 14:27:12 -07002494
2495 BroadcastStats bs = uidStats.valueAt(ip);
Yi Jin2b30f322018-02-20 15:41:47 -08002496 bs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.BROADCAST);
Kweku Adams61e03292017-10-19 14:27:12 -07002497
2498 // uidStats is an ArrayMap, which we can't sort.
2499 tmpFilters.clear();
2500 for (int is = 0; is < bs.filterStats.size(); ++is) {
2501 tmpFilters.add(bs.filterStats.valueAt(is));
2502 }
2503 Collections.sort(tmpFilters, comparator);
2504 for (FilterStats fs : tmpFilters) {
Yi Jin2b30f322018-02-20 15:41:47 -08002505 fs.writeToProto(proto, AlarmManagerServiceDumpProto.AlarmStat.FILTERS);
Kweku Adams61e03292017-10-19 14:27:12 -07002506 }
2507
2508 proto.end(token);
2509 }
2510 }
2511
2512 if (RECORD_DEVICE_IDLE_ALARMS) {
2513 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2514 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2515 final long token = proto.start(
Yi Jin2b30f322018-02-20 15:41:47 -08002516 AlarmManagerServiceDumpProto.ALLOW_WHILE_IDLE_DISPATCHES);
Kweku Adams61e03292017-10-19 14:27:12 -07002517
2518 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2519 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2520 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2521 proto.write(IdleDispatchEntryProto.OP, ent.op);
2522 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2523 ent.elapsedRealtime);
2524 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2525
2526 proto.end(token);
2527 }
2528 }
2529
2530 if (WAKEUP_STATS) {
2531 for (WakeupEvent event : mRecentWakeups) {
Yi Jin2b30f322018-02-20 15:41:47 -08002532 final long token = proto.start(AlarmManagerServiceDumpProto.RECENT_WAKEUP_HISTORY);
Kweku Adams61e03292017-10-19 14:27:12 -07002533 proto.write(WakeupEventProto.UID, event.uid);
2534 proto.write(WakeupEventProto.ACTION, event.action);
2535 proto.write(WakeupEventProto.WHEN, event.when);
2536 proto.end(token);
2537 }
2538 }
2539 }
2540
2541 proto.flush();
2542 }
2543
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002544 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002545 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2546 PrintWriter pw = new PrintWriter(bs);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002547 final long nowRTC = mInjector.getCurrentTimeMillis();
2548 final long nowELAPSED = mInjector.getElapsedRealtime();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002549 final int NZ = mAlarmBatches.size();
2550 for (int iz = 0; iz < NZ; iz++) {
2551 Batch bz = mAlarmBatches.get(iz);
2552 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002553 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002554 pw.flush();
2555 Slog.v(TAG, bs.toString());
2556 bs.reset();
2557 }
2558 }
2559
2560 private boolean validateConsistencyLocked() {
2561 if (DEBUG_VALIDATE) {
2562 long lastTime = Long.MIN_VALUE;
2563 final int N = mAlarmBatches.size();
2564 for (int i = 0; i < N; i++) {
2565 Batch b = mAlarmBatches.get(i);
2566 if (b.start >= lastTime) {
2567 // duplicate start times are okay because of standalone batches
2568 lastTime = b.start;
2569 } else {
2570 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002571 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2572 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002573 return false;
2574 }
2575 }
2576 }
2577 return true;
2578 }
2579
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002580 private Batch findFirstWakeupBatchLocked() {
2581 final int N = mAlarmBatches.size();
2582 for (int i = 0; i < N; i++) {
2583 Batch b = mAlarmBatches.get(i);
2584 if (b.hasWakeups()) {
2585 return b;
2586 }
2587 }
2588 return null;
2589 }
2590
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002591 long getNextWakeFromIdleTimeImpl() {
2592 synchronized (mLock) {
2593 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2594 }
2595 }
2596
2597 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002598 synchronized (mLock) {
2599 return mNextAlarmClockForUser.get(userId);
2600 }
2601 }
2602
2603 /**
2604 * Recomputes the next alarm clock for all users.
2605 */
2606 private void updateNextAlarmClockLocked() {
2607 if (!mNextAlarmClockMayChange) {
2608 return;
2609 }
2610 mNextAlarmClockMayChange = false;
2611
Jose Lima235510e2014-08-13 12:50:01 -07002612 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002613 nextForUser.clear();
2614
2615 final int N = mAlarmBatches.size();
2616 for (int i = 0; i < N; i++) {
2617 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2618 final int M = alarms.size();
2619
2620 for (int j = 0; j < M; j++) {
2621 Alarm a = alarms.get(j);
2622 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002623 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002624 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002625
2626 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002627 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002628 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002629 " for user " + userId);
2630 }
2631
2632 // Alarms and batches are sorted by time, no need to compare times here.
2633 if (nextForUser.get(userId) == null) {
2634 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002635 } else if (a.alarmClock.equals(current)
2636 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2637 // same/earlier time and it's the one we cited before, so stick with it
2638 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002639 }
2640 }
2641 }
2642 }
2643
2644 // Update mNextAlarmForUser with new values.
2645 final int NN = nextForUser.size();
2646 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002647 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002648 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002649 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002650 if (!newAlarm.equals(currentAlarm)) {
2651 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2652 }
2653 }
2654
2655 // Remove users without any alarm clocks scheduled.
2656 final int NNN = mNextAlarmClockForUser.size();
2657 for (int i = NNN - 1; i >= 0; i--) {
2658 int userId = mNextAlarmClockForUser.keyAt(i);
2659 if (nextForUser.get(userId) == null) {
2660 updateNextAlarmInfoForUserLocked(userId, null);
2661 }
2662 }
2663 }
2664
Jose Lima235510e2014-08-13 12:50:01 -07002665 private void updateNextAlarmInfoForUserLocked(int userId,
2666 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002667 if (alarmClock != null) {
2668 if (DEBUG_ALARM_CLOCK) {
2669 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002670 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002671 }
2672 mNextAlarmClockForUser.put(userId, alarmClock);
2673 } else {
2674 if (DEBUG_ALARM_CLOCK) {
2675 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2676 }
2677 mNextAlarmClockForUser.remove(userId);
2678 }
2679
2680 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2681 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2682 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2683 }
2684
2685 /**
2686 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2687 * for which alarm clocks have changed since the last call to this.
2688 *
2689 * Do not call with a lock held. Only call from mHandler's thread.
2690 *
2691 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2692 */
2693 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002694 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002695 pendingUsers.clear();
2696
2697 synchronized (mLock) {
2698 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2699 for (int i = 0; i < N; i++) {
2700 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2701 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2702 }
2703 mPendingSendNextAlarmClockChangedForUser.clear();
2704 }
2705
2706 final int N = pendingUsers.size();
2707 for (int i = 0; i < N; i++) {
2708 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002709 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002710 Settings.System.putStringForUser(getContext().getContentResolver(),
2711 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002712 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002713 userId);
2714
2715 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2716 new UserHandle(userId));
2717 }
2718 }
2719
2720 /**
2721 * Formats an alarm like platform/packages/apps/DeskClock used to.
2722 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002723 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2724 int userId) {
2725 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002726 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2727 return (info == null) ? "" :
2728 DateFormat.format(pattern, info.getTriggerTime()).toString();
2729 }
2730
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002731 /**
2732 * If the last time AlarmThread woke up precedes any due wakeup or non-wakeup alarm that we set
2733 * by more than half a minute, log a wtf.
2734 */
2735 private void validateLastAlarmExpiredLocked(long nowElapsed) {
2736 final StringBuilder errorMsg = new StringBuilder();
2737 boolean stuck = false;
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002738 if (mNextNonWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextNonWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002739 stuck = true;
2740 errorMsg.append("[mNextNonWakeup=");
2741 TimeUtils.formatDuration(mNextNonWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002742 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002743 TimeUtils.formatDuration(mNextNonWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002744 errorMsg.append(", mLastWakeup=");
2745 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002746 errorMsg.append(", timerfd_gettime=" + mInjector.getNextAlarm(ELAPSED_REALTIME));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002747 errorMsg.append("];");
2748 }
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002749 if (mNextWakeup < (nowElapsed - 10_000) && mLastWakeup < mNextWakeup) {
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002750 stuck = true;
2751 errorMsg.append("[mNextWakeup=");
2752 TimeUtils.formatDuration(mNextWakeup - nowElapsed, errorMsg);
Suprabh Shuklab50f43f2018-06-27 16:40:55 -07002753 errorMsg.append(" set at ");
Suprabh Shukla673d34b2018-07-03 14:00:29 -07002754 TimeUtils.formatDuration(mNextWakeUpSetAt - nowElapsed, errorMsg);
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002755 errorMsg.append(", mLastWakeup=");
2756 TimeUtils.formatDuration(mLastWakeup - nowElapsed, errorMsg);
2757 errorMsg.append(", timerfd_gettime="
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002758 + mInjector.getNextAlarm(ELAPSED_REALTIME_WAKEUP));
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002759 errorMsg.append("];");
2760 }
2761 if (stuck) {
2762 Slog.wtf(TAG, "Alarm delivery stuck: " + errorMsg.toString());
2763 }
2764 }
2765
Adam Lesinski182f73f2013-12-05 16:48:06 -08002766 void rescheduleKernelAlarmsLocked() {
2767 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2768 // prior to that which contains no wakeups, we schedule that as well.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002769 final long nowElapsed = mInjector.getElapsedRealtime();
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002770 validateLastAlarmExpiredLocked(nowElapsed);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002771 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002772 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002773 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002774 final Batch firstBatch = mAlarmBatches.get(0);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002775 if (firstWakeup != null) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002776 mNextWakeup = firstWakeup.start;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002777 mNextWakeUpSetAt = nowElapsed;
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002778 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002779 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002780 if (firstBatch != firstWakeup) {
2781 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002782 }
2783 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002784 if (mPendingNonWakeupAlarms.size() > 0) {
2785 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2786 nextNonWakeup = mNextNonWakeupDeliveryTime;
2787 }
2788 }
Suprabh Shukla2fa95452018-02-12 12:53:23 -08002789 if (nextNonWakeup != 0) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002790 mNextNonWakeup = nextNonWakeup;
Suprabh Shukla0e4510d2018-06-20 17:28:26 -07002791 mNextNonWakeUpSetAt = nowElapsed;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002792 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2793 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002794 }
2795
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07002796 void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002797 if (operation == null && directReceiver == null) {
2798 if (localLOGV) {
2799 Slog.w(TAG, "requested remove() of null operation",
2800 new RuntimeException("here"));
2801 }
2802 return;
2803 }
2804
Adam Lesinski182f73f2013-12-05 16:48:06 -08002805 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002806 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002807 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2808 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002809 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002810 if (b.size() == 0) {
2811 mAlarmBatches.remove(i);
2812 }
2813 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002814 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002815 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002816 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2817 mPendingWhileIdleAlarms.remove(i);
2818 }
2819 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002820 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2821 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2822 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2823 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2824 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2825 alarmsForUid.remove(j);
2826 }
2827 }
2828 if (alarmsForUid.size() == 0) {
2829 mPendingBackgroundAlarms.removeAt(i);
2830 }
2831 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002832 if (didRemove) {
2833 if (DEBUG_BATCH) {
2834 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2835 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002836 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002837 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002838 mPendingIdleUntil = null;
2839 restorePending = true;
2840 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002841 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002842 mNextWakeFromIdle = null;
2843 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002844 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002845 if (restorePending) {
2846 restorePendingWhileIdleAlarmsLocked();
2847 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002848 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002849 }
2850 }
2851
Christopher Tate1d99c392017-12-07 16:54:04 -08002852 void removeLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002853 if (uid == Process.SYSTEM_UID) {
2854 Slog.wtf(TAG, "removeLocked: Shouldn't for UID=" + uid);
2855 return;
2856 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002857 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002858 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002859 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2860 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002861 didRemove |= b.remove(whichAlarms);
2862 if (b.size() == 0) {
2863 mAlarmBatches.remove(i);
2864 }
2865 }
2866 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2867 final Alarm a = mPendingWhileIdleAlarms.get(i);
2868 if (a.uid == uid) {
2869 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2870 mPendingWhileIdleAlarms.remove(i);
2871 }
2872 }
2873 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2874 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2875 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2876 if (alarmsForUid.get(j).uid == uid) {
2877 alarmsForUid.remove(j);
2878 }
2879 }
2880 if (alarmsForUid.size() == 0) {
2881 mPendingBackgroundAlarms.removeAt(i);
2882 }
2883 }
2884 if (didRemove) {
2885 if (DEBUG_BATCH) {
2886 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2887 }
2888 rebatchAllAlarmsLocked(true);
2889 rescheduleKernelAlarmsLocked();
2890 updateNextAlarmClockLocked();
2891 }
2892 }
2893
2894 void removeLocked(final String packageName) {
2895 if (packageName == null) {
2896 if (localLOGV) {
2897 Slog.w(TAG, "requested remove() of null packageName",
2898 new RuntimeException("here"));
2899 }
2900 return;
2901 }
2902
2903 boolean didRemove = false;
2904 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
Makoto Onuki5d93b832018-01-10 16:12:39 -08002905 final boolean oldHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
Christopher Tate1d99c392017-12-07 16:54:04 -08002906 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2907 Batch b = mAlarmBatches.get(i);
2908 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002909 if (b.size() == 0) {
2910 mAlarmBatches.remove(i);
2911 }
2912 }
Makoto Onuki5d93b832018-01-10 16:12:39 -08002913 final boolean newHasTick = haveBatchesTimeTickAlarm(mAlarmBatches);
2914 if (oldHasTick != newHasTick) {
2915 Slog.wtf(TAG, "removeLocked: hasTick changed from " + oldHasTick + " to " + newHasTick);
2916 }
2917
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002918 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002919 final Alarm a = mPendingWhileIdleAlarms.get(i);
2920 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002921 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2922 mPendingWhileIdleAlarms.remove(i);
2923 }
2924 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002925 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2926 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2927 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2928 if (alarmsForUid.get(j).matches(packageName)) {
2929 alarmsForUid.remove(j);
2930 }
2931 }
2932 if (alarmsForUid.size() == 0) {
2933 mPendingBackgroundAlarms.removeAt(i);
2934 }
2935 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002936 if (didRemove) {
2937 if (DEBUG_BATCH) {
2938 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2939 }
2940 rebatchAllAlarmsLocked(true);
2941 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002942 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002943 }
2944 }
2945
Christopher Tate1d99c392017-12-07 16:54:04 -08002946 void removeForStoppedLocked(final int uid) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002947 if (uid == Process.SYSTEM_UID) {
2948 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for UID=" + uid);
2949 return;
2950 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002951 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002952 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2953 try {
2954 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2955 uid, a.packageName)) {
2956 return true;
2957 }
2958 } catch (RemoteException e) { /* fall through */}
2959 return false;
2960 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002961 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2962 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002963 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002964 if (b.size() == 0) {
2965 mAlarmBatches.remove(i);
2966 }
2967 }
2968 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2969 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002970 if (a.uid == uid) {
2971 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2972 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002973 }
2974 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002975 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2976 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2977 mPendingBackgroundAlarms.removeAt(i);
2978 }
2979 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002980 if (didRemove) {
2981 if (DEBUG_BATCH) {
2982 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2983 }
2984 rebatchAllAlarmsLocked(true);
2985 rescheduleKernelAlarmsLocked();
2986 updateNextAlarmClockLocked();
2987 }
2988 }
2989
Adam Lesinski182f73f2013-12-05 16:48:06 -08002990 void removeUserLocked(int userHandle) {
Makoto Onuki5d93b832018-01-10 16:12:39 -08002991 if (userHandle == UserHandle.USER_SYSTEM) {
2992 Slog.wtf(TAG, "removeForStoppedLocked: Shouldn't for user=" + userHandle);
2993 return;
2994 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002995 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002996 final Predicate<Alarm> whichAlarms =
2997 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002998 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2999 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08003000 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003001 if (b.size() == 0) {
3002 mAlarmBatches.remove(i);
3003 }
3004 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003005 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003006 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003007 == userHandle) {
3008 // Don't set didRemove, since this doesn't impact the scheduled alarms.
3009 mPendingWhileIdleAlarms.remove(i);
3010 }
3011 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003012 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
3013 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
3014 mPendingBackgroundAlarms.removeAt(i);
3015 }
3016 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003017 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
3018 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
3019 mLastAllowWhileIdleDispatch.removeAt(i);
3020 }
3021 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003022
3023 if (didRemove) {
3024 if (DEBUG_BATCH) {
3025 Slog.v(TAG, "remove(user) changed bounds; rebatching");
3026 }
3027 rebatchAllAlarmsLocked(true);
3028 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02003029 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08003030 }
3031 }
3032
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003033 void interactiveStateChangedLocked(boolean interactive) {
3034 if (mInteractive != interactive) {
3035 mInteractive = interactive;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003036 final long nowELAPSED = mInjector.getElapsedRealtime();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003037 if (interactive) {
3038 if (mPendingNonWakeupAlarms.size() > 0) {
3039 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3040 mTotalDelayTime += thisDelayTime;
3041 if (mMaxDelayTime < thisDelayTime) {
3042 mMaxDelayTime = thisDelayTime;
3043 }
3044 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
3045 mPendingNonWakeupAlarms.clear();
3046 }
3047 if (mNonInteractiveStartTime > 0) {
3048 long dur = nowELAPSED - mNonInteractiveStartTime;
3049 if (dur > mNonInteractiveTime) {
3050 mNonInteractiveTime = dur;
3051 }
3052 }
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003053 // And send a TIME_TICK right now, since it is important to get the UI updated.
3054 mHandler.post(() ->
3055 getContext().sendBroadcastAsUser(mTimeTickIntent, UserHandle.ALL));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003056 } else {
3057 mNonInteractiveStartTime = nowELAPSED;
3058 }
3059 }
3060 }
3061
Adam Lesinski182f73f2013-12-05 16:48:06 -08003062 boolean lookForPackageLocked(String packageName) {
3063 for (int i = 0; i < mAlarmBatches.size(); i++) {
3064 Batch b = mAlarmBatches.get(i);
3065 if (b.hasPackage(packageName)) {
3066 return true;
3067 }
3068 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003069 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003070 final Alarm a = mPendingWhileIdleAlarms.get(i);
3071 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003072 return true;
3073 }
3074 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08003075 return false;
3076 }
3077
3078 private void setLocked(int type, long when) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003079 if (mInjector.isAlarmDriverPresent()) {
3080 mInjector.setAlarm(type, when);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003081 } else {
3082 Message msg = Message.obtain();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003083 msg.what = AlarmHandler.ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07003084
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003085 mHandler.removeMessages(msg.what);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003086 mHandler.sendMessageAtTime(msg, when);
3087 }
3088 }
3089
Dianne Hackborn043fcd92010-10-06 14:27:34 -07003090 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07003091 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003092 for (int i=list.size()-1; i>=0; i--) {
3093 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003094 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3095 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003096 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003097 }
3098 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003099
3100 private static final String labelForType(int type) {
3101 switch (type) {
3102 case RTC: return "RTC";
3103 case RTC_WAKEUP : return "RTC_WAKEUP";
3104 case ELAPSED_REALTIME : return "ELAPSED";
3105 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07003106 }
3107 return "--unknown--";
3108 }
3109
3110 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003111 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003112 for (int i=list.size()-1; i>=0; i--) {
3113 Alarm a = list.get(i);
3114 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003115 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
3116 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07003117 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003118 }
3119 }
3120
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003121 private boolean isBackgroundRestricted(Alarm alarm) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003122 boolean exemptOnBatterySaver = (alarm.flags & FLAG_ALLOW_WHILE_IDLE) != 0;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003123 if (alarm.alarmClock != null) {
Christopher Tateda3dc922018-05-09 13:49:41 -07003124 // Don't defer alarm clocks
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003125 return false;
3126 }
Christopher Tateda3dc922018-05-09 13:49:41 -07003127 if (alarm.operation != null) {
3128 if (alarm.operation.isActivity()) {
3129 // Don't defer starting actual UI
3130 return false;
3131 }
3132 if (alarm.operation.isForegroundService()) {
3133 // FG service alarms are nearly as important; consult AST policy
3134 exemptOnBatterySaver = true;
3135 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003136 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003137 final String sourcePackage = alarm.sourcePackage;
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003138 final int sourceUid = alarm.creatorUid;
Makoto Onukie4918212018-02-06 11:30:15 -08003139 return (mAppStateTracker != null) &&
Christopher Tateda3dc922018-05-09 13:49:41 -07003140 mAppStateTracker.areAlarmsRestricted(sourceUid, sourcePackage,
3141 exemptOnBatterySaver);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003142 }
3143
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003144 private static native long init();
3145 private static native void close(long nativeData);
3146 private static native int set(long nativeData, int type, long seconds, long nanoseconds);
3147 private static native int waitForAlarm(long nativeData);
3148 private static native int setKernelTime(long nativeData, long millis);
3149 private static native int setKernelTimezone(long nativeData, int minuteswest);
3150 private static native long getNextAlarm(long nativeData, int type);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003151
Makoto Onukiadb50d82018-01-29 16:20:30 -08003152 private long getWhileIdleMinIntervalLocked(int uid) {
3153 final boolean dozing = mPendingIdleUntil != null;
Makoto Onukie4918212018-02-06 11:30:15 -08003154 final boolean ebs = (mAppStateTracker != null)
3155 && mAppStateTracker.isForceAllAppsStandbyEnabled();
Makoto Onukiadb50d82018-01-29 16:20:30 -08003156 if (!dozing && !ebs) {
3157 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3158 }
3159 if (dozing) {
3160 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3161 }
3162 if (mUseAllowWhileIdleShortTime.get(uid)) {
3163 // if the last allow-while-idle went off while uid was fg, or the uid
3164 // recently came into fg, don't block the alarm for long.
3165 return mConstants.ALLOW_WHILE_IDLE_SHORT_TIME;
3166 }
3167 return mConstants.ALLOW_WHILE_IDLE_LONG_TIME;
3168 }
3169
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003170 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003171 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003172 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003173 // batches are temporally sorted, so we need only pull from the
3174 // start of the list until we either empty it or hit a batch
3175 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07003176 while (mAlarmBatches.size() > 0) {
3177 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003178 if (batch.start > nowELAPSED) {
3179 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003180 break;
3181 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003182
Christopher Tatee0a22b32013-07-11 14:43:13 -07003183 // We will (re)schedule some alarms now; don't let that interfere
3184 // with delivery of this current batch
3185 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07003186
Christopher Tatee0a22b32013-07-11 14:43:13 -07003187 final int N = batch.size();
3188 for (int i = 0; i < N; i++) {
3189 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003190
3191 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
3192 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
Christopher Tateddd1da142018-04-13 13:41:51 -07003193 // schedule such alarms. The first such alarm from an app is always delivered.
3194 final long lastTime = mLastAllowWhileIdleDispatch.get(alarm.creatorUid, -1);
Makoto Onukiadb50d82018-01-29 16:20:30 -08003195 final long minTime = lastTime + getWhileIdleMinIntervalLocked(alarm.creatorUid);
Christopher Tateddd1da142018-04-13 13:41:51 -07003196 if (lastTime >= 0 && nowELAPSED < minTime) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003197 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
3198 // alarm went off for this app. Reschedule the alarm to be in the
3199 // correct time period.
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003200 alarm.expectedWhenElapsed = alarm.whenElapsed = minTime;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003201 if (alarm.maxWhenElapsed < minTime) {
3202 alarm.maxWhenElapsed = minTime;
3203 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003204 alarm.expectedMaxWhenElapsed = alarm.maxWhenElapsed;
Dianne Hackbornae78bf82015-10-26 13:33:20 -07003205 if (RECORD_DEVICE_IDLE_ALARMS) {
3206 IdleDispatchEntry ent = new IdleDispatchEntry();
3207 ent.uid = alarm.uid;
3208 ent.pkg = alarm.operation.getCreatorPackage();
3209 ent.tag = alarm.operation.getTag("");
3210 ent.op = "RESCHEDULE";
3211 ent.elapsedRealtime = nowELAPSED;
3212 ent.argRealtime = lastTime;
3213 mAllowWhileIdleDispatches.add(ent);
3214 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003215 setImplLocked(alarm, true, false);
3216 continue;
3217 }
3218 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003219 if (isBackgroundRestricted(alarm)) {
3220 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
3221 if (DEBUG_BG_LIMIT) {
3222 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
3223 }
3224 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
3225 if (alarmsForUid == null) {
3226 alarmsForUid = new ArrayList<>();
3227 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
3228 }
3229 alarmsForUid.add(alarm);
3230 continue;
3231 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003232
Christopher Tatee0a22b32013-07-11 14:43:13 -07003233 alarm.count = 1;
3234 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003235 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
3236 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003237 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003238 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003239 if (mPendingIdleUntil == alarm) {
3240 mPendingIdleUntil = null;
3241 rebatchAllAlarmsLocked(false);
3242 restorePendingWhileIdleAlarmsLocked();
3243 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003244 if (mNextWakeFromIdle == alarm) {
3245 mNextWakeFromIdle = null;
3246 rebatchAllAlarmsLocked(false);
3247 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003248
3249 // Recurring alarms may have passed several alarm intervals while the
3250 // phone was asleep or off, so pass a trigger count when sending them.
3251 if (alarm.repeatInterval > 0) {
3252 // this adjustment will be zero if we're late by
3253 // less than one full repeat interval
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003254 alarm.count += (nowELAPSED - alarm.expectedWhenElapsed) / alarm.repeatInterval;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003255
3256 // Also schedule its next recurrence
3257 final long delta = alarm.count * alarm.repeatInterval;
3258 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07003259 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07003260 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07003261 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
3262 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08003263 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003264
Christopher Tate864d42e2014-12-02 11:48:53 -08003265 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003266 hasWakeup = true;
3267 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003268
3269 // We removed an alarm clock. Let the caller recompute the next alarm clock.
3270 if (alarm.alarmClock != null) {
3271 mNextAlarmClockMayChange = true;
3272 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07003273 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003275
Christopher Tate1590f1e2014-10-02 17:27:57 -07003276 // This is a new alarm delivery set; bump the sequence number to indicate that
3277 // all apps' alarm delivery classes should be recalculated.
3278 mCurrentSeq++;
3279 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003280 Collections.sort(triggerList, mAlarmDispatchComparator);
3281
3282 if (localLOGV) {
3283 for (int i=0; i<triggerList.size(); i++) {
3284 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
3285 }
3286 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003287
3288 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003290
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003291 /**
3292 * This Comparator sorts Alarms into increasing time order.
3293 */
3294 public static class IncreasingTimeOrder implements Comparator<Alarm> {
3295 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09003296 long when1 = a1.whenElapsed;
3297 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003298 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 return 1;
3300 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08003301 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003302 return -1;
3303 }
3304 return 0;
3305 }
3306 }
Kweku Adams61e03292017-10-19 14:27:12 -07003307
Makoto Onuki2206af32017-11-21 16:25:35 -08003308 @VisibleForTesting
3309 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003310 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003311 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003312 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003313 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003314 public final IAlarmListener listener;
3315 public final String listenerTag;
3316 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003317 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003318 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003319 public final AlarmManager.AlarmClockInfo alarmClock;
3320 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003321 public final int creatorUid;
3322 public final String packageName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003323 public final String sourcePackage;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003324 public int count;
3325 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07003326 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003327 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003328 public long maxWhenElapsed; // also in the elapsed time base
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003329 // Expected alarm expiry time before app standby deferring is applied.
3330 public long expectedWhenElapsed;
3331 public long expectedMaxWhenElapsed;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003332 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07003333 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003334
Christopher Tate3e04b472013-10-21 17:51:31 -07003335 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003336 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
3337 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
3338 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07003339 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003340 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003341 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
3342 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07003343 when = _when;
3344 whenElapsed = _whenElapsed;
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003345 expectedWhenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07003346 windowLength = _windowLength;
Christopher Tate22e919d2018-02-16 16:16:50 -08003347 maxWhenElapsed = expectedMaxWhenElapsed = clampPositive(_maxWhen);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003348 repeatInterval = _interval;
3349 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003350 listener = _rec;
3351 listenerTag = _listenerTag;
3352 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07003353 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003354 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02003355 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003356 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003357 packageName = _pkgName;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003358 sourcePackage = (operation != null) ? operation.getCreatorPackage() : packageName;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003359 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003360 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07003361
Christopher Tate14a7bb02015-10-01 10:24:31 -07003362 public static String makeTag(PendingIntent pi, String tag, int type) {
3363 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
3364 ? "*walarm*:" : "*alarm*:";
3365 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
3366 }
3367
3368 public WakeupEvent makeWakeupEvent(long nowRTC) {
3369 return new WakeupEvent(nowRTC, creatorUid,
3370 (operation != null)
3371 ? operation.getIntent().getAction()
3372 : ("<listener>:" + listenerTag));
3373 }
3374
3375 // Returns true if either matches
3376 public boolean matches(PendingIntent pi, IAlarmListener rec) {
3377 return (operation != null)
3378 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09003379 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07003380 }
3381
3382 public boolean matches(String packageName) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08003383 return packageName.equals(sourcePackage);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003384 }
3385
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003386 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003387 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003388 StringBuilder sb = new StringBuilder(128);
3389 sb.append("Alarm{");
3390 sb.append(Integer.toHexString(System.identityHashCode(this)));
3391 sb.append(" type ");
3392 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003393 sb.append(" when ");
3394 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003395 sb.append(" ");
Suprabh Shukla75edab12018-01-29 14:09:06 -08003396 sb.append(sourcePackage);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003397 sb.append('}');
3398 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003399 }
3400
Kweku Adams61e03292017-10-19 14:27:12 -07003401 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003402 SimpleDateFormat sdf) {
3403 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003404 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003405 pw.print(prefix); pw.print("type="); pw.print(type);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003406 pw.print(" expectedWhenElapsed="); TimeUtils.formatDuration(
3407 expectedWhenElapsed, nowELAPSED, pw);
3408 pw.print(" expectedMaxWhenElapsed="); TimeUtils.formatDuration(
3409 expectedMaxWhenElapsed, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003410 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
3411 nowELAPSED, pw);
Suprabh Shukla2fa95452018-02-12 12:53:23 -08003412 pw.print(" maxWhenElapsed="); TimeUtils.formatDuration(maxWhenElapsed,
3413 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003414 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003415 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003416 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003417 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003418 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003419 }
3420 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003421 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003422 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003423 pw.print(" count="); pw.print(count);
3424 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003425 if (alarmClock != null) {
3426 pw.print(prefix); pw.println("Alarm clock:");
3427 pw.print(prefix); pw.print(" triggerTime=");
3428 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
3429 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
3430 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07003431 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003432 if (listener != null) {
3433 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
3434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003435 }
Kweku Adams61e03292017-10-19 14:27:12 -07003436
3437 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
3438 long nowRTC) {
3439 final long token = proto.start(fieldId);
3440
3441 proto.write(AlarmProto.TAG, statsTag);
3442 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08003443 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07003444 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
3445 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
3446 proto.write(AlarmProto.COUNT, count);
3447 proto.write(AlarmProto.FLAGS, flags);
3448 if (alarmClock != null) {
3449 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
3450 }
3451 if (operation != null) {
3452 operation.writeToProto(proto, AlarmProto.OPERATION);
3453 }
3454 if (listener != null) {
3455 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3456 }
3457
3458 proto.end(token);
3459 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003460 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003461
Christopher Tatee0a22b32013-07-11 14:43:13 -07003462 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3463 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003464 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3465 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003466 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003467 break;
3468 }
3469
Christopher Tatee0a22b32013-07-11 14:43:13 -07003470 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003471 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3472 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003473 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003474 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003475 }
3476 }
3477
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003478 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3479 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3480 if (timeSinceOn < 5*60*1000) {
3481 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3482 return 2*60*1000;
3483 } else if (timeSinceOn < 30*60*1000) {
3484 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3485 return 15*60*1000;
3486 } else {
3487 // Otherwise, we will delay by at most an hour.
3488 return 60*60*1000;
3489 }
3490 }
3491
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003492 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003493 if (duration < 15*60*1000) {
3494 // If the duration until the time is less than 15 minutes, the maximum fuzz
3495 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003496 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003497 } else if (duration < 90*60*1000) {
3498 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3499 return 15*60*1000;
3500 } else {
3501 // Otherwise, we will fuzz by at most half an hour.
3502 return 30*60*1000;
3503 }
3504 }
3505
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003506 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3507 if (mInteractive) {
3508 return false;
3509 }
3510 if (mLastAlarmDeliveryTime <= 0) {
3511 return false;
3512 }
minho.choo649acab2014-12-12 16:13:55 +09003513 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003514 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3515 // and the next delivery time is in the past, then just deliver them all. This
3516 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3517 return false;
3518 }
3519 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3520 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3521 }
3522
3523 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3524 mLastAlarmDeliveryTime = nowELAPSED;
3525 for (int i=0; i<triggerList.size(); i++) {
3526 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003527 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003528 if (alarm.wakeup) {
3529 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3530 } else {
3531 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3532 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003533 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003534 if (localLOGV) {
3535 Slog.v(TAG, "sending alarm " + alarm);
3536 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003537 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003538 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3539 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003540 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003541 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003542 } catch (RuntimeException e) {
3543 Slog.w(TAG, "Failure sending alarm.", e);
3544 }
Tim Murray175c0f92017-11-28 15:01:04 -08003545 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003546 }
3547 }
3548
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003549 private boolean isExemptFromAppStandby(Alarm a) {
3550 return a.alarmClock != null || UserHandle.isCore(a.creatorUid)
3551 || (a.flags & FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED) != 0;
3552 }
3553
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003554 @VisibleForTesting
3555 static class Injector {
3556 private long mNativeData;
3557 private Context mContext;
3558
3559 Injector(Context context) {
3560 mContext = context;
3561 }
3562
3563 void init() {
3564 mNativeData = AlarmManagerService.init();
3565 }
3566
3567 int waitForAlarm() {
3568 return AlarmManagerService.waitForAlarm(mNativeData);
3569 }
3570
3571 boolean isAlarmDriverPresent() {
3572 return mNativeData != 0;
3573 }
3574
3575 void setAlarm(int type, long millis) {
3576 // The kernel never triggers alarms with negative wakeup times
3577 // so we ensure they are positive.
3578 final long alarmSeconds, alarmNanoseconds;
3579 if (millis < 0) {
3580 alarmSeconds = 0;
3581 alarmNanoseconds = 0;
3582 } else {
3583 alarmSeconds = millis / 1000;
3584 alarmNanoseconds = (millis % 1000) * 1000 * 1000;
3585 }
3586
3587 final int result = AlarmManagerService.set(mNativeData, type, alarmSeconds,
3588 alarmNanoseconds);
3589 if (result != 0) {
3590 final long nowElapsed = SystemClock.elapsedRealtime();
3591 Slog.wtf(TAG, "Unable to set kernel alarm, now=" + nowElapsed
3592 + " type=" + type + " @ (" + alarmSeconds + "," + alarmNanoseconds
3593 + "), ret = " + result + " = " + Os.strerror(result));
3594 }
3595 }
3596
3597 long getNextAlarm(int type) {
3598 return AlarmManagerService.getNextAlarm(mNativeData, type);
3599 }
3600
3601 void setKernelTimezone(int minutesWest) {
3602 AlarmManagerService.setKernelTimezone(mNativeData, minutesWest);
3603 }
3604
3605 void setKernelTime(long millis) {
3606 if (mNativeData != 0) {
3607 AlarmManagerService.setKernelTime(mNativeData, millis);
3608 }
3609 }
3610
3611 void close() {
3612 AlarmManagerService.close(mNativeData);
3613 }
3614
3615 long getElapsedRealtime() {
3616 return SystemClock.elapsedRealtime();
3617 }
3618
3619 long getCurrentTimeMillis() {
3620 return System.currentTimeMillis();
3621 }
3622
3623 PowerManager.WakeLock getAlarmWakeLock() {
3624 final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
3625 return pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
3626 }
3627
3628 int getSystemUiUid() {
3629 int sysUiUid = -1;
3630 final PackageManager pm = mContext.getPackageManager();
3631 try {
3632 PermissionInfo sysUiPerm = pm.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
3633 ApplicationInfo sysUi = pm.getApplicationInfo(sysUiPerm.packageName, 0);
3634 if ((sysUi.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
3635 sysUiUid = sysUi.uid;
3636 } else {
3637 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
3638 + " defined by non-privileged app " + sysUi.packageName
3639 + " - ignoring");
3640 }
3641 } catch (NameNotFoundException e) {
3642 }
3643 return sysUiUid;
3644 }
3645
3646 ClockReceiver getClockReceiver(AlarmManagerService service) {
3647 return service.new ClockReceiver();
3648 }
3649 }
3650
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003651 private class AlarmThread extends Thread
3652 {
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003653 private int mFalseWakeups;
3654 private int mWtfThreshold;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003655 public AlarmThread()
3656 {
3657 super("AlarmManager");
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003658 mFalseWakeups = 0;
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003659 mWtfThreshold = 100;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 }
Kweku Adams61e03292017-10-19 14:27:12 -07003661
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003662 public void run()
3663 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003664 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3665
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003666 while (true)
3667 {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003668 int result = mInjector.waitForAlarm();
3669 final long nowRTC = mInjector.getCurrentTimeMillis();
3670 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate8b98ade2018-02-09 11:13:19 -08003671 synchronized (mLock) {
3672 mLastWakeup = nowELAPSED;
3673 }
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003674 if (result == 0) {
3675 Slog.wtf(TAG, "waitForAlarm returned 0, nowRTC = " + nowRTC
3676 + ", nowElapsed = " + nowELAPSED);
3677 }
Christopher Tate8b98ade2018-02-09 11:13:19 -08003678 triggerList.clear();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003679
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003680 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003681 // The kernel can give us spurious time change notifications due to
3682 // small adjustments it makes internally; we want to filter those out.
3683 final long lastTimeChangeClockTime;
3684 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003685 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003686 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3687 expectedClockTime = lastTimeChangeClockTime
3688 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003689 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003690 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3691 || nowRTC > (expectedClockTime+1000)) {
3692 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003693 // let's do it!
3694 if (DEBUG_BATCH) {
3695 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3696 }
Bookatz7948c872018-09-04 12:58:33 -07003697 // StatsLog requires currentTimeMillis(), which == nowRTC to within usecs.
3698 StatsLog.write(StatsLog.WALL_CLOCK_TIME_SHIFTED, nowRTC);
Christopher Tatec8b7f432018-09-28 16:23:10 -07003699 removeImpl(null, mTimeTickTrigger);
3700 removeImpl(mDateChangeSender, null);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003701 rebatchAllAlarms();
3702 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003703 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003704 synchronized (mLock) {
3705 mNumTimeChanged++;
3706 mLastTimeChangeClockTime = nowRTC;
3707 mLastTimeChangeRealtime = nowELAPSED;
3708 }
3709 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3710 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003711 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003712 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3713 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003714 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3715
3716 // The world has changed on us, so we need to re-evaluate alarms
3717 // regardless of whether the kernel has told us one went off.
3718 result |= IS_WAKEUP_MASK;
3719 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003721
Dianne Hackbornc3527222015-05-13 14:03:20 -07003722 if (result != TIME_CHANGED_MASK) {
3723 // If this was anything besides just a time change, then figure what if
3724 // anything to do about alarms.
3725 synchronized (mLock) {
3726 if (localLOGV) Slog.v(
3727 TAG, "Checking for alarms... rtc=" + nowRTC
3728 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003729
Dianne Hackbornc3527222015-05-13 14:03:20 -07003730 if (WAKEUP_STATS) {
3731 if ((result & IS_WAKEUP_MASK) != 0) {
3732 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3733 int n = 0;
3734 for (WakeupEvent event : mRecentWakeups) {
3735 if (event.when > newEarliest) break;
3736 n++; // number of now-stale entries at the list head
3737 }
3738 for (int i = 0; i < n; i++) {
3739 mRecentWakeups.remove();
3740 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003741
Dianne Hackbornc3527222015-05-13 14:03:20 -07003742 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003743 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003744 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003745
Christopher Tate8b98ade2018-02-09 11:13:19 -08003746 mLastTrigger = nowELAPSED;
Dianne Hackbornc3527222015-05-13 14:03:20 -07003747 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3748 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3749 // if there are no wakeup alarms and the screen is off, we can
3750 // delay what we have so far until the future.
3751 if (mPendingNonWakeupAlarms.size() == 0) {
3752 mStartCurrentDelayTime = nowELAPSED;
3753 mNextNonWakeupDeliveryTime = nowELAPSED
3754 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3755 }
3756 mPendingNonWakeupAlarms.addAll(triggerList);
3757 mNumDelayedAlarms += triggerList.size();
3758 rescheduleKernelAlarmsLocked();
3759 updateNextAlarmClockLocked();
3760 } else {
3761 // now deliver the alarm intents; if there are pending non-wakeup
3762 // alarms, we need to merge them in to the list. note we don't
3763 // just deliver them first because we generally want non-wakeup
3764 // alarms delivered after wakeup alarms.
Dianne Hackbornc3527222015-05-13 14:03:20 -07003765 if (mPendingNonWakeupAlarms.size() > 0) {
3766 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3767 triggerList.addAll(mPendingNonWakeupAlarms);
3768 Collections.sort(triggerList, mAlarmDispatchComparator);
3769 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3770 mTotalDelayTime += thisDelayTime;
3771 if (mMaxDelayTime < thisDelayTime) {
3772 mMaxDelayTime = thisDelayTime;
3773 }
3774 mPendingNonWakeupAlarms.clear();
3775 }
Suprabh Shukla1d6a4032018-07-09 16:59:27 -07003776 if (mLastTimeChangeRealtime != nowELAPSED && triggerList.isEmpty()) {
3777 if (++mFalseWakeups >= mWtfThreshold) {
3778 Slog.wtf(TAG, "Too many (" + mFalseWakeups
3779 + ") false wakeups, nowElapsed=" + nowELAPSED);
3780 if (mWtfThreshold < 100_000) {
3781 mWtfThreshold *= 10;
3782 } else {
3783 mFalseWakeups = 0;
3784 }
3785 }
3786 }
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003787 final ArraySet<Pair<String, Integer>> triggerPackages =
3788 new ArraySet<>();
3789 for (int i = 0; i < triggerList.size(); i++) {
3790 final Alarm a = triggerList.get(i);
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08003791 if (!isExemptFromAppStandby(a)) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003792 triggerPackages.add(Pair.create(
3793 a.sourcePackage, UserHandle.getUserId(a.creatorUid)));
Suprabh Shukla75edab12018-01-29 14:09:06 -08003794 }
3795 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003796 deliverAlarmsLocked(triggerList, nowELAPSED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003797 reorderAlarmsBasedOnStandbyBuckets(triggerPackages);
3798 rescheduleKernelAlarmsLocked();
3799 updateNextAlarmClockLocked();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003800 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003801 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003802
3803 } else {
3804 // Just in case -- even though no wakeup flag was set, make sure
3805 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003806 synchronized (mLock) {
3807 rescheduleKernelAlarmsLocked();
3808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003809 }
3810 }
3811 }
3812 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003813
David Christieebe51fc2013-07-26 13:23:29 -07003814 /**
3815 * Attribute blame for a WakeLock.
David Christieebe51fc2013-07-26 13:23:29 -07003816 * @param ws WorkSource to attribute blame.
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00003817 * @param knownUid attribution uid; < 0 values are ignored.
David Christieebe51fc2013-07-26 13:23:29 -07003818 */
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00003819 void setWakelockWorkSource(WorkSource ws, int knownUid, String tag, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003820 try {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003821 mWakeLock.setHistoryTag(first ? tag : null);
3822
David Christieebe51fc2013-07-26 13:23:29 -07003823 if (ws != null) {
3824 mWakeLock.setWorkSource(ws);
3825 return;
3826 }
3827
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00003828 if (knownUid >= 0) {
3829 mWakeLock.setWorkSource(new WorkSource(knownUid));
Christopher Tatec4a07d12012-04-06 14:19:13 -07003830 return;
3831 }
3832 } catch (Exception e) {
3833 }
3834
3835 // Something went wrong; fall back to attributing the lock to the OS
3836 mWakeLock.setWorkSource(null);
3837 }
3838
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00003839 private static int getAlarmAttributionUid(Alarm alarm) {
3840 if (alarm.workSource != null && !alarm.workSource.isEmpty()) {
3841 return alarm.workSource.getAttributionUid();
3842 }
3843
3844 return alarm.creatorUid;
3845 }
3846
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003847 @VisibleForTesting
3848 class AlarmHandler extends Handler {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003849 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003850 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3851 public static final int LISTENER_TIMEOUT = 3;
3852 public static final int REPORT_ALARMS_ACTIVE = 4;
Suprabh Shukla75edab12018-01-29 14:09:06 -08003853 public static final int APP_STANDBY_BUCKET_CHANGED = 5;
3854 public static final int APP_STANDBY_PAROLE_CHANGED = 6;
Makoto Onuki4d298b52018-02-05 10:54:58 -08003855 public static final int REMOVE_FOR_STOPPED = 7;
Kweku Adams61e03292017-10-19 14:27:12 -07003856
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003857 AlarmHandler() {
3858 super(Looper.myLooper());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003859 }
Kweku Adams61e03292017-10-19 14:27:12 -07003860
Makoto Onuki4d298b52018-02-05 10:54:58 -08003861 public void postRemoveForStopped(int uid) {
3862 obtainMessage(REMOVE_FOR_STOPPED, uid, 0).sendToTarget();
3863 }
3864
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003865 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003866 switch (msg.what) {
3867 case ALARM_EVENT: {
3868 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3869 synchronized (mLock) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003870 final long nowRTC = mInjector.getCurrentTimeMillis();
3871 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003872 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3873 updateNextAlarmClockLocked();
3874 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003875
Christopher Tate14a7bb02015-10-01 10:24:31 -07003876 // now trigger the alarms without the lock held
3877 for (int i=0; i<triggerList.size(); i++) {
3878 Alarm alarm = triggerList.get(i);
3879 try {
3880 alarm.operation.send();
3881 } catch (PendingIntent.CanceledException e) {
3882 if (alarm.repeatInterval > 0) {
3883 // This IntentSender is no longer valid, but this
3884 // is a repeating alarm, so toss the hoser.
Christopher Tatec8b7f432018-09-28 16:23:10 -07003885 removeImpl(alarm.operation, null);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003886 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003887 }
3888 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003889 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003890 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003891
3892 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3893 sendNextAlarmClockChanged();
3894 break;
3895
3896 case LISTENER_TIMEOUT:
3897 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3898 break;
3899
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003900 case REPORT_ALARMS_ACTIVE:
3901 if (mLocalDeviceIdleController != null) {
3902 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3903 }
3904 break;
3905
Suprabh Shukla75edab12018-01-29 14:09:06 -08003906 case APP_STANDBY_PAROLE_CHANGED:
3907 synchronized (mLock) {
3908 mAppStandbyParole = (Boolean) msg.obj;
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003909 if (reorderAlarmsBasedOnStandbyBuckets(null)) {
3910 rescheduleKernelAlarmsLocked();
3911 updateNextAlarmClockLocked();
3912 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003913 }
3914 break;
3915
3916 case APP_STANDBY_BUCKET_CHANGED:
3917 synchronized (mLock) {
Suprabh Shukla92994ab2018-01-31 17:39:30 -08003918 final ArraySet<Pair<String, Integer>> filterPackages = new ArraySet<>();
3919 filterPackages.add(Pair.create((String) msg.obj, msg.arg1));
3920 if (reorderAlarmsBasedOnStandbyBuckets(filterPackages)) {
3921 rescheduleKernelAlarmsLocked();
3922 updateNextAlarmClockLocked();
3923 }
Suprabh Shukla75edab12018-01-29 14:09:06 -08003924 }
3925 break;
3926
Makoto Onuki4d298b52018-02-05 10:54:58 -08003927 case REMOVE_FOR_STOPPED:
3928 synchronized (mLock) {
3929 removeForStoppedLocked(msg.arg1);
3930 }
3931 break;
3932
Christopher Tate14a7bb02015-10-01 10:24:31 -07003933 default:
3934 // nope, just ignore it
3935 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003936 }
3937 }
3938 }
Kweku Adams61e03292017-10-19 14:27:12 -07003939
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003940 class ClockReceiver extends BroadcastReceiver {
3941 public ClockReceiver() {
3942 IntentFilter filter = new IntentFilter();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003943 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003944 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003945 }
Kweku Adams61e03292017-10-19 14:27:12 -07003946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003947 @Override
3948 public void onReceive(Context context, Intent intent) {
Christopher Tatec8b7f432018-09-28 16:23:10 -07003949 if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003950 // Since the kernel does not keep track of DST, we need to
3951 // reset the TZ information at the beginning of each day
3952 // based off of the current Zone gmt offset + userspace tracked
3953 // daylight savings information.
3954 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003955 int gmtOffset = zone.getOffset(mInjector.getCurrentTimeMillis());
3956 mInjector.setKernelTimezone(-(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003957 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003958 }
3959 }
Kweku Adams61e03292017-10-19 14:27:12 -07003960
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003961 public void scheduleTimeTickEvent() {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003962 final long currentTime = mInjector.getCurrentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003963 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003964
3965 // Schedule this event for the amount of time that it would take to get to
3966 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003967 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003968
David Christieebe51fc2013-07-26 13:23:29 -07003969 final WorkSource workSource = null; // Let system take blame for time tick events.
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003970 setImpl(ELAPSED_REALTIME, mInjector.getElapsedRealtime() + tickEventDelay, 0,
Suprabh Shukla12bd0162018-11-12 18:00:18 -08003971 0, null, mTimeTickTrigger, "TIME_TICK", AlarmManager.FLAG_STANDALONE,
3972 workSource, null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003973
3974 // Finally, remember when we set the tick alarm
3975 synchronized (mLock) {
3976 mLastTickSet = currentTime;
3977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003978 }
Christopher Tate385e4982013-07-23 18:22:29 -07003979
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003980 public void scheduleDateChangedEvent() {
3981 Calendar calendar = Calendar.getInstance();
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07003982 calendar.setTimeInMillis(mInjector.getCurrentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003983 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003984 calendar.set(Calendar.MINUTE, 0);
3985 calendar.set(Calendar.SECOND, 0);
3986 calendar.set(Calendar.MILLISECOND, 0);
3987 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003988
3989 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003990 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3991 AlarmManager.FLAG_STANDALONE, workSource, null,
3992 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003993 }
3994 }
Kweku Adams61e03292017-10-19 14:27:12 -07003995
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003996 class InteractiveStateReceiver extends BroadcastReceiver {
3997 public InteractiveStateReceiver() {
3998 IntentFilter filter = new IntentFilter();
3999 filter.addAction(Intent.ACTION_SCREEN_OFF);
4000 filter.addAction(Intent.ACTION_SCREEN_ON);
4001 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
4002 getContext().registerReceiver(this, filter);
4003 }
4004
4005 @Override
4006 public void onReceive(Context context, Intent intent) {
4007 synchronized (mLock) {
4008 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
4009 }
4010 }
4011 }
4012
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004013 class UninstallReceiver extends BroadcastReceiver {
4014 public UninstallReceiver() {
4015 IntentFilter filter = new IntentFilter();
4016 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
4017 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004018 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004019 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08004020 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004021 // Register for events related to sdcard installation.
4022 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08004023 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004024 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004025 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08004026 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004027 }
Kweku Adams61e03292017-10-19 14:27:12 -07004028
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004029 @Override
4030 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004031 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004032 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004033 String action = intent.getAction();
4034 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08004035 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
4036 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
4037 for (String packageName : pkgList) {
4038 if (lookForPackageLocked(packageName)) {
4039 setResultCode(Activity.RESULT_OK);
4040 return;
4041 }
4042 }
4043 return;
4044 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004045 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004046 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
4047 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
4048 if (userHandle >= 0) {
4049 removeUserLocked(userHandle);
Suprabh Shukla75edab12018-01-29 14:09:06 -08004050 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4051 final Pair<String, Integer> packageUser =
4052 mLastAlarmDeliveredForPackage.keyAt(i);
4053 if (packageUser.second == userHandle) {
4054 mLastAlarmDeliveredForPackage.removeAt(i);
4055 }
4056 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07004057 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004058 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004059 if (uid >= 0) {
4060 mLastAllowWhileIdleDispatch.delete(uid);
Makoto Onukiadb50d82018-01-29 16:20:30 -08004061 mUseAllowWhileIdleShortTime.delete(uid);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07004062 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004063 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08004064 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
4065 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
4066 // This package is being updated; don't kill its alarms.
4067 return;
4068 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004069 Uri data = intent.getData();
4070 if (data != null) {
4071 String pkg = data.getSchemeSpecificPart();
4072 if (pkg != null) {
4073 pkgList = new String[]{pkg};
4074 }
4075 }
4076 }
4077 if (pkgList != null && (pkgList.length > 0)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004078 for (int i = mLastAlarmDeliveredForPackage.size() - 1; i >= 0; i--) {
4079 Pair<String, Integer> packageUser = mLastAlarmDeliveredForPackage.keyAt(i);
4080 if (ArrayUtils.contains(pkgList, packageUser.first)
4081 && packageUser.second == UserHandle.getUserId(uid)) {
4082 mLastAlarmDeliveredForPackage.removeAt(i);
4083 }
4084 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004085 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08004086 if (uid >= 0) {
4087 // package-removed case
4088 removeLocked(uid);
4089 } else {
4090 // external-applications-unavailable etc case
4091 removeLocked(pkg);
4092 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07004093 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004094 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
4095 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
4096 if (uidStats.remove(pkg) != null) {
4097 if (uidStats.size() <= 0) {
4098 mBroadcastStats.removeAt(i);
4099 }
4100 }
4101 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08004102 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004103 }
4104 }
4105 }
4106 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004107
4108 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004109 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004110 }
4111
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004112 @Override public void onUidGone(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004113 if (disabled) {
4114 mHandler.postRemoveForStopped(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08004115 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004116 }
4117
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004118 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004119 }
4120
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004121 @Override public void onUidIdle(int uid, boolean disabled) {
Makoto Onuki4d298b52018-02-05 10:54:58 -08004122 if (disabled) {
4123 mHandler.postRemoveForStopped(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08004124 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004125 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07004126
4127 @Override public void onUidCachedChanged(int uid, boolean cached) {
4128 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07004129 };
4130
Suprabh Shukla75edab12018-01-29 14:09:06 -08004131 /**
4132 * Tracking of app assignments to standby buckets
4133 */
4134 final class AppStandbyTracker extends UsageStatsManagerInternal.AppIdleStateChangeListener {
4135 @Override
4136 public void onAppIdleStateChanged(final String packageName, final @UserIdInt int userId,
Amith Yamasani119be9a2018-02-18 22:23:00 -08004137 boolean idle, int bucket, int reason) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004138 if (DEBUG_STANDBY) {
4139 Slog.d(TAG, "Package " + packageName + " for user " + userId + " now in bucket " +
4140 bucket);
4141 }
4142 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
Suprabh Shukla92994ab2018-01-31 17:39:30 -08004143 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_BUCKET_CHANGED, userId, -1, packageName)
4144 .sendToTarget();
Suprabh Shukla75edab12018-01-29 14:09:06 -08004145 }
4146
4147 @Override
4148 public void onParoleStateChanged(boolean isParoleOn) {
4149 if (DEBUG_STANDBY) {
4150 Slog.d(TAG, "Global parole state now " + (isParoleOn ? "ON" : "OFF"));
4151 }
4152 mHandler.removeMessages(AlarmHandler.APP_STANDBY_BUCKET_CHANGED);
4153 mHandler.removeMessages(AlarmHandler.APP_STANDBY_PAROLE_CHANGED);
4154 mHandler.obtainMessage(AlarmHandler.APP_STANDBY_PAROLE_CHANGED,
4155 Boolean.valueOf(isParoleOn)).sendToTarget();
4156 }
4157 };
4158
Makoto Onuki2206af32017-11-21 16:25:35 -08004159 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004160 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08004161 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004162 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08004163 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004164 }
4165 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004166
4167 @Override
4168 public void unblockAlarmsForUid(int uid) {
4169 synchronized (mLock) {
4170 sendPendingBackgroundAlarmsLocked(uid, null);
4171 }
4172 }
4173
4174 @Override
4175 public void unblockAlarmsForUidPackage(int uid, String packageName) {
4176 synchronized (mLock) {
4177 sendPendingBackgroundAlarmsLocked(uid, packageName);
4178 }
4179 }
Makoto Onukiadb50d82018-01-29 16:20:30 -08004180
4181 @Override
4182 public void onUidForeground(int uid, boolean foreground) {
4183 synchronized (mLock) {
4184 if (foreground) {
4185 mUseAllowWhileIdleShortTime.put(uid, true);
4186
4187 // Note we don't have to drain the pending while-idle alarms here, because
4188 // this event should coincide with unblockAlarmsForUid().
4189 }
4190 }
4191 }
Makoto Onuki2206af32017-11-21 16:25:35 -08004192 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07004193
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004194 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004195 String pkg = pi.getCreatorPackage();
4196 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004197 return getStatsLocked(uid, pkg);
4198 }
4199
4200 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08004201 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
4202 if (uidStats == null) {
4203 uidStats = new ArrayMap<String, BroadcastStats>();
4204 mBroadcastStats.put(uid, uidStats);
4205 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004206 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004207 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004208 bs = new BroadcastStats(uid, pkgName);
4209 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004210 }
4211 return bs;
4212 }
Dianne Hackborn81038902012-11-26 17:04:09 -08004213
Christopher Tate21e9f192017-08-08 13:49:11 -07004214 /**
4215 * Canonical count of (operation.send() - onSendFinished()) and
4216 * listener send/complete/timeout invocations.
4217 * Guarded by the usual lock.
4218 */
4219 @GuardedBy("mLock")
4220 private int mSendCount = 0;
4221 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07004222 private int mSendFinishCount = 0;
4223 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07004224 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07004225 @GuardedBy("mLock")
4226 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07004227
Christopher Tate14a7bb02015-10-01 10:24:31 -07004228 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07004229
Christopher Tate14a7bb02015-10-01 10:24:31 -07004230 private InFlight removeLocked(PendingIntent pi, Intent intent) {
4231 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07004232 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004233 return mInFlight.remove(i);
4234 }
4235 }
4236 mLog.w("No in-flight alarm for " + pi + " " + intent);
4237 return null;
4238 }
4239
4240 private InFlight removeLocked(IBinder listener) {
4241 for (int i = 0; i < mInFlight.size(); i++) {
4242 if (mInFlight.get(i).mListener == listener) {
4243 return mInFlight.remove(i);
4244 }
4245 }
4246 mLog.w("No in-flight alarm for listener " + listener);
4247 return null;
4248 }
4249
4250 private void updateStatsLocked(InFlight inflight) {
Suprabh Shukla6226c2f2018-08-22 18:15:04 -07004251 final long nowELAPSED = mInjector.getElapsedRealtime();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004252 BroadcastStats bs = inflight.mBroadcastStats;
4253 bs.nesting--;
4254 if (bs.nesting <= 0) {
4255 bs.nesting = 0;
4256 bs.aggregateTime += nowELAPSED - bs.startTime;
4257 }
4258 FilterStats fs = inflight.mFilterStats;
4259 fs.nesting--;
4260 if (fs.nesting <= 0) {
4261 fs.nesting = 0;
4262 fs.aggregateTime += nowELAPSED - fs.startTime;
4263 }
4264 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00004265 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
4266 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004267 }
4268 }
4269
4270 private void updateTrackingLocked(InFlight inflight) {
4271 if (inflight != null) {
4272 updateStatsLocked(inflight);
4273 }
4274 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004275 if (DEBUG_WAKELOCK) {
4276 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
4277 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004278 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004279 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004280 mWakeLock.release();
4281 if (mInFlight.size() > 0) {
4282 mLog.w("Finished all dispatches with " + mInFlight.size()
4283 + " remaining inflights");
4284 for (int i=0; i<mInFlight.size(); i++) {
4285 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
4286 }
4287 mInFlight.clear();
4288 }
4289 } else {
4290 // the next of our alarms is now in flight. reattribute the wakelock.
4291 if (mInFlight.size() > 0) {
4292 InFlight inFlight = mInFlight.get(0);
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004293 setWakelockWorkSource(inFlight.mWorkSource, inFlight.mCreatorUid, inFlight.mTag,
4294 false);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004295 } else {
4296 // should never happen
4297 mLog.w("Alarm wakelock still held but sent queue empty");
4298 mWakeLock.setWorkSource(null);
4299 }
4300 }
4301 }
4302
4303 /**
4304 * Callback that arrives when a direct-call alarm reports that delivery has finished
4305 */
4306 @Override
4307 public void alarmComplete(IBinder who) {
4308 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07004309 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07004310 + " pid=" + Binder.getCallingPid());
4311 return;
4312 }
4313
4314 final long ident = Binder.clearCallingIdentity();
4315 try {
4316 synchronized (mLock) {
4317 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
4318 InFlight inflight = removeLocked(who);
4319 if (inflight != null) {
4320 if (DEBUG_LISTENER_CALLBACK) {
4321 Slog.i(TAG, "alarmComplete() from " + who);
4322 }
4323 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004324 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004325 } else {
4326 // Delivery timed out, and the timeout handling already took care of
4327 // updating our tracking here, so we needn't do anything further.
4328 if (DEBUG_LISTENER_CALLBACK) {
4329 Slog.i(TAG, "Late alarmComplete() from " + who);
4330 }
4331 }
4332 }
4333 } finally {
4334 Binder.restoreCallingIdentity(ident);
4335 }
4336 }
4337
4338 /**
4339 * Callback that arrives when a PendingIntent alarm has finished delivery
4340 */
4341 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004342 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
4343 String resultData, Bundle resultExtras) {
4344 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07004345 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004346 updateTrackingLocked(removeLocked(pi, intent));
4347 }
4348 }
4349
4350 /**
4351 * Timeout of a direct-call alarm delivery
4352 */
4353 public void alarmTimedOut(IBinder who) {
4354 synchronized (mLock) {
4355 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08004356 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004357 // TODO: implement ANR policy for the target
4358 if (DEBUG_LISTENER_CALLBACK) {
4359 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004360 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004361 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07004362 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08004363 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07004364 if (DEBUG_LISTENER_CALLBACK) {
4365 Slog.i(TAG, "Spurious timeout of listener " + who);
4366 }
Christopher Tate21e9f192017-08-08 13:49:11 -07004367 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004368 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004369 }
4370 }
4371
4372 /**
4373 * Deliver an alarm and set up the post-delivery handling appropriately
4374 */
Andreas Gampea36dc622018-02-05 17:19:22 -08004375 @GuardedBy("mLock")
Christopher Tate14a7bb02015-10-01 10:24:31 -07004376 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004377 final long workSourceToken = ThreadLocalWorkSource.setUid(
4378 getAlarmAttributionUid(alarm));
4379 try {
4380 if (alarm.operation != null) {
4381 // PendingIntent alarm
4382 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08004383
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004384 try {
4385 alarm.operation.send(getContext(), 0,
4386 mBackgroundIntent.putExtra(
4387 Intent.EXTRA_ALARM_COUNT, alarm.count),
4388 mDeliveryTracker, mHandler, null,
4389 allowWhileIdle ? mIdleOptions : null);
4390 } catch (PendingIntent.CanceledException e) {
4391 if (alarm.repeatInterval > 0) {
4392 // This IntentSender is no longer valid, but this
4393 // is a repeating alarm, so toss it
4394 removeImpl(alarm.operation, null);
4395 }
4396 // No actual delivery was possible, so the delivery tracker's
4397 // 'finished' callback won't be invoked. We also don't need
4398 // to do any wakelock or stats tracking, so we have nothing
4399 // left to do here but go on to the next thing.
4400 mSendFinishCount++;
4401 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004402 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004403 } else {
4404 // Direct listener callback alarm
4405 mListenerCount++;
Christopher Tatec8b7f432018-09-28 16:23:10 -07004406
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004407 if (RECORD_ALARMS_IN_HISTORY) {
4408 if (alarm.listener == mTimeTickTrigger) {
4409 mTickHistory[mNextTickHistory++] = nowELAPSED;
4410 if (mNextTickHistory >= TICK_HISTORY_DEPTH) {
4411 mNextTickHistory = 0;
4412 }
Christopher Tatec8b7f432018-09-28 16:23:10 -07004413 }
4414 }
Christopher Tatec8b7f432018-09-28 16:23:10 -07004415
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004416 try {
4417 if (DEBUG_LISTENER_CALLBACK) {
4418 Slog.v(TAG, "Alarm to uid=" + alarm.uid
4419 + " listener=" + alarm.listener.asBinder());
4420 }
4421 alarm.listener.doAlarm(this);
4422 mHandler.sendMessageDelayed(
4423 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
4424 alarm.listener.asBinder()),
4425 mConstants.LISTENER_TIMEOUT);
4426 } catch (Exception e) {
4427 if (DEBUG_LISTENER_CALLBACK) {
4428 Slog.i(TAG, "Alarm undeliverable to listener "
4429 + alarm.listener.asBinder(), e);
4430 }
4431 // As in the PendingIntent.CanceledException case, delivery of the
4432 // alarm was not possible, so we have no wakelock or timeout or
4433 // stats management to do. It threw before we posted the delayed
4434 // timeout message, so we're done here.
4435 mListenerFinishCount++;
4436 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004437 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004438 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004439 } finally {
4440 ThreadLocalWorkSource.restore(workSourceToken);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004441 }
4442
4443 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08004444 if (DEBUG_WAKELOCK) {
4445 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
4446 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004447 if (mBroadcastRefCount == 0) {
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004448 setWakelockWorkSource(alarm.workSource, alarm.creatorUid, alarm.statsTag, true);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004449 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08004450 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07004451 }
Marcin Oczeretko735b19b2018-12-14 15:38:15 +00004452 final InFlight inflight = new InFlight(AlarmManagerService.this, alarm, nowELAPSED);
Christopher Tate14a7bb02015-10-01 10:24:31 -07004453 mInFlight.add(inflight);
4454 mBroadcastRefCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07004455 if (allowWhileIdle) {
4456 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004457 mLastAllowWhileIdleDispatch.put(alarm.creatorUid, nowELAPSED);
Makoto Onukie4918212018-02-06 11:30:15 -08004458 if ((mAppStateTracker == null)
4459 || mAppStateTracker.isUidInForeground(alarm.creatorUid)) {
Suprabh Shuklac25447d2018-01-19 16:43:35 -08004460 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, true);
4461 } else {
4462 mUseAllowWhileIdleShortTime.put(alarm.creatorUid, false);
4463 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004464 if (RECORD_DEVICE_IDLE_ALARMS) {
4465 IdleDispatchEntry ent = new IdleDispatchEntry();
4466 ent.uid = alarm.uid;
4467 ent.pkg = alarm.packageName;
4468 ent.tag = alarm.statsTag;
4469 ent.op = "DELIVER";
4470 ent.elapsedRealtime = nowELAPSED;
4471 mAllowWhileIdleDispatches.add(ent);
4472 }
4473 }
Suprabh Shuklad65e58a2018-02-05 20:36:08 -08004474 if (!isExemptFromAppStandby(alarm)) {
Suprabh Shukla75edab12018-01-29 14:09:06 -08004475 final Pair<String, Integer> packageUser = Pair.create(alarm.sourcePackage,
4476 UserHandle.getUserId(alarm.creatorUid));
4477 mLastAlarmDeliveredForPackage.put(packageUser, nowELAPSED);
4478 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07004479
4480 final BroadcastStats bs = inflight.mBroadcastStats;
4481 bs.count++;
4482 if (bs.nesting == 0) {
4483 bs.nesting = 1;
4484 bs.startTime = nowELAPSED;
4485 } else {
4486 bs.nesting++;
4487 }
4488 final FilterStats fs = inflight.mFilterStats;
4489 fs.count++;
4490 if (fs.nesting == 0) {
4491 fs.nesting = 1;
4492 fs.startTime = nowELAPSED;
4493 } else {
4494 fs.nesting++;
4495 }
4496 if (alarm.type == ELAPSED_REALTIME_WAKEUP
4497 || alarm.type == RTC_WAKEUP) {
4498 bs.numWakeup++;
4499 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00004500 ActivityManager.noteWakeupAlarm(
4501 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
4502 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004503 }
4504 }
4505 }
mswest463f4c99d2018-02-01 10:13:10 -08004506
4507 private class ShellCmd extends ShellCommand {
4508
4509 IAlarmManager getBinderService() {
4510 return IAlarmManager.Stub.asInterface(mService);
4511 }
4512
4513 @Override
4514 public int onCommand(String cmd) {
4515 if (cmd == null) {
4516 return handleDefaultCommands(cmd);
4517 }
4518
4519 final PrintWriter pw = getOutPrintWriter();
4520 try {
4521 switch (cmd) {
4522 case "set-time":
4523 final long millis = Long.parseLong(getNextArgRequired());
4524 return (getBinderService().setTime(millis)) ? 0 : -1;
4525 case "set-timezone":
4526 final String tz = getNextArgRequired();
4527 getBinderService().setTimeZone(tz);
4528 return 0;
4529 default:
4530 return handleDefaultCommands(cmd);
4531 }
4532 } catch (Exception e) {
4533 pw.println(e);
4534 }
4535 return -1;
4536 }
4537
4538 @Override
4539 public void onHelp() {
4540 PrintWriter pw = getOutPrintWriter();
4541 pw.println("Alarm manager service (alarm) commands:");
4542 pw.println(" help");
4543 pw.println(" Print this help text.");
4544 pw.println(" set-time TIME");
4545 pw.println(" Set the system clock time to TIME where TIME is milliseconds");
4546 pw.println(" since the Epoch.");
4547 pw.println(" set-timezone TZ");
4548 pw.println(" Set the system timezone to TZ where TZ is an Olson id.");
4549 }
4550 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004551}