blob: 472723dfa90931c9f5585202a926daca3d7733cf [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
Dianne Hackborn21f1bd12010-02-19 17:02:21 -080019import android.app.Activity;
Adrian Roosc42a1e12014-07-07 23:35:53 +020020import android.app.ActivityManager;
Christopher Tate57ceaaa2013-07-19 16:30:43 -070021import android.app.AlarmManager;
Christopher Tate14a7bb02015-10-01 10:24:31 -070022import android.app.AppOpsManager;
Dianne Hackborna750a632015-06-16 17:18:23 -070023import android.app.BroadcastOptions;
Christopher Tate14a7bb02015-10-01 10:24:31 -070024import android.app.IAlarmCompleteListener;
25import android.app.IAlarmListener;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080026import android.app.IAlarmManager;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070027import android.app.IUidObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080028import android.app.PendingIntent;
29import android.content.BroadcastReceiver;
Dianne Hackborna750a632015-06-16 17:18:23 -070030import android.content.ContentResolver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080031import android.content.Context;
32import android.content.Intent;
33import android.content.IntentFilter;
Christopher Tatebb9cce52017-04-18 14:19:43 -070034import android.content.pm.ApplicationInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.pm.PackageManager;
Christopher Tatebb9cce52017-04-18 14:19:43 -070036import android.content.pm.PackageManager.NameNotFoundException;
37import android.content.pm.PermissionInfo;
Dianne Hackborna750a632015-06-16 17:18:23 -070038import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.net.Uri;
40import android.os.Binder;
41import android.os.Bundle;
Christopher Tate247571462017-04-10 11:45:05 -070042import android.os.Environment;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.os.Handler;
Adam Lesinski182f73f2013-12-05 16:48:06 -080044import android.os.IBinder;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.os.Message;
46import android.os.PowerManager;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070047import android.os.Process;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -070048import android.os.RemoteException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.os.SystemClock;
50import android.os.SystemProperties;
Tim Murray175c0f92017-11-28 15:01:04 -080051import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070052import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070053import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020054import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020056import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080057import android.util.ArrayMap;
Dianne Hackborna750a632015-06-16 17:18:23 -070058import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020059import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080060import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080061import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020062import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070063import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070064import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070065import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080066
Christopher Tate4cb338d2013-07-26 13:11:31 -070067import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import java.io.FileDescriptor;
69import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070070import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080072import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.Calendar;
74import java.util.Collections;
75import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050076import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070077import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070078import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020079import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070080import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040082import java.util.TreeSet;
Makoto Onuki2206af32017-11-21 16:25:35 -080083import java.util.function.Predicate;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084
Christopher Tatee0a22b32013-07-11 14:43:13 -070085import static android.app.AlarmManager.RTC_WAKEUP;
86import static android.app.AlarmManager.RTC;
87import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
88import static android.app.AlarmManager.ELAPSED_REALTIME;
89
Christopher Tate21e9f192017-08-08 13:49:11 -070090import com.android.internal.annotations.GuardedBy;
Makoto Onuki2206af32017-11-21 16:25:35 -080091import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060092import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080093import com.android.internal.util.LocalLog;
Makoto Onuki2206af32017-11-21 16:25:35 -080094import com.android.server.ForceAppStandbyTracker.Listener;
Christopher Tate1d99c392017-12-07 16:54:04 -080095import com.android.server.LocalServices;
Dianne Hackborn81038902012-11-26 17:04:09 -080096
Makoto Onuki2206af32017-11-21 16:25:35 -080097/**
98 * Alarm manager implementaion.
99 *
100 * Unit test:
101 atest $ANDROID_BUILD_TOP/frameworks/base/services/tests/servicestests/src/com/android/server/AlarmManagerServiceTest.java
102 */
Adam Lesinski182f73f2013-12-05 16:48:06 -0800103class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700104 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
105 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700107 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final int TIME_CHANGED_MASK = 1 << 16;
109 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800110
Christopher Tatee0a22b32013-07-11 14:43:13 -0700111 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800112 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800113
Adam Lesinski182f73f2013-12-05 16:48:06 -0800114 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800115 static final boolean localLOGV = false;
116 static final boolean DEBUG_BATCH = localLOGV || false;
117 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200118 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700119 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800120 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700121 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700122 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700123 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final int ALARM_EVENT = 1;
125 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200126
Christopher Tate14a7bb02015-10-01 10:24:31 -0700127 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800129 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700130
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700132
Christopher Tate24cd46f2016-02-02 14:28:01 -0800133 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
134 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700135 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
136 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200137
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800139
Christopher Tate14a7bb02015-10-01 10:24:31 -0700140 AppOpsManager mAppOps;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800141 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700142
Adam Lesinski182f73f2013-12-05 16:48:06 -0800143 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800144
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700145 // List of alarms per uid deferred due to user applied background restrictions on the source app
146 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800147 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800148 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700149 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700150 private long mLastWakeupSet;
151 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800152 int mBroadcastRefCount = 0;
153 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700154 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700155 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
156 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800157 final AlarmHandler mHandler = new AlarmHandler();
158 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700159 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700161 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800162 PendingIntent mTimeTickSender;
163 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700164 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700165 boolean mInteractive = true;
166 long mNonInteractiveStartTime;
167 long mNonInteractiveTime;
168 long mLastAlarmDeliveryTime;
169 long mStartCurrentDelayTime;
170 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700171 long mLastTimeChangeClockTime;
172 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700173 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700174 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800175
Christopher Tatebb9cce52017-04-18 14:19:43 -0700176 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
177
178 /**
179 * This permission must be defined by the canonical System UI package,
180 * with protection level "signature".
181 */
182 private static final String SYSTEM_UI_SELF_PERMISSION =
183 "android.permission.systemui.IDENTITY";
184
185 /**
186 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
187 */
188 int mSystemUiUid;
189
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700190 /**
191 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700192 * used to determine the earliest we can dispatch the next such alarm. Times are in the
193 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700194 */
195 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
196
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700197 final static class IdleDispatchEntry {
198 int uid;
199 String pkg;
200 String tag;
201 String op;
202 long elapsedRealtime;
203 long argRealtime;
204 }
205 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
206
Dianne Hackborna750a632015-06-16 17:18:23 -0700207 /**
208 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
209 */
210 Bundle mIdleOptions;
211
Jose Lima235510e2014-08-13 12:50:01 -0700212 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
213 new SparseArray<>();
214 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
215 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200216 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
217 new SparseBooleanArray();
218 private boolean mNextAlarmClockMayChange;
219
220 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700221 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
222 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200223
Makoto Onuki2206af32017-11-21 16:25:35 -0800224 private final ForceAppStandbyTracker mForceAppStandbyTracker;
225
Dianne Hackborna750a632015-06-16 17:18:23 -0700226 /**
227 * All times are in milliseconds. These constants are kept synchronized with the system
228 * global Settings. Any access to this class or its fields should be done while
229 * holding the AlarmManagerService.mLock lock.
230 */
231 private final class Constants extends ContentObserver {
232 // Key names stored in the settings value.
233 private static final String KEY_MIN_FUTURITY = "min_futurity";
234 private static final String KEY_MIN_INTERVAL = "min_interval";
235 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
236 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
237 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
238 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700239 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700240 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700241
242 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
243 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700244 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700245 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700246 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
247
Christopher Tate14a7bb02015-10-01 10:24:31 -0700248 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
249
Dianne Hackborna750a632015-06-16 17:18:23 -0700250 // Minimum futurity of a new alarm
251 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
252
253 // Minimum alarm recurrence interval
254 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
255
256 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
257 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
258
259 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
260 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
261
262 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
263 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
264 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
265
Christopher Tate14a7bb02015-10-01 10:24:31 -0700266 // Direct alarm listener callback timeout
267 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
268
Dianne Hackborna750a632015-06-16 17:18:23 -0700269 private ContentResolver mResolver;
270 private final KeyValueListParser mParser = new KeyValueListParser(',');
271 private long mLastAllowWhileIdleWhitelistDuration = -1;
272
273 public Constants(Handler handler) {
274 super(handler);
275 updateAllowWhileIdleMinTimeLocked();
276 updateAllowWhileIdleWhitelistDurationLocked();
277 }
278
279 public void start(ContentResolver resolver) {
280 mResolver = resolver;
281 mResolver.registerContentObserver(Settings.Global.getUriFor(
282 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
283 updateConstants();
284 }
285
286 public void updateAllowWhileIdleMinTimeLocked() {
287 mAllowWhileIdleMinTime = mPendingIdleUntil != null
288 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
289 }
290
291 public void updateAllowWhileIdleWhitelistDurationLocked() {
292 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
293 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
294 BroadcastOptions opts = BroadcastOptions.makeBasic();
295 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
296 mIdleOptions = opts.toBundle();
297 }
298 }
299
300 @Override
301 public void onChange(boolean selfChange, Uri uri) {
302 updateConstants();
303 }
304
305 private void updateConstants() {
306 synchronized (mLock) {
307 try {
308 mParser.setString(Settings.Global.getString(mResolver,
309 Settings.Global.ALARM_MANAGER_CONSTANTS));
310 } catch (IllegalArgumentException e) {
311 // Failed to parse the settings string, log this and move on
312 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800313 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700314 }
315
316 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
317 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
318 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
319 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
320 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
321 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
322 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
323 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
324 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700325 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
326 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700327
328 updateAllowWhileIdleMinTimeLocked();
329 updateAllowWhileIdleWhitelistDurationLocked();
330 }
331 }
332
333 void dump(PrintWriter pw) {
334 pw.println(" Settings:");
335
336 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
337 TimeUtils.formatDuration(MIN_FUTURITY, pw);
338 pw.println();
339
340 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
341 TimeUtils.formatDuration(MIN_INTERVAL, pw);
342 pw.println();
343
Christopher Tate14a7bb02015-10-01 10:24:31 -0700344 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
345 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
346 pw.println();
347
Dianne Hackborna750a632015-06-16 17:18:23 -0700348 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
349 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
350 pw.println();
351
352 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
353 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
354 pw.println();
355
356 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
357 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
358 pw.println();
359 }
Kweku Adams61e03292017-10-19 14:27:12 -0700360
361 void dumpProto(ProtoOutputStream proto, long fieldId) {
362 final long token = proto.start(fieldId);
363
364 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
365 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
366 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
367 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
368 ALLOW_WHILE_IDLE_SHORT_TIME);
369 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
370 ALLOW_WHILE_IDLE_LONG_TIME);
371 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
372 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
373
374 proto.end(token);
375 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700376 }
377
378 final Constants mConstants;
379
Christopher Tate1590f1e2014-10-02 17:27:57 -0700380 // Alarm delivery ordering bookkeeping
381 static final int PRIO_TICK = 0;
382 static final int PRIO_WAKEUP = 1;
383 static final int PRIO_NORMAL = 2;
384
Dianne Hackborna750a632015-06-16 17:18:23 -0700385 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700386 int seq;
387 int priority;
388
389 PriorityClass() {
390 seq = mCurrentSeq - 1;
391 priority = PRIO_NORMAL;
392 }
393 }
394
Dianne Hackborna750a632015-06-16 17:18:23 -0700395 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700396 int mCurrentSeq = 0;
397
Dianne Hackborna750a632015-06-16 17:18:23 -0700398 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700399 public long when;
400 public int uid;
401 public String action;
402
403 public WakeupEvent(long theTime, int theUid, String theAction) {
404 when = theTime;
405 uid = theUid;
406 action = theAction;
407 }
408 }
409
Adam Lesinski182f73f2013-12-05 16:48:06 -0800410 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
411 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700412
Adrian Roosc42a1e12014-07-07 23:35:53 +0200413 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414 long start; // These endpoints are always in ELAPSED
415 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700416 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700417
418 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
419
420 Batch() {
421 start = 0;
422 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700423 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700424 }
425
426 Batch(Alarm seed) {
427 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700428 end = seed.maxWhenElapsed;
429 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700430 alarms.add(seed);
431 }
432
433 int size() {
434 return alarms.size();
435 }
436
437 Alarm get(int index) {
438 return alarms.get(index);
439 }
440
441 boolean canHold(long whenElapsed, long maxWhen) {
442 return (end >= whenElapsed) && (start <= maxWhen);
443 }
444
445 boolean add(Alarm alarm) {
446 boolean newStart = false;
447 // narrows the batch if necessary; presumes that canHold(alarm) is true
448 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
449 if (index < 0) {
450 index = 0 - index - 1;
451 }
452 alarms.add(index, alarm);
453 if (DEBUG_BATCH) {
454 Slog.v(TAG, "Adding " + alarm + " to " + this);
455 }
456 if (alarm.whenElapsed > start) {
457 start = alarm.whenElapsed;
458 newStart = true;
459 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700460 if (alarm.maxWhenElapsed < end) {
461 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700463 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700464
465 if (DEBUG_BATCH) {
466 Slog.v(TAG, " => now " + this);
467 }
468 return newStart;
469 }
470
Christopher Tate1d99c392017-12-07 16:54:04 -0800471 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700472 boolean didRemove = false;
473 long newStart = 0; // recalculate endpoints as we go
474 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700475 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700476 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700477 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800478 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700479 alarms.remove(i);
480 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200481 if (alarm.alarmClock != null) {
482 mNextAlarmClockMayChange = true;
483 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700484 } else {
485 if (alarm.whenElapsed > newStart) {
486 newStart = alarm.whenElapsed;
487 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700488 if (alarm.maxWhenElapsed < newEnd) {
489 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700490 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700491 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700492 i++;
493 }
494 }
495 if (didRemove) {
496 // commit the new batch bounds
497 start = newStart;
498 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700499 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700500 }
501 return didRemove;
502 }
503
Christopher Tatee0a22b32013-07-11 14:43:13 -0700504 boolean hasPackage(final String packageName) {
505 final int N = alarms.size();
506 for (int i = 0; i < N; i++) {
507 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700508 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700509 return true;
510 }
511 }
512 return false;
513 }
514
515 boolean hasWakeups() {
516 final int N = alarms.size();
517 for (int i = 0; i < N; i++) {
518 Alarm a = alarms.get(i);
519 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
520 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
521 return true;
522 }
523 }
524 return false;
525 }
526
527 @Override
528 public String toString() {
529 StringBuilder b = new StringBuilder(40);
530 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
531 b.append(" num="); b.append(size());
532 b.append(" start="); b.append(start);
533 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700534 if (flags != 0) {
535 b.append(" flgs=0x");
536 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700537 }
538 b.append('}');
539 return b.toString();
540 }
Kweku Adams61e03292017-10-19 14:27:12 -0700541
542 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
543 long nowRTC) {
544 final long token = proto.start(fieldId);
545
546 proto.write(BatchProto.START_REALTIME, start);
547 proto.write(BatchProto.END_REALTIME, end);
548 proto.write(BatchProto.FLAGS, flags);
549 for (Alarm a : alarms) {
550 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
551 }
552
553 proto.end(token);
554 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700555 }
556
557 static class BatchTimeOrder implements Comparator<Batch> {
558 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800559 long when1 = b1.start;
560 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800561 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700562 return 1;
563 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800564 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 return -1;
566 }
567 return 0;
568 }
569 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800570
571 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
572 @Override
573 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700574 // priority class trumps everything. TICK < WAKEUP < NORMAL
575 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
576 return -1;
577 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
578 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800579 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700580
581 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800582 if (lhs.whenElapsed < rhs.whenElapsed) {
583 return -1;
584 } else if (lhs.whenElapsed > rhs.whenElapsed) {
585 return 1;
586 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700587
588 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800589 return 0;
590 }
591 };
592
Christopher Tate1590f1e2014-10-02 17:27:57 -0700593 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
594 final int N = alarms.size();
595 for (int i = 0; i < N; i++) {
596 Alarm a = alarms.get(i);
597
598 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700599 if (a.operation != null
600 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700601 alarmPrio = PRIO_TICK;
602 } else if (a.wakeup) {
603 alarmPrio = PRIO_WAKEUP;
604 } else {
605 alarmPrio = PRIO_NORMAL;
606 }
607
608 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700609 String alarmPackage = (a.operation != null)
610 ? a.operation.getCreatorPackage()
611 : a.packageName;
612 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700613 if (packagePrio == null) {
614 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700615 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700616 }
617 a.priorityClass = packagePrio;
618
619 if (packagePrio.seq != mCurrentSeq) {
620 // first alarm we've seen in the current delivery generation from this package
621 packagePrio.priority = alarmPrio;
622 packagePrio.seq = mCurrentSeq;
623 } else {
624 // Multiple alarms from this package being delivered in this generation;
625 // bump the package's delivery class if it's warranted.
626 // TICK < WAKEUP < NORMAL
627 if (alarmPrio < packagePrio.priority) {
628 packagePrio.priority = alarmPrio;
629 }
630 }
631 }
632 }
633
Christopher Tatee0a22b32013-07-11 14:43:13 -0700634 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800635 static final long MIN_FUZZABLE_INTERVAL = 10000;
636 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700637 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
638
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700639 // 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 -0700640 // to run during this time are placed in mPendingWhileIdleAlarms
641 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700642 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700643 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700644
Jeff Brownb880d882014-02-10 19:47:07 -0800645 public AlarmManagerService(Context context) {
646 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700647 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800648
649 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
650 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Christopher Tate1d99c392017-12-07 16:54:04 -0800651
652 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800653 }
654
Christopher Tatee0a22b32013-07-11 14:43:13 -0700655 static long convertToElapsed(long when, int type) {
656 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
657 if (isRtc) {
658 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
659 }
660 return when;
661 }
662
663 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
664 // calculate the end of our nominal delivery window for the alarm.
665 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
666 // Current heuristic: batchable window is 75% of either the recurrence interval
667 // [for a periodic alarm] or of the time from now to the desired delivery time,
668 // with a minimum delay/interval of 10 seconds, under which we will simply not
669 // defer the alarm.
670 long futurity = (interval == 0)
671 ? (triggerAtTime - now)
672 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700673 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700674 futurity = 0;
675 }
676 return triggerAtTime + (long)(.75 * futurity);
677 }
678
679 // returns true if the batch was added at the head
680 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
681 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
682 if (index < 0) {
683 index = 0 - index - 1;
684 }
685 list.add(index, newBatch);
686 return (index == 0);
687 }
688
Christopher Tate385e4982013-07-23 18:22:29 -0700689 // Return the index of the matching batch, or -1 if none found.
690 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700691 final int N = mAlarmBatches.size();
692 for (int i = 0; i < N; i++) {
693 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700694 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700695 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700696 }
697 }
Christopher Tate385e4982013-07-23 18:22:29 -0700698 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699 }
700
701 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
702 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700703 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700704 rebatchAllAlarmsLocked(true);
705 }
706 }
707
708 void rebatchAllAlarmsLocked(boolean doValidate) {
709 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
710 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700711 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700712 final long nowElapsed = SystemClock.elapsedRealtime();
713 final int oldBatches = oldSet.size();
714 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
715 Batch batch = oldSet.get(batchNum);
716 final int N = batch.size();
717 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700718 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700719 }
720 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700721 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
722 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
723 + " to " + mPendingIdleUntil);
724 if (mPendingIdleUntil == null) {
725 // Somehow we lost this... we need to restore all of the pending alarms.
726 restorePendingWhileIdleAlarmsLocked();
727 }
728 }
729 rescheduleKernelAlarmsLocked();
730 updateNextAlarmClockLocked();
731 }
732
733 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
734 a.when = a.origWhen;
735 long whenElapsed = convertToElapsed(a.when, a.type);
736 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700737 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700738 // Exact
739 maxElapsed = whenElapsed;
740 } else {
741 // Not exact. Preserve any explicit window, otherwise recalculate
742 // the window based on the alarm's new futurity. Note that this
743 // reflects a policy of preferring timely to deferred delivery.
744 maxElapsed = (a.windowLength > 0)
745 ? (whenElapsed + a.windowLength)
746 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
747 }
748 a.whenElapsed = whenElapsed;
749 a.maxWhenElapsed = maxElapsed;
750 setImplLocked(a, true, doValidate);
751 }
752
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700753 /**
754 * Sends alarms that were blocked due to user applied background restrictions - either because
755 * the user lifted those or the uid came to foreground.
756 *
757 * @param uid uid to filter on
758 * @param packageName package to filter on, or null for all packages in uid
759 */
760 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
761 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
762 if (alarmsForUid == null || alarmsForUid.size() == 0) {
763 return;
764 }
765 final ArrayList<Alarm> alarmsToDeliver;
766 if (packageName != null) {
767 if (DEBUG_BG_LIMIT) {
768 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
769 }
770 alarmsToDeliver = new ArrayList<>();
771 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
772 final Alarm a = alarmsForUid.get(i);
773 if (a.matches(packageName)) {
774 alarmsToDeliver.add(alarmsForUid.remove(i));
775 }
776 }
777 if (alarmsForUid.size() == 0) {
778 mPendingBackgroundAlarms.remove(uid);
779 }
780 } else {
781 if (DEBUG_BG_LIMIT) {
782 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
783 }
784 alarmsToDeliver = alarmsForUid;
785 mPendingBackgroundAlarms.remove(uid);
786 }
787 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
788 }
789
Makoto Onuki2206af32017-11-21 16:25:35 -0800790 /**
791 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
792 * restricted.
793 *
794 * This is only called when the global "force all apps-standby" flag changes or when the
795 * power save whitelist changes, so it's okay to be slow.
796 */
797 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700798 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800799
800 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
801 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
802
803 if (alarmsToDeliver.size() > 0) {
804 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
805 }
806 }
807
808 @VisibleForTesting
809 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
810 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
811 Predicate<Alarm> isBackgroundRestricted) {
812
813 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
814 final int uid = pendingAlarms.keyAt(uidIndex);
815 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
816
817 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
818 final Alarm alarm = alarmsForUid.get(alarmIndex);
819
820 if (isBackgroundRestricted.test(alarm)) {
821 continue;
822 }
823
824 unrestrictedAlarms.add(alarm);
825 alarmsForUid.remove(alarmIndex);
826 }
827
828 if (alarmsForUid.size() == 0) {
829 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700830 }
831 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700832 }
833
834 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
835 final int N = alarms.size();
836 boolean hasWakeup = false;
837 for (int i = 0; i < N; i++) {
838 final Alarm alarm = alarms.get(i);
839 if (alarm.wakeup) {
840 hasWakeup = true;
841 }
842 alarm.count = 1;
843 // Recurring alarms may have passed several alarm intervals while the
844 // alarm was kept pending. Send the appropriate trigger count.
845 if (alarm.repeatInterval > 0) {
846 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
847 // Also schedule its next recurrence
848 final long delta = alarm.count * alarm.repeatInterval;
849 final long nextElapsed = alarm.whenElapsed + delta;
850 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
851 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
852 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
853 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
854 // Kernel alarms will be rescheduled as needed in setImplLocked
855 }
856 }
857 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
858 // No need to wakeup for non wakeup alarms
859 if (mPendingNonWakeupAlarms.size() == 0) {
860 mStartCurrentDelayTime = nowELAPSED;
861 mNextNonWakeupDeliveryTime = nowELAPSED
862 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
863 }
864 mPendingNonWakeupAlarms.addAll(alarms);
865 mNumDelayedAlarms += alarms.size();
866 } else {
867 if (DEBUG_BG_LIMIT) {
868 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
869 }
870 // Since we are waking up, also deliver any pending non wakeup alarms we have.
871 if (mPendingNonWakeupAlarms.size() > 0) {
872 alarms.addAll(mPendingNonWakeupAlarms);
873 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
874 mTotalDelayTime += thisDelayTime;
875 if (mMaxDelayTime < thisDelayTime) {
876 mMaxDelayTime = thisDelayTime;
877 }
878 mPendingNonWakeupAlarms.clear();
879 }
880 calculateDeliveryPriorities(alarms);
881 Collections.sort(alarms, mAlarmDispatchComparator);
882 deliverAlarmsLocked(alarms, nowELAPSED);
883 }
884 }
885
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700886 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700887 if (RECORD_DEVICE_IDLE_ALARMS) {
888 IdleDispatchEntry ent = new IdleDispatchEntry();
889 ent.uid = 0;
890 ent.pkg = "FINISH IDLE";
891 ent.elapsedRealtime = SystemClock.elapsedRealtime();
892 mAllowWhileIdleDispatches.add(ent);
893 }
894
Dianne Hackborn35d54032015-04-23 10:30:43 -0700895 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700896 if (mPendingWhileIdleAlarms.size() > 0) {
897 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
898 mPendingWhileIdleAlarms = new ArrayList<>();
899 final long nowElapsed = SystemClock.elapsedRealtime();
900 for (int i=alarms.size() - 1; i >= 0; i--) {
901 Alarm a = alarms.get(i);
902 reAddAlarmLocked(a, nowElapsed, false);
903 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700904 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700905
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700906 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700907 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700908
Dianne Hackborn35d54032015-04-23 10:30:43 -0700909 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700910 rescheduleKernelAlarmsLocked();
911 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700912
913 // And send a TIME_TICK right now, since it is important to get the UI updated.
914 try {
915 mTimeTickSender.send();
916 } catch (PendingIntent.CanceledException e) {
917 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700918 }
919
Christopher Tate14a7bb02015-10-01 10:24:31 -0700920 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800921 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700922 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700923 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700924 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700925 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700926 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800927 final BroadcastStats mBroadcastStats;
928 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800929 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800930
Christopher Tate14a7bb02015-10-01 10:24:31 -0700931 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
932 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
933 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800934 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700935 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700936 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700937 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700938 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700939 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700940 mBroadcastStats = (pendingIntent != null)
941 ? service.getStatsLocked(pendingIntent)
942 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700943 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800944 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700945 fs = new FilterStats(mBroadcastStats, mTag);
946 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800947 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700948 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800949 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800950 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800951 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800952
953 @Override
954 public String toString() {
955 return "InFlight{"
956 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -0700957 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -0800958 + ", workSource=" + mWorkSource
959 + ", uid=" + mUid
960 + ", tag=" + mTag
961 + ", broadcastStats=" + mBroadcastStats
962 + ", filterStats=" + mFilterStats
963 + ", alarmType=" + mAlarmType
964 + "}";
965 }
Kweku Adams61e03292017-10-19 14:27:12 -0700966
967 public void writeToProto(ProtoOutputStream proto, long fieldId) {
968 final long token = proto.start(fieldId);
969
970 proto.write(InFlightProto.UID, mUid);
971 proto.write(InFlightProto.TAG, mTag);
972 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
973 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
974 if (mPendingIntent != null) {
975 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
976 }
977 if (mBroadcastStats != null) {
978 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
979 }
980 if (mFilterStats != null) {
981 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
982 }
983 if (mWorkSource != null) {
984 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
985 }
986
987 proto.end(token);
988 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800990
Adam Lesinski182f73f2013-12-05 16:48:06 -0800991 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800992 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700993 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800994
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700995 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -0800997 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 int numWakeup;
999 long startTime;
1000 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001001
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001002 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001003 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001004 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001005 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001006
1007 @Override
1008 public String toString() {
1009 return "FilterStats{"
1010 + "tag=" + mTag
1011 + ", lastTime=" + lastTime
1012 + ", aggregateTime=" + aggregateTime
1013 + ", count=" + count
1014 + ", numWakeup=" + numWakeup
1015 + ", startTime=" + startTime
1016 + ", nesting=" + nesting
1017 + "}";
1018 }
Kweku Adams61e03292017-10-19 14:27:12 -07001019
1020 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1021 final long token = proto.start(fieldId);
1022
1023 proto.write(FilterStatsProto.TAG, mTag);
1024 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1025 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1026 proto.write(FilterStatsProto.COUNT, count);
1027 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1028 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1029 proto.write(FilterStatsProto.NESTING, nesting);
1030
1031 proto.end(token);
1032 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001033 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001034
Adam Lesinski182f73f2013-12-05 16:48:06 -08001035 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001036 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001037 final String mPackageName;
1038
1039 long aggregateTime;
1040 int count;
1041 int numWakeup;
1042 long startTime;
1043 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001044 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001045
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001046 BroadcastStats(int uid, String packageName) {
1047 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001048 mPackageName = packageName;
1049 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001050
1051 @Override
1052 public String toString() {
1053 return "BroadcastStats{"
1054 + "uid=" + mUid
1055 + ", packageName=" + mPackageName
1056 + ", aggregateTime=" + aggregateTime
1057 + ", count=" + count
1058 + ", numWakeup=" + numWakeup
1059 + ", startTime=" + startTime
1060 + ", nesting=" + nesting
1061 + "}";
1062 }
Kweku Adams61e03292017-10-19 14:27:12 -07001063
1064 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1065 final long token = proto.start(fieldId);
1066
1067 proto.write(BroadcastStatsProto.UID, mUid);
1068 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1069 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1070 proto.write(BroadcastStatsProto.COUNT, count);
1071 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1072 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1073 proto.write(BroadcastStatsProto.NESTING, nesting);
1074
1075 proto.end(token);
1076 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001078
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001079 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1080 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001081
1082 int mNumDelayedAlarms = 0;
1083 long mTotalDelayTime = 0;
1084 long mMaxDelayTime = 0;
1085
Adam Lesinski182f73f2013-12-05 16:48:06 -08001086 @Override
1087 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001088 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001089 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001090
1091 // We have to set current TimeZone info to kernel
1092 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001093 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001094
Christopher Tate247571462017-04-10 11:45:05 -07001095 // Also sure that we're booting with a halfway sensible current time
1096 if (mNativeData != 0) {
1097 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1098 if (System.currentTimeMillis() < systemBuildTime) {
1099 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1100 + ", advancing to build time " + systemBuildTime);
1101 setKernelTime(mNativeData, systemBuildTime);
1102 }
1103 }
1104
Christopher Tatebb9cce52017-04-18 14:19:43 -07001105 // Determine SysUI's uid
1106 final PackageManager packMan = getContext().getPackageManager();
1107 try {
1108 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1109 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1110 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1111 mSystemUiUid = sysUi.uid;
1112 } else {
1113 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1114 + " defined by non-privileged app " + sysUi.packageName
1115 + " - ignoring");
1116 }
1117 } catch (NameNotFoundException e) {
1118 }
1119
1120 if (mSystemUiUid <= 0) {
1121 Slog.wtf(TAG, "SysUI package not found!");
1122 }
1123
Adam Lesinski182f73f2013-12-05 16:48:06 -08001124 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001125 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001126
Adam Lesinski182f73f2013-12-05 16:48:06 -08001127 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001129 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001130 | Intent.FLAG_RECEIVER_FOREGROUND
1131 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001132 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001133 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001134 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1135 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001136 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001137 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001138
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001139 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001140 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001141 mClockReceiver.scheduleTimeTickEvent();
1142 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001143 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001145
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001146 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001147 AlarmThread waitThread = new AlarmThread();
1148 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001150 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001152
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001153 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001154 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001155 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1156 | ActivityManager.UID_OBSERVER_ACTIVE,
1157 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001158 } catch (RemoteException e) {
1159 // ignored; both services live in system_server
1160 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001161 publishBinderService(Context.ALARM_SERVICE, mService);
Makoto Onuki2206af32017-11-21 16:25:35 -08001162 mForceAppStandbyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001163 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001164
1165 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001166 public void onBootPhase(int phase) {
1167 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1168 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001169 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001170 mLocalDeviceIdleController
1171 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001172 }
1173 }
1174
1175 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 protected void finalize() throws Throwable {
1177 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001178 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 } finally {
1180 super.finalize();
1181 }
1182 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001183
Adam Lesinski182f73f2013-12-05 16:48:06 -08001184 void setTimeZoneImpl(String tz) {
1185 if (TextUtils.isEmpty(tz)) {
1186 return;
David Christieebe51fc2013-07-26 13:23:29 -07001187 }
1188
Adam Lesinski182f73f2013-12-05 16:48:06 -08001189 TimeZone zone = TimeZone.getTimeZone(tz);
1190 // Prevent reentrant calls from stepping on each other when writing
1191 // the time zone property
1192 boolean timeZoneWasChanged = false;
1193 synchronized (this) {
1194 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1195 if (current == null || !current.equals(zone.getID())) {
1196 if (localLOGV) {
1197 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1198 }
1199 timeZoneWasChanged = true;
1200 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1201 }
1202
1203 // Update the kernel timezone information
1204 // Kernel tracks time offsets as 'minutes west of GMT'
1205 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001206 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001207 }
1208
1209 TimeZone.setDefault(null);
1210
1211 if (timeZoneWasChanged) {
1212 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001213 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001214 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001215 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001216 intent.putExtra("time-zone", zone.getID());
1217 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1218 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001220
Adam Lesinski182f73f2013-12-05 16:48:06 -08001221 void removeImpl(PendingIntent operation) {
1222 if (operation == null) {
1223 return;
1224 }
1225 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001226 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001227 }
1228 }
1229
1230 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001231 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1232 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1233 int callingUid, String callingPackage) {
1234 // must be *either* PendingIntent or AlarmReceiver, but not both
1235 if ((operation == null && directReceiver == null)
1236 || (operation != null && directReceiver != null)) {
1237 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1238 // NB: previous releases failed silently here, so we are continuing to do the same
1239 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001240 return;
1241 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001242
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001243 // Sanity check the window length. This will catch people mistakenly
1244 // trying to pass an end-of-window timestamp rather than a duration.
1245 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1246 Slog.w(TAG, "Window length " + windowLength
1247 + "ms suspiciously long; limiting to 1 hour");
1248 windowLength = AlarmManager.INTERVAL_HOUR;
1249 }
1250
Christopher Tate498c6cb2014-11-17 16:09:27 -08001251 // Sanity check the recurrence interval. This will catch people who supply
1252 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001253 final long minInterval = mConstants.MIN_INTERVAL;
1254 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001255 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001256 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001257 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001258 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001259 }
1260
Christopher Tatee0a22b32013-07-11 14:43:13 -07001261 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1262 throw new IllegalArgumentException("Invalid alarm type " + type);
1263 }
1264
Christopher Tate5f221e82013-07-30 17:13:15 -07001265 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001266 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001267 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001268 + " pid=" + what);
1269 triggerAtTime = 0;
1270 }
1271
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001272 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001273 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1274 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001275 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001276 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1277
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001278 final long maxElapsed;
1279 if (windowLength == AlarmManager.WINDOW_EXACT) {
1280 maxElapsed = triggerElapsed;
1281 } else if (windowLength < 0) {
1282 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001283 // Fix this window in place, so that as time approaches we don't collapse it.
1284 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001285 } else {
1286 maxElapsed = triggerElapsed + windowLength;
1287 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001290 if (DEBUG_BATCH) {
1291 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001292 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001293 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001294 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001296 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001297 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1298 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 }
1300 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001301
Christopher Tate3e04b472013-10-21 17:51:31 -07001302 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001303 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1304 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1305 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001306 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001307 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1308 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001309 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001310 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001311 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1312 + " -- package not allowed to start");
1313 return;
1314 }
1315 } catch (RemoteException e) {
1316 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001317 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001318 setImplLocked(a, false, doValidate);
1319 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001320
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001321 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1322 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001323 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001324 // The caller has given the time they want this to happen at, however we need
1325 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001326 // bring us out of idle at an earlier time.
1327 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001328 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001329 }
1330 // Add fuzz to make the alarm go off some time before the actual desired time.
1331 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001332 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001333 if (fuzz > 0) {
1334 if (mRandom == null) {
1335 mRandom = new Random();
1336 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001337 final int delta = mRandom.nextInt(fuzz);
1338 a.whenElapsed -= delta;
1339 if (false) {
1340 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1341 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1342 Slog.d(TAG, "Applied fuzz: " + fuzz);
1343 Slog.d(TAG, "Final delta: " + delta);
1344 Slog.d(TAG, "Final when: " + a.whenElapsed);
1345 }
1346 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001347 }
1348
1349 } else if (mPendingIdleUntil != null) {
1350 // We currently have an idle until alarm scheduled; if the new alarm has
1351 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001352 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1353 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1354 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001355 == 0) {
1356 mPendingWhileIdleAlarms.add(a);
1357 return;
1358 }
1359 }
1360
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001361 if (RECORD_DEVICE_IDLE_ALARMS) {
1362 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1363 IdleDispatchEntry ent = new IdleDispatchEntry();
1364 ent.uid = a.uid;
1365 ent.pkg = a.operation.getCreatorPackage();
1366 ent.tag = a.operation.getTag("");
1367 ent.op = "SET";
1368 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1369 ent.argRealtime = a.whenElapsed;
1370 mAllowWhileIdleDispatches.add(ent);
1371 }
1372 }
1373
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001374 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1375 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001376 if (whichBatch < 0) {
1377 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001378 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001380 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001381 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001382 // The start time of this batch advanced, so batch ordering may
1383 // have just been broken. Move it to where it now belongs.
1384 mAlarmBatches.remove(whichBatch);
1385 addBatchLocked(mAlarmBatches, batch);
1386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 }
1388
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001389 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001390 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001391 }
1392
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001393 boolean needRebatch = false;
1394
1395 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001396 if (RECORD_DEVICE_IDLE_ALARMS) {
1397 if (mPendingIdleUntil == null) {
1398 IdleDispatchEntry ent = new IdleDispatchEntry();
1399 ent.uid = 0;
1400 ent.pkg = "START IDLE";
1401 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1402 mAllowWhileIdleDispatches.add(ent);
1403 }
1404 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001405 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1406 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1407 + " to " + a);
1408 }
1409
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001410 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001411 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001412 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001413 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1414 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1415 mNextWakeFromIdle = a;
1416 // If this wake from idle is earlier than whatever was previously scheduled,
1417 // and we are currently idling, then we need to rebatch alarms in case the idle
1418 // until time needs to be updated.
1419 if (mPendingIdleUntil != null) {
1420 needRebatch = true;
1421 }
1422 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001423 }
1424
1425 if (!rebatching) {
1426 if (DEBUG_VALIDATE) {
1427 if (doValidate && !validateConsistencyLocked()) {
1428 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1429 + " when(hex)=" + Long.toHexString(a.when)
1430 + " whenElapsed=" + a.whenElapsed
1431 + " maxWhenElapsed=" + a.maxWhenElapsed
1432 + " interval=" + a.repeatInterval + " op=" + a.operation
1433 + " flags=0x" + Integer.toHexString(a.flags));
1434 rebatchAllAlarmsLocked(false);
1435 needRebatch = false;
1436 }
1437 }
1438
1439 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001440 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001441 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001442
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001443 rescheduleKernelAlarmsLocked();
1444 updateNextAlarmClockLocked();
1445 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001446 }
1447
Christopher Tate1d99c392017-12-07 16:54:04 -08001448 /**
1449 * System-process internal API
1450 */
1451 private final class LocalService implements AlarmManagerInternal {
1452 @Override
1453 public void removeAlarmsForUid(int uid) {
1454 synchronized (mLock) {
1455 removeLocked(uid);
1456 }
1457 }
1458 }
1459
1460 /**
1461 * Public-facing binder interface
1462 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001463 private final IBinder mService = new IAlarmManager.Stub() {
1464 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001465 public void set(String callingPackage,
1466 int type, long triggerAtTime, long windowLength, long interval, int flags,
1467 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1468 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001469 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001470
1471 // make sure the caller is not lying about which package should be blamed for
1472 // wakelock time spent in alarm delivery
1473 mAppOps.checkPackage(callingUid, callingPackage);
1474
1475 // Repeating alarms must use PendingIntent, not direct listener
1476 if (interval != 0) {
1477 if (directReceiver != null) {
1478 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1479 }
1480 }
1481
Adam Lesinski182f73f2013-12-05 16:48:06 -08001482 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001483 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001484 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001485 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001486 }
1487
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001488 // No incoming callers can request either WAKE_FROM_IDLE or
1489 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1490 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1491 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1492
1493 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1494 // manager when to come out of idle mode, which is only for DeviceIdleController.
1495 if (callingUid != Process.SYSTEM_UID) {
1496 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1497 }
1498
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001499 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001500 if (windowLength == AlarmManager.WINDOW_EXACT) {
1501 flags |= AlarmManager.FLAG_STANDALONE;
1502 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001503
1504 // If this alarm is for an alarm clock, then it must be standalone and we will
1505 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001506 if (alarmClock != null) {
1507 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001508
1509 // If the caller is a core system component or on the user's whitelist, and not calling
1510 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1511 // This means we will allow these alarms to go off as normal even while idle, with no
1512 // timing restrictions.
1513 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001514 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001515 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001516 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1517 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001518 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001519
Christopher Tate14a7bb02015-10-01 10:24:31 -07001520 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1521 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001522 }
Christopher Tate89779822012-08-31 14:40:03 -07001523
Adam Lesinski182f73f2013-12-05 16:48:06 -08001524 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001525 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001526 getContext().enforceCallingOrSelfPermission(
1527 "android.permission.SET_TIME",
1528 "setTime");
1529
Greg Hackmann0cab8962014-02-21 16:35:52 -08001530 if (mNativeData == 0) {
1531 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1532 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001533 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001534
1535 synchronized (mLock) {
1536 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001539
1540 @Override
1541 public void setTimeZone(String tz) {
1542 getContext().enforceCallingOrSelfPermission(
1543 "android.permission.SET_TIME_ZONE",
1544 "setTimeZone");
1545
1546 final long oldId = Binder.clearCallingIdentity();
1547 try {
1548 setTimeZoneImpl(tz);
1549 } finally {
1550 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001551 }
1552 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001553
Adam Lesinski182f73f2013-12-05 16:48:06 -08001554 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001555 public void remove(PendingIntent operation, IAlarmListener listener) {
1556 if (operation == null && listener == null) {
1557 Slog.w(TAG, "remove() with no intent or listener");
1558 return;
1559 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001560
Christopher Tate14a7bb02015-10-01 10:24:31 -07001561 synchronized (mLock) {
1562 removeLocked(operation, listener);
1563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001565
Adam Lesinski182f73f2013-12-05 16:48:06 -08001566 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001567 public long getNextWakeFromIdleTime() {
1568 return getNextWakeFromIdleTimeImpl();
1569 }
1570
1571 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001572 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001573 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1574 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1575 "getNextAlarmClock", null);
1576
1577 return getNextAlarmClockImpl(userId);
1578 }
1579
1580 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001581 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001582 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001583
1584 if (args.length > 0 && "--proto".equals(args[0])) {
1585 dumpProto(fd);
1586 } else {
1587 dumpImpl(pw);
1588 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001589 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001590 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001591
Adam Lesinski182f73f2013-12-05 16:48:06 -08001592 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001593 synchronized (mLock) {
1594 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001595 mConstants.dump(pw);
1596 pw.println();
1597
Makoto Onuki2206af32017-11-21 16:25:35 -08001598 mForceAppStandbyTracker.dump(pw, " ");
1599
Christopher Tatee0a22b32013-07-11 14:43:13 -07001600 final long nowRTC = System.currentTimeMillis();
1601 final long nowELAPSED = SystemClock.elapsedRealtime();
1602 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1603
Dianne Hackborna750a632015-06-16 17:18:23 -07001604 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001605 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001606 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001607 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001608 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001609 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001610 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001611 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1612 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001613 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001614 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001615 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1616 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001617 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001618 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1619 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001620 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001621 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1622 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001623 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001624 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1625 pw.println();
1626 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001627
1628 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1629 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001630 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001631 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001632 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001633 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001634 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001635 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1636 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1637 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001638 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001639
John Spurlock604a5ee2015-06-01 12:27:22 -04001640 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001641 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001642 final TreeSet<Integer> users = new TreeSet<>();
1643 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1644 users.add(mNextAlarmClockForUser.keyAt(i));
1645 }
1646 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1647 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1648 }
1649 for (int user : users) {
1650 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1651 final long time = next != null ? next.getTriggerTime() : 0;
1652 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001653 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001654 pw.print(" pendingSend:"); pw.print(pendingSend);
1655 pw.print(" time:"); pw.print(time);
1656 if (time > 0) {
1657 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1658 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1659 }
1660 pw.println();
1661 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001662 if (mAlarmBatches.size() > 0) {
1663 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001664 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001665 pw.println(mAlarmBatches.size());
1666 for (Batch b : mAlarmBatches) {
1667 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001668 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001669 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001671 pw.println();
1672 pw.println(" Pending user blocked background alarms: ");
1673 boolean blocked = false;
1674 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1675 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1676 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1677 blocked = true;
1678 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1679 }
1680 }
1681 if (!blocked) {
1682 pw.println(" none");
1683 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001684 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001685 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001686 pw.println(" Idle mode state:");
1687 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001688 if (mPendingIdleUntil != null) {
1689 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001690 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001691 } else {
1692 pw.println("null");
1693 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001694 pw.println(" Pending alarms:");
1695 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001696 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001697 if (mNextWakeFromIdle != null) {
1698 pw.println();
1699 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001700 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001701 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001702
1703 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001704 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001705 if (mPendingNonWakeupAlarms.size() > 0) {
1706 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001707 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001708 } else {
1709 pw.println("(none)");
1710 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001711 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001712 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1713 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001714 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001715 pw.print(", max non-interactive time: ");
1716 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1717 pw.println();
1718
1719 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001720 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001721 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1722 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1723 pw.print(" Listener send count: "); pw.println(mListenerCount);
1724 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001725 pw.println();
1726
Christopher Tate7f2a0352015-12-08 10:24:33 -08001727 if (mInFlight.size() > 0) {
1728 pw.println("Outstanding deliveries:");
1729 for (int i = 0; i < mInFlight.size(); i++) {
1730 pw.print(" #"); pw.print(i); pw.print(": ");
1731 pw.println(mInFlight.get(i));
1732 }
1733 pw.println();
1734 }
1735
Dianne Hackborna750a632015-06-16 17:18:23 -07001736 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001737 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1738 pw.println();
1739 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001740 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001741 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1742 pw.print(" UID ");
1743 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1744 pw.print(": ");
1745 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1746 nowELAPSED, pw);
1747 pw.println();
1748 }
1749 }
1750 pw.println();
1751
Dianne Hackborn81038902012-11-26 17:04:09 -08001752 if (mLog.dump(pw, " Recent problems", " ")) {
1753 pw.println();
1754 }
1755
1756 final FilterStats[] topFilters = new FilterStats[10];
1757 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1758 @Override
1759 public int compare(FilterStats lhs, FilterStats rhs) {
1760 if (lhs.aggregateTime < rhs.aggregateTime) {
1761 return 1;
1762 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1763 return -1;
1764 }
1765 return 0;
1766 }
1767 };
1768 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001769 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001770 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1771 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1772 for (int ip=0; ip<uidStats.size(); ip++) {
1773 BroadcastStats bs = uidStats.valueAt(ip);
1774 for (int is=0; is<bs.filterStats.size(); is++) {
1775 FilterStats fs = bs.filterStats.valueAt(is);
1776 int pos = len > 0
1777 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1778 if (pos < 0) {
1779 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001780 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001781 if (pos < topFilters.length) {
1782 int copylen = topFilters.length - pos - 1;
1783 if (copylen > 0) {
1784 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1785 }
1786 topFilters[pos] = fs;
1787 if (len < topFilters.length) {
1788 len++;
1789 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001790 }
1791 }
1792 }
1793 }
1794 if (len > 0) {
1795 pw.println(" Top Alarms:");
1796 for (int i=0; i<len; i++) {
1797 FilterStats fs = topFilters[i];
1798 pw.print(" ");
1799 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1800 TimeUtils.formatDuration(fs.aggregateTime, pw);
1801 pw.print(" running, "); pw.print(fs.numWakeup);
1802 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001803 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1804 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001805 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001806 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001807 pw.println();
1808 }
1809 }
1810
1811 pw.println(" ");
1812 pw.println(" Alarm Stats:");
1813 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001814 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1815 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1816 for (int ip=0; ip<uidStats.size(); ip++) {
1817 BroadcastStats bs = uidStats.valueAt(ip);
1818 pw.print(" ");
1819 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1820 UserHandle.formatUid(pw, bs.mUid);
1821 pw.print(":");
1822 pw.print(bs.mPackageName);
1823 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1824 pw.print(" running, "); pw.print(bs.numWakeup);
1825 pw.println(" wakeups:");
1826 tmpFilters.clear();
1827 for (int is=0; is<bs.filterStats.size(); is++) {
1828 tmpFilters.add(bs.filterStats.valueAt(is));
1829 }
1830 Collections.sort(tmpFilters, comparator);
1831 for (int i=0; i<tmpFilters.size(); i++) {
1832 FilterStats fs = tmpFilters.get(i);
1833 pw.print(" ");
1834 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1835 TimeUtils.formatDuration(fs.aggregateTime, pw);
1836 pw.print(" "); pw.print(fs.numWakeup);
1837 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001838 pw.print(" alarms, last ");
1839 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1840 pw.println(":");
1841 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001842 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001843 pw.println();
1844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001847
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001848 if (RECORD_DEVICE_IDLE_ALARMS) {
1849 pw.println();
1850 pw.println(" Allow while idle dispatches:");
1851 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1852 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1853 pw.print(" ");
1854 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1855 pw.print(": ");
1856 UserHandle.formatUid(pw, ent.uid);
1857 pw.print(":");
1858 pw.println(ent.pkg);
1859 if (ent.op != null) {
1860 pw.print(" ");
1861 pw.print(ent.op);
1862 pw.print(" / ");
1863 pw.print(ent.tag);
1864 if (ent.argRealtime != 0) {
1865 pw.print(" (");
1866 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1867 pw.print(")");
1868 }
1869 pw.println();
1870 }
1871 }
1872 }
1873
Christopher Tate18a75f12013-07-01 18:18:59 -07001874 if (WAKEUP_STATS) {
1875 pw.println();
1876 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001877 long last = -1;
1878 for (WakeupEvent event : mRecentWakeups) {
1879 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1880 pw.print('|');
1881 if (last < 0) {
1882 pw.print('0');
1883 } else {
1884 pw.print(event.when - last);
1885 }
1886 last = event.when;
1887 pw.print('|'); pw.print(event.uid);
1888 pw.print('|'); pw.print(event.action);
1889 pw.println();
1890 }
1891 pw.println();
1892 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
1894 }
1895
Kweku Adams61e03292017-10-19 14:27:12 -07001896 void dumpProto(FileDescriptor fd) {
1897 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1898
1899 synchronized (mLock) {
1900 final long nowRTC = System.currentTimeMillis();
1901 final long nowElapsed = SystemClock.elapsedRealtime();
1902 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1903 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1904 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1905 mLastTimeChangeClockTime);
1906 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
1907 mLastTimeChangeRealtime);
1908
1909 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
1910
Makoto Onuki2206af32017-11-21 16:25:35 -08001911 mForceAppStandbyTracker.dumpProto(proto,
1912 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07001913
1914 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
1915 if (!mInteractive) {
1916 // Durations
1917 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
1918 nowElapsed - mNonInteractiveStartTime);
1919 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
1920 currentNonWakeupFuzzLocked(nowElapsed));
1921 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
1922 nowElapsed - mLastAlarmDeliveryTime);
1923 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
1924 nowElapsed - mNextNonWakeupDeliveryTime);
1925 }
1926
1927 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
1928 mNextNonWakeup - nowElapsed);
1929 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
1930 mNextWakeup - nowElapsed);
1931 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
1932 nowElapsed - mLastWakeup);
1933 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
1934 nowElapsed - mLastWakeupSet);
1935 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07001936
1937 final TreeSet<Integer> users = new TreeSet<>();
1938 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
1939 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
1940 users.add(mNextAlarmClockForUser.keyAt(i));
1941 }
1942 final int pendingSendNextAlarmClockChangedForUserSize =
1943 mPendingSendNextAlarmClockChangedForUser.size();
1944 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
1945 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1946 }
1947 for (int user : users) {
1948 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1949 final long time = next != null ? next.getTriggerTime() : 0;
1950 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
1951 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
1952 proto.write(AlarmClockMetadataProto.USER, user);
1953 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
1954 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
1955 proto.end(aToken);
1956 }
1957 for (Batch b : mAlarmBatches) {
1958 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
1959 nowElapsed, nowRTC);
1960 }
1961 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1962 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1963 if (blockedAlarms != null) {
1964 for (Alarm a : blockedAlarms) {
1965 a.writeToProto(proto,
1966 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
1967 nowElapsed, nowRTC);
1968 }
1969 }
1970 }
1971 if (mPendingIdleUntil != null) {
1972 mPendingIdleUntil.writeToProto(
1973 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
1974 }
1975 for (Alarm a : mPendingWhileIdleAlarms) {
1976 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
1977 nowElapsed, nowRTC);
1978 }
1979 if (mNextWakeFromIdle != null) {
1980 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
1981 nowElapsed, nowRTC);
1982 }
1983
1984 for (Alarm a : mPendingNonWakeupAlarms) {
1985 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
1986 nowElapsed, nowRTC);
1987 }
1988
1989 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
1990 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
1991 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
1992 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
1993 mNonInteractiveTime);
1994
1995 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
1996 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
1997 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
1998 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
1999 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2000
2001 for (InFlight f : mInFlight) {
2002 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2003 }
2004
2005 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2006 mAllowWhileIdleMinTime);
2007 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2008 final long token = proto.start(
2009 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2010 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2011 mLastAllowWhileIdleDispatch.keyAt(i));
2012 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2013 mLastAllowWhileIdleDispatch.valueAt(i));
2014 proto.end(token);
2015 }
2016
2017 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2018
2019 final FilterStats[] topFilters = new FilterStats[10];
2020 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2021 @Override
2022 public int compare(FilterStats lhs, FilterStats rhs) {
2023 if (lhs.aggregateTime < rhs.aggregateTime) {
2024 return 1;
2025 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2026 return -1;
2027 }
2028 return 0;
2029 }
2030 };
2031 int len = 0;
2032 // Get the top 10 FilterStats, ordered by aggregateTime.
2033 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2034 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2035 for (int ip = 0; ip < uidStats.size(); ++ip) {
2036 BroadcastStats bs = uidStats.valueAt(ip);
2037 for (int is = 0; is < bs.filterStats.size(); ++is) {
2038 FilterStats fs = bs.filterStats.valueAt(is);
2039 int pos = len > 0
2040 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2041 if (pos < 0) {
2042 pos = -pos - 1;
2043 }
2044 if (pos < topFilters.length) {
2045 int copylen = topFilters.length - pos - 1;
2046 if (copylen > 0) {
2047 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2048 }
2049 topFilters[pos] = fs;
2050 if (len < topFilters.length) {
2051 len++;
2052 }
2053 }
2054 }
2055 }
2056 }
2057 for (int i = 0; i < len; ++i) {
2058 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2059 FilterStats fs = topFilters[i];
2060
2061 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2062 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2063 fs.mBroadcastStats.mPackageName);
2064 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2065
2066 proto.end(token);
2067 }
2068
2069 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2070 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2071 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2072 for (int ip = 0; ip < uidStats.size(); ++ip) {
2073 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2074
2075 BroadcastStats bs = uidStats.valueAt(ip);
2076 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2077
2078 // uidStats is an ArrayMap, which we can't sort.
2079 tmpFilters.clear();
2080 for (int is = 0; is < bs.filterStats.size(); ++is) {
2081 tmpFilters.add(bs.filterStats.valueAt(is));
2082 }
2083 Collections.sort(tmpFilters, comparator);
2084 for (FilterStats fs : tmpFilters) {
2085 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2086 }
2087
2088 proto.end(token);
2089 }
2090 }
2091
2092 if (RECORD_DEVICE_IDLE_ALARMS) {
2093 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2094 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2095 final long token = proto.start(
2096 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2097
2098 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2099 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2100 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2101 proto.write(IdleDispatchEntryProto.OP, ent.op);
2102 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2103 ent.elapsedRealtime);
2104 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2105
2106 proto.end(token);
2107 }
2108 }
2109
2110 if (WAKEUP_STATS) {
2111 for (WakeupEvent event : mRecentWakeups) {
2112 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2113 proto.write(WakeupEventProto.UID, event.uid);
2114 proto.write(WakeupEventProto.ACTION, event.action);
2115 proto.write(WakeupEventProto.WHEN, event.when);
2116 proto.end(token);
2117 }
2118 }
2119 }
2120
2121 proto.flush();
2122 }
2123
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002124 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002125 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2126 PrintWriter pw = new PrintWriter(bs);
2127 final long nowRTC = System.currentTimeMillis();
2128 final long nowELAPSED = SystemClock.elapsedRealtime();
2129 final int NZ = mAlarmBatches.size();
2130 for (int iz = 0; iz < NZ; iz++) {
2131 Batch bz = mAlarmBatches.get(iz);
2132 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002133 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002134 pw.flush();
2135 Slog.v(TAG, bs.toString());
2136 bs.reset();
2137 }
2138 }
2139
2140 private boolean validateConsistencyLocked() {
2141 if (DEBUG_VALIDATE) {
2142 long lastTime = Long.MIN_VALUE;
2143 final int N = mAlarmBatches.size();
2144 for (int i = 0; i < N; i++) {
2145 Batch b = mAlarmBatches.get(i);
2146 if (b.start >= lastTime) {
2147 // duplicate start times are okay because of standalone batches
2148 lastTime = b.start;
2149 } else {
2150 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002151 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2152 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002153 return false;
2154 }
2155 }
2156 }
2157 return true;
2158 }
2159
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002160 private Batch findFirstWakeupBatchLocked() {
2161 final int N = mAlarmBatches.size();
2162 for (int i = 0; i < N; i++) {
2163 Batch b = mAlarmBatches.get(i);
2164 if (b.hasWakeups()) {
2165 return b;
2166 }
2167 }
2168 return null;
2169 }
2170
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002171 long getNextWakeFromIdleTimeImpl() {
2172 synchronized (mLock) {
2173 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2174 }
2175 }
2176
2177 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002178 synchronized (mLock) {
2179 return mNextAlarmClockForUser.get(userId);
2180 }
2181 }
2182
2183 /**
2184 * Recomputes the next alarm clock for all users.
2185 */
2186 private void updateNextAlarmClockLocked() {
2187 if (!mNextAlarmClockMayChange) {
2188 return;
2189 }
2190 mNextAlarmClockMayChange = false;
2191
Jose Lima235510e2014-08-13 12:50:01 -07002192 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002193 nextForUser.clear();
2194
2195 final int N = mAlarmBatches.size();
2196 for (int i = 0; i < N; i++) {
2197 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2198 final int M = alarms.size();
2199
2200 for (int j = 0; j < M; j++) {
2201 Alarm a = alarms.get(j);
2202 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002203 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002204 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002205
2206 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002207 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002208 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002209 " for user " + userId);
2210 }
2211
2212 // Alarms and batches are sorted by time, no need to compare times here.
2213 if (nextForUser.get(userId) == null) {
2214 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002215 } else if (a.alarmClock.equals(current)
2216 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2217 // same/earlier time and it's the one we cited before, so stick with it
2218 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002219 }
2220 }
2221 }
2222 }
2223
2224 // Update mNextAlarmForUser with new values.
2225 final int NN = nextForUser.size();
2226 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002227 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002228 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002229 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002230 if (!newAlarm.equals(currentAlarm)) {
2231 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2232 }
2233 }
2234
2235 // Remove users without any alarm clocks scheduled.
2236 final int NNN = mNextAlarmClockForUser.size();
2237 for (int i = NNN - 1; i >= 0; i--) {
2238 int userId = mNextAlarmClockForUser.keyAt(i);
2239 if (nextForUser.get(userId) == null) {
2240 updateNextAlarmInfoForUserLocked(userId, null);
2241 }
2242 }
2243 }
2244
Jose Lima235510e2014-08-13 12:50:01 -07002245 private void updateNextAlarmInfoForUserLocked(int userId,
2246 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002247 if (alarmClock != null) {
2248 if (DEBUG_ALARM_CLOCK) {
2249 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002250 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002251 }
2252 mNextAlarmClockForUser.put(userId, alarmClock);
2253 } else {
2254 if (DEBUG_ALARM_CLOCK) {
2255 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2256 }
2257 mNextAlarmClockForUser.remove(userId);
2258 }
2259
2260 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2261 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2262 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2263 }
2264
2265 /**
2266 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2267 * for which alarm clocks have changed since the last call to this.
2268 *
2269 * Do not call with a lock held. Only call from mHandler's thread.
2270 *
2271 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2272 */
2273 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002274 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002275 pendingUsers.clear();
2276
2277 synchronized (mLock) {
2278 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2279 for (int i = 0; i < N; i++) {
2280 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2281 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2282 }
2283 mPendingSendNextAlarmClockChangedForUser.clear();
2284 }
2285
2286 final int N = pendingUsers.size();
2287 for (int i = 0; i < N; i++) {
2288 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002289 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002290 Settings.System.putStringForUser(getContext().getContentResolver(),
2291 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002292 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002293 userId);
2294
2295 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2296 new UserHandle(userId));
2297 }
2298 }
2299
2300 /**
2301 * Formats an alarm like platform/packages/apps/DeskClock used to.
2302 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002303 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2304 int userId) {
2305 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002306 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2307 return (info == null) ? "" :
2308 DateFormat.format(pattern, info.getTriggerTime()).toString();
2309 }
2310
Adam Lesinski182f73f2013-12-05 16:48:06 -08002311 void rescheduleKernelAlarmsLocked() {
2312 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2313 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002314 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002315 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002316 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002317 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002318 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002319 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002320 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002321 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002322 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002323 if (firstBatch != firstWakeup) {
2324 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002325 }
2326 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002327 if (mPendingNonWakeupAlarms.size() > 0) {
2328 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2329 nextNonWakeup = mNextNonWakeupDeliveryTime;
2330 }
2331 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002332 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002333 mNextNonWakeup = nextNonWakeup;
2334 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2335 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002336 }
2337
Christopher Tate14a7bb02015-10-01 10:24:31 -07002338 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002339 if (operation == null && directReceiver == null) {
2340 if (localLOGV) {
2341 Slog.w(TAG, "requested remove() of null operation",
2342 new RuntimeException("here"));
2343 }
2344 return;
2345 }
2346
Adam Lesinski182f73f2013-12-05 16:48:06 -08002347 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002348 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002349 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2350 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002351 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002352 if (b.size() == 0) {
2353 mAlarmBatches.remove(i);
2354 }
2355 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002356 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002357 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002358 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2359 mPendingWhileIdleAlarms.remove(i);
2360 }
2361 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002362 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2363 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2364 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2365 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2366 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2367 alarmsForUid.remove(j);
2368 }
2369 }
2370 if (alarmsForUid.size() == 0) {
2371 mPendingBackgroundAlarms.removeAt(i);
2372 }
2373 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002374 if (didRemove) {
2375 if (DEBUG_BATCH) {
2376 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2377 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002378 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002379 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002380 mPendingIdleUntil = null;
2381 restorePending = true;
2382 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002383 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002384 mNextWakeFromIdle = null;
2385 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002386 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002387 if (restorePending) {
2388 restorePendingWhileIdleAlarmsLocked();
2389 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002390 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002391 }
2392 }
2393
Christopher Tate1d99c392017-12-07 16:54:04 -08002394 void removeLocked(final int uid) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002395 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002396 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002397 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2398 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002399 didRemove |= b.remove(whichAlarms);
2400 if (b.size() == 0) {
2401 mAlarmBatches.remove(i);
2402 }
2403 }
2404 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2405 final Alarm a = mPendingWhileIdleAlarms.get(i);
2406 if (a.uid == uid) {
2407 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2408 mPendingWhileIdleAlarms.remove(i);
2409 }
2410 }
2411 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2412 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2413 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2414 if (alarmsForUid.get(j).uid == uid) {
2415 alarmsForUid.remove(j);
2416 }
2417 }
2418 if (alarmsForUid.size() == 0) {
2419 mPendingBackgroundAlarms.removeAt(i);
2420 }
2421 }
2422 if (didRemove) {
2423 if (DEBUG_BATCH) {
2424 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2425 }
2426 rebatchAllAlarmsLocked(true);
2427 rescheduleKernelAlarmsLocked();
2428 updateNextAlarmClockLocked();
2429 }
2430 }
2431
2432 void removeLocked(final String packageName) {
2433 if (packageName == null) {
2434 if (localLOGV) {
2435 Slog.w(TAG, "requested remove() of null packageName",
2436 new RuntimeException("here"));
2437 }
2438 return;
2439 }
2440
2441 boolean didRemove = false;
2442 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
2443 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2444 Batch b = mAlarmBatches.get(i);
2445 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002446 if (b.size() == 0) {
2447 mAlarmBatches.remove(i);
2448 }
2449 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002450 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002451 final Alarm a = mPendingWhileIdleAlarms.get(i);
2452 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002453 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2454 mPendingWhileIdleAlarms.remove(i);
2455 }
2456 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002457 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2458 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2459 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2460 if (alarmsForUid.get(j).matches(packageName)) {
2461 alarmsForUid.remove(j);
2462 }
2463 }
2464 if (alarmsForUid.size() == 0) {
2465 mPendingBackgroundAlarms.removeAt(i);
2466 }
2467 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002468 if (didRemove) {
2469 if (DEBUG_BATCH) {
2470 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2471 }
2472 rebatchAllAlarmsLocked(true);
2473 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002474 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002475 }
2476 }
2477
Christopher Tate1d99c392017-12-07 16:54:04 -08002478 void removeForStoppedLocked(final int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002479 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002480 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2481 try {
2482 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2483 uid, a.packageName)) {
2484 return true;
2485 }
2486 } catch (RemoteException e) { /* fall through */}
2487 return false;
2488 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002489 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2490 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002491 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002492 if (b.size() == 0) {
2493 mAlarmBatches.remove(i);
2494 }
2495 }
2496 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2497 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002498 if (a.uid == uid) {
2499 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2500 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002501 }
2502 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002503 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2504 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2505 mPendingBackgroundAlarms.removeAt(i);
2506 }
2507 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002508 if (didRemove) {
2509 if (DEBUG_BATCH) {
2510 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2511 }
2512 rebatchAllAlarmsLocked(true);
2513 rescheduleKernelAlarmsLocked();
2514 updateNextAlarmClockLocked();
2515 }
2516 }
2517
Adam Lesinski182f73f2013-12-05 16:48:06 -08002518 void removeUserLocked(int userHandle) {
2519 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002520 final Predicate<Alarm> whichAlarms =
2521 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002522 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2523 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002524 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002525 if (b.size() == 0) {
2526 mAlarmBatches.remove(i);
2527 }
2528 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002529 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002530 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002531 == userHandle) {
2532 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2533 mPendingWhileIdleAlarms.remove(i);
2534 }
2535 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002536 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2537 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2538 mPendingBackgroundAlarms.removeAt(i);
2539 }
2540 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002541 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2542 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2543 mLastAllowWhileIdleDispatch.removeAt(i);
2544 }
2545 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002546
2547 if (didRemove) {
2548 if (DEBUG_BATCH) {
2549 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2550 }
2551 rebatchAllAlarmsLocked(true);
2552 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002553 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002554 }
2555 }
2556
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002557 void interactiveStateChangedLocked(boolean interactive) {
2558 if (mInteractive != interactive) {
2559 mInteractive = interactive;
2560 final long nowELAPSED = SystemClock.elapsedRealtime();
2561 if (interactive) {
2562 if (mPendingNonWakeupAlarms.size() > 0) {
2563 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2564 mTotalDelayTime += thisDelayTime;
2565 if (mMaxDelayTime < thisDelayTime) {
2566 mMaxDelayTime = thisDelayTime;
2567 }
2568 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2569 mPendingNonWakeupAlarms.clear();
2570 }
2571 if (mNonInteractiveStartTime > 0) {
2572 long dur = nowELAPSED - mNonInteractiveStartTime;
2573 if (dur > mNonInteractiveTime) {
2574 mNonInteractiveTime = dur;
2575 }
2576 }
2577 } else {
2578 mNonInteractiveStartTime = nowELAPSED;
2579 }
2580 }
2581 }
2582
Adam Lesinski182f73f2013-12-05 16:48:06 -08002583 boolean lookForPackageLocked(String packageName) {
2584 for (int i = 0; i < mAlarmBatches.size(); i++) {
2585 Batch b = mAlarmBatches.get(i);
2586 if (b.hasPackage(packageName)) {
2587 return true;
2588 }
2589 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002590 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002591 final Alarm a = mPendingWhileIdleAlarms.get(i);
2592 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002593 return true;
2594 }
2595 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002596 return false;
2597 }
2598
2599 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002600 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002601 // The kernel never triggers alarms with negative wakeup times
2602 // so we ensure they are positive.
2603 long alarmSeconds, alarmNanoseconds;
2604 if (when < 0) {
2605 alarmSeconds = 0;
2606 alarmNanoseconds = 0;
2607 } else {
2608 alarmSeconds = when / 1000;
2609 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2610 }
Kweku Adams61e03292017-10-19 14:27:12 -07002611
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002612 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002613 } else {
2614 Message msg = Message.obtain();
2615 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002616
Adam Lesinski182f73f2013-12-05 16:48:06 -08002617 mHandler.removeMessages(ALARM_EVENT);
2618 mHandler.sendMessageAtTime(msg, when);
2619 }
2620 }
2621
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002622 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002623 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002624 for (int i=list.size()-1; i>=0; i--) {
2625 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002626 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2627 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002628 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002629 }
2630 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002631
2632 private static final String labelForType(int type) {
2633 switch (type) {
2634 case RTC: return "RTC";
2635 case RTC_WAKEUP : return "RTC_WAKEUP";
2636 case ELAPSED_REALTIME : return "ELAPSED";
2637 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002638 }
2639 return "--unknown--";
2640 }
2641
2642 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002643 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002644 for (int i=list.size()-1; i>=0; i--) {
2645 Alarm a = list.get(i);
2646 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002647 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2648 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002649 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002650 }
2651 }
2652
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002653 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002654 if (alarm.alarmClock != null) {
2655 // Don't block alarm clocks
2656 return false;
2657 }
2658 if (alarm.operation != null
2659 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2660 // Don't block starting foreground components
2661 return false;
2662 }
2663 final String sourcePackage =
2664 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2665 final int sourceUid = alarm.creatorUid;
Makoto Onuki2206af32017-11-21 16:25:35 -08002666 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002667 }
2668
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002669 private native long init();
2670 private native void close(long nativeData);
2671 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2672 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002673 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002674 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002675
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002676 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002677 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002678 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002679 // batches are temporally sorted, so we need only pull from the
2680 // start of the list until we either empty it or hit a batch
2681 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002682 while (mAlarmBatches.size() > 0) {
2683 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002684 if (batch.start > nowELAPSED) {
2685 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002686 break;
2687 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002688
Christopher Tatee0a22b32013-07-11 14:43:13 -07002689 // We will (re)schedule some alarms now; don't let that interfere
2690 // with delivery of this current batch
2691 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002692
Christopher Tatee0a22b32013-07-11 14:43:13 -07002693 final int N = batch.size();
2694 for (int i = 0; i < N; i++) {
2695 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002696
2697 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2698 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2699 // schedule such alarms.
2700 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2701 long minTime = lastTime + mAllowWhileIdleMinTime;
2702 if (nowELAPSED < minTime) {
2703 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2704 // alarm went off for this app. Reschedule the alarm to be in the
2705 // correct time period.
2706 alarm.whenElapsed = minTime;
2707 if (alarm.maxWhenElapsed < minTime) {
2708 alarm.maxWhenElapsed = minTime;
2709 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002710 if (RECORD_DEVICE_IDLE_ALARMS) {
2711 IdleDispatchEntry ent = new IdleDispatchEntry();
2712 ent.uid = alarm.uid;
2713 ent.pkg = alarm.operation.getCreatorPackage();
2714 ent.tag = alarm.operation.getTag("");
2715 ent.op = "RESCHEDULE";
2716 ent.elapsedRealtime = nowELAPSED;
2717 ent.argRealtime = lastTime;
2718 mAllowWhileIdleDispatches.add(ent);
2719 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002720 setImplLocked(alarm, true, false);
2721 continue;
2722 }
2723 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002724 if (isBackgroundRestricted(alarm)) {
2725 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2726 if (DEBUG_BG_LIMIT) {
2727 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2728 }
2729 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2730 if (alarmsForUid == null) {
2731 alarmsForUid = new ArrayList<>();
2732 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2733 }
2734 alarmsForUid.add(alarm);
2735 continue;
2736 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002737
Christopher Tatee0a22b32013-07-11 14:43:13 -07002738 alarm.count = 1;
2739 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002740 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2741 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002742 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002743 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002744 if (mPendingIdleUntil == alarm) {
2745 mPendingIdleUntil = null;
2746 rebatchAllAlarmsLocked(false);
2747 restorePendingWhileIdleAlarmsLocked();
2748 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002749 if (mNextWakeFromIdle == alarm) {
2750 mNextWakeFromIdle = null;
2751 rebatchAllAlarmsLocked(false);
2752 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002753
2754 // Recurring alarms may have passed several alarm intervals while the
2755 // phone was asleep or off, so pass a trigger count when sending them.
2756 if (alarm.repeatInterval > 0) {
2757 // this adjustment will be zero if we're late by
2758 // less than one full repeat interval
2759 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2760
2761 // Also schedule its next recurrence
2762 final long delta = alarm.count * alarm.repeatInterval;
2763 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002764 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002765 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002766 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2767 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002769
Christopher Tate864d42e2014-12-02 11:48:53 -08002770 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002771 hasWakeup = true;
2772 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002773
2774 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2775 if (alarm.alarmClock != null) {
2776 mNextAlarmClockMayChange = true;
2777 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002779 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002780
Christopher Tate1590f1e2014-10-02 17:27:57 -07002781 // This is a new alarm delivery set; bump the sequence number to indicate that
2782 // all apps' alarm delivery classes should be recalculated.
2783 mCurrentSeq++;
2784 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002785 Collections.sort(triggerList, mAlarmDispatchComparator);
2786
2787 if (localLOGV) {
2788 for (int i=0; i<triggerList.size(); i++) {
2789 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2790 }
2791 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002792
2793 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002794 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002795
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002796 /**
2797 * This Comparator sorts Alarms into increasing time order.
2798 */
2799 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2800 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002801 long when1 = a1.whenElapsed;
2802 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002803 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 return 1;
2805 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002806 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002807 return -1;
2808 }
2809 return 0;
2810 }
2811 }
Kweku Adams61e03292017-10-19 14:27:12 -07002812
Makoto Onuki2206af32017-11-21 16:25:35 -08002813 @VisibleForTesting
2814 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002815 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002816 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002817 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002818 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002819 public final IAlarmListener listener;
2820 public final String listenerTag;
2821 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002822 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002823 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002824 public final AlarmManager.AlarmClockInfo alarmClock;
2825 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002826 public final int creatorUid;
2827 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 public int count;
2829 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002830 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002831 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002832 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002833 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002834 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002835
Christopher Tate3e04b472013-10-21 17:51:31 -07002836 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002837 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2838 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2839 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002840 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002841 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002842 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2843 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002844 when = _when;
2845 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002846 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002847 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002848 repeatInterval = _interval;
2849 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002850 listener = _rec;
2851 listenerTag = _listenerTag;
2852 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002853 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002854 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002855 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002856 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002857 packageName = _pkgName;
2858
2859 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002860 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002861
Christopher Tate14a7bb02015-10-01 10:24:31 -07002862 public static String makeTag(PendingIntent pi, String tag, int type) {
2863 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2864 ? "*walarm*:" : "*alarm*:";
2865 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2866 }
2867
2868 public WakeupEvent makeWakeupEvent(long nowRTC) {
2869 return new WakeupEvent(nowRTC, creatorUid,
2870 (operation != null)
2871 ? operation.getIntent().getAction()
2872 : ("<listener>:" + listenerTag));
2873 }
2874
2875 // Returns true if either matches
2876 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2877 return (operation != null)
2878 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002879 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002880 }
2881
2882 public boolean matches(String packageName) {
2883 return (operation != null)
2884 ? packageName.equals(operation.getTargetPackage())
2885 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002886 }
2887
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002888 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002889 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002890 StringBuilder sb = new StringBuilder(128);
2891 sb.append("Alarm{");
2892 sb.append(Integer.toHexString(System.identityHashCode(this)));
2893 sb.append(" type ");
2894 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002895 sb.append(" when ");
2896 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002897 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002898 if (operation != null) {
2899 sb.append(operation.getTargetPackage());
2900 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002901 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002902 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002903 sb.append('}');
2904 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002905 }
2906
Kweku Adams61e03292017-10-19 14:27:12 -07002907 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002908 SimpleDateFormat sdf) {
2909 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002910 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002911 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002912 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2913 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002914 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002915 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002916 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002917 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002918 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002919 }
2920 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002921 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002922 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002923 pw.print(" count="); pw.print(count);
2924 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002925 if (alarmClock != null) {
2926 pw.print(prefix); pw.println("Alarm clock:");
2927 pw.print(prefix); pw.print(" triggerTime=");
2928 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2929 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2930 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002931 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002932 if (listener != null) {
2933 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2934 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002935 }
Kweku Adams61e03292017-10-19 14:27:12 -07002936
2937 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
2938 long nowRTC) {
2939 final long token = proto.start(fieldId);
2940
2941 proto.write(AlarmProto.TAG, statsTag);
2942 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08002943 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07002944 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
2945 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
2946 proto.write(AlarmProto.COUNT, count);
2947 proto.write(AlarmProto.FLAGS, flags);
2948 if (alarmClock != null) {
2949 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
2950 }
2951 if (operation != null) {
2952 operation.writeToProto(proto, AlarmProto.OPERATION);
2953 }
2954 if (listener != null) {
2955 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
2956 }
2957
2958 proto.end(token);
2959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002960 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002961
Christopher Tatee0a22b32013-07-11 14:43:13 -07002962 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2963 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002964 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2965 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002966 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002967 break;
2968 }
2969
Christopher Tatee0a22b32013-07-11 14:43:13 -07002970 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002971 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2972 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002973 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002974 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002975 }
2976 }
2977
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002978 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2979 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2980 if (timeSinceOn < 5*60*1000) {
2981 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2982 return 2*60*1000;
2983 } else if (timeSinceOn < 30*60*1000) {
2984 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2985 return 15*60*1000;
2986 } else {
2987 // Otherwise, we will delay by at most an hour.
2988 return 60*60*1000;
2989 }
2990 }
2991
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002992 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002993 if (duration < 15*60*1000) {
2994 // If the duration until the time is less than 15 minutes, the maximum fuzz
2995 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002996 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002997 } else if (duration < 90*60*1000) {
2998 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
2999 return 15*60*1000;
3000 } else {
3001 // Otherwise, we will fuzz by at most half an hour.
3002 return 30*60*1000;
3003 }
3004 }
3005
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003006 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3007 if (mInteractive) {
3008 return false;
3009 }
3010 if (mLastAlarmDeliveryTime <= 0) {
3011 return false;
3012 }
minho.choo649acab2014-12-12 16:13:55 +09003013 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003014 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3015 // and the next delivery time is in the past, then just deliver them all. This
3016 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3017 return false;
3018 }
3019 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3020 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3021 }
3022
3023 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3024 mLastAlarmDeliveryTime = nowELAPSED;
3025 for (int i=0; i<triggerList.size(); i++) {
3026 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003027 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003028 if (alarm.wakeup) {
3029 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3030 } else {
3031 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3032 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003033 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003034 if (localLOGV) {
3035 Slog.v(TAG, "sending alarm " + alarm);
3036 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003037 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003038 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3039 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003040 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003041 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003042 } catch (RuntimeException e) {
3043 Slog.w(TAG, "Failure sending alarm.", e);
3044 }
Tim Murray175c0f92017-11-28 15:01:04 -08003045 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003046 }
3047 }
3048
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003049 private class AlarmThread extends Thread
3050 {
3051 public AlarmThread()
3052 {
3053 super("AlarmManager");
3054 }
Kweku Adams61e03292017-10-19 14:27:12 -07003055
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003056 public void run()
3057 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003058 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3059
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003060 while (true)
3061 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003062 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003063 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003064
3065 triggerList.clear();
3066
Dianne Hackbornc3527222015-05-13 14:03:20 -07003067 final long nowRTC = System.currentTimeMillis();
3068 final long nowELAPSED = SystemClock.elapsedRealtime();
3069
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003070 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003071 // The kernel can give us spurious time change notifications due to
3072 // small adjustments it makes internally; we want to filter those out.
3073 final long lastTimeChangeClockTime;
3074 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003075 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003076 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3077 expectedClockTime = lastTimeChangeClockTime
3078 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003079 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003080 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3081 || nowRTC > (expectedClockTime+1000)) {
3082 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003083 // let's do it!
3084 if (DEBUG_BATCH) {
3085 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3086 }
3087 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003088 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003089 rebatchAllAlarms();
3090 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003091 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003092 synchronized (mLock) {
3093 mNumTimeChanged++;
3094 mLastTimeChangeClockTime = nowRTC;
3095 mLastTimeChangeRealtime = nowELAPSED;
3096 }
3097 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3098 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003099 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003100 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3101 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003102 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3103
3104 // The world has changed on us, so we need to re-evaluate alarms
3105 // regardless of whether the kernel has told us one went off.
3106 result |= IS_WAKEUP_MASK;
3107 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003108 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109
Dianne Hackbornc3527222015-05-13 14:03:20 -07003110 if (result != TIME_CHANGED_MASK) {
3111 // If this was anything besides just a time change, then figure what if
3112 // anything to do about alarms.
3113 synchronized (mLock) {
3114 if (localLOGV) Slog.v(
3115 TAG, "Checking for alarms... rtc=" + nowRTC
3116 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003117
Dianne Hackbornc3527222015-05-13 14:03:20 -07003118 if (WAKEUP_STATS) {
3119 if ((result & IS_WAKEUP_MASK) != 0) {
3120 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3121 int n = 0;
3122 for (WakeupEvent event : mRecentWakeups) {
3123 if (event.when > newEarliest) break;
3124 n++; // number of now-stale entries at the list head
3125 }
3126 for (int i = 0; i < n; i++) {
3127 mRecentWakeups.remove();
3128 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003129
Dianne Hackbornc3527222015-05-13 14:03:20 -07003130 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003131 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003132 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003133
3134 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3135 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3136 // if there are no wakeup alarms and the screen is off, we can
3137 // delay what we have so far until the future.
3138 if (mPendingNonWakeupAlarms.size() == 0) {
3139 mStartCurrentDelayTime = nowELAPSED;
3140 mNextNonWakeupDeliveryTime = nowELAPSED
3141 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3142 }
3143 mPendingNonWakeupAlarms.addAll(triggerList);
3144 mNumDelayedAlarms += triggerList.size();
3145 rescheduleKernelAlarmsLocked();
3146 updateNextAlarmClockLocked();
3147 } else {
3148 // now deliver the alarm intents; if there are pending non-wakeup
3149 // alarms, we need to merge them in to the list. note we don't
3150 // just deliver them first because we generally want non-wakeup
3151 // alarms delivered after wakeup alarms.
3152 rescheduleKernelAlarmsLocked();
3153 updateNextAlarmClockLocked();
3154 if (mPendingNonWakeupAlarms.size() > 0) {
3155 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3156 triggerList.addAll(mPendingNonWakeupAlarms);
3157 Collections.sort(triggerList, mAlarmDispatchComparator);
3158 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3159 mTotalDelayTime += thisDelayTime;
3160 if (mMaxDelayTime < thisDelayTime) {
3161 mMaxDelayTime = thisDelayTime;
3162 }
3163 mPendingNonWakeupAlarms.clear();
3164 }
3165 deliverAlarmsLocked(triggerList, nowELAPSED);
3166 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003167 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003168
3169 } else {
3170 // Just in case -- even though no wakeup flag was set, make sure
3171 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003172 synchronized (mLock) {
3173 rescheduleKernelAlarmsLocked();
3174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 }
3176 }
3177 }
3178 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003179
David Christieebe51fc2013-07-26 13:23:29 -07003180 /**
3181 * Attribute blame for a WakeLock.
3182 * @param pi PendingIntent to attribute blame to if ws is null.
3183 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003184 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003185 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003186 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003187 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003188 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003189 final boolean unimportant = pi == mTimeTickSender;
3190 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003191 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003192 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003193 } else {
3194 mWakeLock.setHistoryTag(null);
3195 }
3196 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003197 if (ws != null) {
3198 mWakeLock.setWorkSource(ws);
3199 return;
3200 }
3201
Christopher Tate14a7bb02015-10-01 10:24:31 -07003202 final int uid = (knownUid >= 0)
3203 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003204 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003205 if (uid >= 0) {
3206 mWakeLock.setWorkSource(new WorkSource(uid));
3207 return;
3208 }
3209 } catch (Exception e) {
3210 }
3211
3212 // Something went wrong; fall back to attributing the lock to the OS
3213 mWakeLock.setWorkSource(null);
3214 }
3215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 private class AlarmHandler extends Handler {
3217 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003218 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3219 public static final int LISTENER_TIMEOUT = 3;
3220 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003221
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003222 public AlarmHandler() {
3223 }
Kweku Adams61e03292017-10-19 14:27:12 -07003224
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003225 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003226 switch (msg.what) {
3227 case ALARM_EVENT: {
3228 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3229 synchronized (mLock) {
3230 final long nowRTC = System.currentTimeMillis();
3231 final long nowELAPSED = SystemClock.elapsedRealtime();
3232 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3233 updateNextAlarmClockLocked();
3234 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003235
Christopher Tate14a7bb02015-10-01 10:24:31 -07003236 // now trigger the alarms without the lock held
3237 for (int i=0; i<triggerList.size(); i++) {
3238 Alarm alarm = triggerList.get(i);
3239 try {
3240 alarm.operation.send();
3241 } catch (PendingIntent.CanceledException e) {
3242 if (alarm.repeatInterval > 0) {
3243 // This IntentSender is no longer valid, but this
3244 // is a repeating alarm, so toss the hoser.
3245 removeImpl(alarm.operation);
3246 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003247 }
3248 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003249 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003250 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003251
3252 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3253 sendNextAlarmClockChanged();
3254 break;
3255
3256 case LISTENER_TIMEOUT:
3257 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3258 break;
3259
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003260 case REPORT_ALARMS_ACTIVE:
3261 if (mLocalDeviceIdleController != null) {
3262 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3263 }
3264 break;
3265
Christopher Tate14a7bb02015-10-01 10:24:31 -07003266 default:
3267 // nope, just ignore it
3268 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003269 }
3270 }
3271 }
Kweku Adams61e03292017-10-19 14:27:12 -07003272
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003273 class ClockReceiver extends BroadcastReceiver {
3274 public ClockReceiver() {
3275 IntentFilter filter = new IntentFilter();
3276 filter.addAction(Intent.ACTION_TIME_TICK);
3277 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003278 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003279 }
Kweku Adams61e03292017-10-19 14:27:12 -07003280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 @Override
3282 public void onReceive(Context context, Intent intent) {
3283 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003284 if (DEBUG_BATCH) {
3285 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3286 }
3287 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003288 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3289 // Since the kernel does not keep track of DST, we need to
3290 // reset the TZ information at the beginning of each day
3291 // based off of the current Zone gmt offset + userspace tracked
3292 // daylight savings information.
3293 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003294 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003295 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003296 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003297 }
3298 }
Kweku Adams61e03292017-10-19 14:27:12 -07003299
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003300 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003301 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003302 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003303
3304 // Schedule this event for the amount of time that it would take to get to
3305 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003306 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003307
David Christieebe51fc2013-07-26 13:23:29 -07003308 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003309 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003310 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3311 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003312 }
Christopher Tate385e4982013-07-23 18:22:29 -07003313
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003314 public void scheduleDateChangedEvent() {
3315 Calendar calendar = Calendar.getInstance();
3316 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003317 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 calendar.set(Calendar.MINUTE, 0);
3319 calendar.set(Calendar.SECOND, 0);
3320 calendar.set(Calendar.MILLISECOND, 0);
3321 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003322
3323 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003324 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3325 AlarmManager.FLAG_STANDALONE, workSource, null,
3326 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003327 }
3328 }
Kweku Adams61e03292017-10-19 14:27:12 -07003329
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003330 class InteractiveStateReceiver extends BroadcastReceiver {
3331 public InteractiveStateReceiver() {
3332 IntentFilter filter = new IntentFilter();
3333 filter.addAction(Intent.ACTION_SCREEN_OFF);
3334 filter.addAction(Intent.ACTION_SCREEN_ON);
3335 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3336 getContext().registerReceiver(this, filter);
3337 }
3338
3339 @Override
3340 public void onReceive(Context context, Intent intent) {
3341 synchronized (mLock) {
3342 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3343 }
3344 }
3345 }
3346
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003347 class UninstallReceiver extends BroadcastReceiver {
3348 public UninstallReceiver() {
3349 IntentFilter filter = new IntentFilter();
3350 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3351 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003352 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003354 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003355 // Register for events related to sdcard installation.
3356 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003357 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003358 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003359 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003360 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
Kweku Adams61e03292017-10-19 14:27:12 -07003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 @Override
3364 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003365 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003366 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003367 String action = intent.getAction();
3368 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003369 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3370 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3371 for (String packageName : pkgList) {
3372 if (lookForPackageLocked(packageName)) {
3373 setResultCode(Activity.RESULT_OK);
3374 return;
3375 }
3376 }
3377 return;
3378 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003379 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003380 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3381 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3382 if (userHandle >= 0) {
3383 removeUserLocked(userHandle);
3384 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003385 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003386 if (uid >= 0) {
3387 mLastAllowWhileIdleDispatch.delete(uid);
3388 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003389 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003390 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3391 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3392 // This package is being updated; don't kill its alarms.
3393 return;
3394 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003395 Uri data = intent.getData();
3396 if (data != null) {
3397 String pkg = data.getSchemeSpecificPart();
3398 if (pkg != null) {
3399 pkgList = new String[]{pkg};
3400 }
3401 }
3402 }
3403 if (pkgList != null && (pkgList.length > 0)) {
3404 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003405 if (uid >= 0) {
3406 // package-removed case
3407 removeLocked(uid);
3408 } else {
3409 // external-applications-unavailable etc case
3410 removeLocked(pkg);
3411 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003412 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003413 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3414 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3415 if (uidStats.remove(pkg) != null) {
3416 if (uidStats.size() <= 0) {
3417 mBroadcastStats.removeAt(i);
3418 }
3419 }
3420 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003421 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003422 }
3423 }
3424 }
3425 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003426
3427 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003428 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003429 }
3430
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003431 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003432 synchronized (mLock) {
3433 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003434 removeForStoppedLocked(uid);
3435 }
3436 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003437 }
3438
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003439 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003440 }
3441
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003442 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003443 synchronized (mLock) {
3444 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003445 removeForStoppedLocked(uid);
3446 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003447 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003448 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003449
3450 @Override public void onUidCachedChanged(int uid, boolean cached) {
3451 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003452 };
3453
Makoto Onuki2206af32017-11-21 16:25:35 -08003454
3455 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003456 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003457 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003458 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003459 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003460 }
3461 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003462
3463 @Override
3464 public void unblockAlarmsForUid(int uid) {
3465 synchronized (mLock) {
3466 sendPendingBackgroundAlarmsLocked(uid, null);
3467 }
3468 }
3469
3470 @Override
3471 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3472 synchronized (mLock) {
3473 sendPendingBackgroundAlarmsLocked(uid, packageName);
3474 }
3475 }
3476 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003477
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003478 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003479 String pkg = pi.getCreatorPackage();
3480 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003481 return getStatsLocked(uid, pkg);
3482 }
3483
3484 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003485 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3486 if (uidStats == null) {
3487 uidStats = new ArrayMap<String, BroadcastStats>();
3488 mBroadcastStats.put(uid, uidStats);
3489 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003490 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003491 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003492 bs = new BroadcastStats(uid, pkgName);
3493 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 }
3495 return bs;
3496 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003497
Christopher Tate21e9f192017-08-08 13:49:11 -07003498 /**
3499 * Canonical count of (operation.send() - onSendFinished()) and
3500 * listener send/complete/timeout invocations.
3501 * Guarded by the usual lock.
3502 */
3503 @GuardedBy("mLock")
3504 private int mSendCount = 0;
3505 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003506 private int mSendFinishCount = 0;
3507 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003508 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003509 @GuardedBy("mLock")
3510 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003511
Christopher Tate14a7bb02015-10-01 10:24:31 -07003512 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003513
Christopher Tate14a7bb02015-10-01 10:24:31 -07003514 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3515 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003516 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003517 return mInFlight.remove(i);
3518 }
3519 }
3520 mLog.w("No in-flight alarm for " + pi + " " + intent);
3521 return null;
3522 }
3523
3524 private InFlight removeLocked(IBinder listener) {
3525 for (int i = 0; i < mInFlight.size(); i++) {
3526 if (mInFlight.get(i).mListener == listener) {
3527 return mInFlight.remove(i);
3528 }
3529 }
3530 mLog.w("No in-flight alarm for listener " + listener);
3531 return null;
3532 }
3533
3534 private void updateStatsLocked(InFlight inflight) {
3535 final long nowELAPSED = SystemClock.elapsedRealtime();
3536 BroadcastStats bs = inflight.mBroadcastStats;
3537 bs.nesting--;
3538 if (bs.nesting <= 0) {
3539 bs.nesting = 0;
3540 bs.aggregateTime += nowELAPSED - bs.startTime;
3541 }
3542 FilterStats fs = inflight.mFilterStats;
3543 fs.nesting--;
3544 if (fs.nesting <= 0) {
3545 fs.nesting = 0;
3546 fs.aggregateTime += nowELAPSED - fs.startTime;
3547 }
3548 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003549 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3550 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003551 }
3552 }
3553
3554 private void updateTrackingLocked(InFlight inflight) {
3555 if (inflight != null) {
3556 updateStatsLocked(inflight);
3557 }
3558 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003559 if (DEBUG_WAKELOCK) {
3560 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3561 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003562 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003563 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003564 mWakeLock.release();
3565 if (mInFlight.size() > 0) {
3566 mLog.w("Finished all dispatches with " + mInFlight.size()
3567 + " remaining inflights");
3568 for (int i=0; i<mInFlight.size(); i++) {
3569 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3570 }
3571 mInFlight.clear();
3572 }
3573 } else {
3574 // the next of our alarms is now in flight. reattribute the wakelock.
3575 if (mInFlight.size() > 0) {
3576 InFlight inFlight = mInFlight.get(0);
3577 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3578 inFlight.mAlarmType, inFlight.mTag, -1, false);
3579 } else {
3580 // should never happen
3581 mLog.w("Alarm wakelock still held but sent queue empty");
3582 mWakeLock.setWorkSource(null);
3583 }
3584 }
3585 }
3586
3587 /**
3588 * Callback that arrives when a direct-call alarm reports that delivery has finished
3589 */
3590 @Override
3591 public void alarmComplete(IBinder who) {
3592 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003593 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003594 + " pid=" + Binder.getCallingPid());
3595 return;
3596 }
3597
3598 final long ident = Binder.clearCallingIdentity();
3599 try {
3600 synchronized (mLock) {
3601 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3602 InFlight inflight = removeLocked(who);
3603 if (inflight != null) {
3604 if (DEBUG_LISTENER_CALLBACK) {
3605 Slog.i(TAG, "alarmComplete() from " + who);
3606 }
3607 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003608 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003609 } else {
3610 // Delivery timed out, and the timeout handling already took care of
3611 // updating our tracking here, so we needn't do anything further.
3612 if (DEBUG_LISTENER_CALLBACK) {
3613 Slog.i(TAG, "Late alarmComplete() from " + who);
3614 }
3615 }
3616 }
3617 } finally {
3618 Binder.restoreCallingIdentity(ident);
3619 }
3620 }
3621
3622 /**
3623 * Callback that arrives when a PendingIntent alarm has finished delivery
3624 */
3625 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003626 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3627 String resultData, Bundle resultExtras) {
3628 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003629 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003630 updateTrackingLocked(removeLocked(pi, intent));
3631 }
3632 }
3633
3634 /**
3635 * Timeout of a direct-call alarm delivery
3636 */
3637 public void alarmTimedOut(IBinder who) {
3638 synchronized (mLock) {
3639 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003640 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003641 // TODO: implement ANR policy for the target
3642 if (DEBUG_LISTENER_CALLBACK) {
3643 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003644 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003645 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003646 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003647 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003648 if (DEBUG_LISTENER_CALLBACK) {
3649 Slog.i(TAG, "Spurious timeout of listener " + who);
3650 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003651 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003652 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003653 }
3654 }
3655
3656 /**
3657 * Deliver an alarm and set up the post-delivery handling appropriately
3658 */
3659 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3660 if (alarm.operation != null) {
3661 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003662 mSendCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003663 try {
3664 alarm.operation.send(getContext(), 0,
3665 mBackgroundIntent.putExtra(
3666 Intent.EXTRA_ALARM_COUNT, alarm.count),
3667 mDeliveryTracker, mHandler, null,
3668 allowWhileIdle ? mIdleOptions : null);
3669 } catch (PendingIntent.CanceledException e) {
3670 if (alarm.repeatInterval > 0) {
3671 // This IntentSender is no longer valid, but this
3672 // is a repeating alarm, so toss it
3673 removeImpl(alarm.operation);
3674 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003675 // No actual delivery was possible, so the delivery tracker's
3676 // 'finished' callback won't be invoked. We also don't need
3677 // to do any wakelock or stats tracking, so we have nothing
3678 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003679 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003680 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003681 }
3682 } else {
3683 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003684 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003685 try {
3686 if (DEBUG_LISTENER_CALLBACK) {
3687 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3688 + " listener=" + alarm.listener.asBinder());
3689 }
3690 alarm.listener.doAlarm(this);
3691 mHandler.sendMessageDelayed(
3692 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3693 alarm.listener.asBinder()),
3694 mConstants.LISTENER_TIMEOUT);
3695 } catch (Exception e) {
3696 if (DEBUG_LISTENER_CALLBACK) {
3697 Slog.i(TAG, "Alarm undeliverable to listener "
3698 + alarm.listener.asBinder(), e);
3699 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003700 // As in the PendingIntent.CanceledException case, delivery of the
3701 // alarm was not possible, so we have no wakelock or timeout or
3702 // stats management to do. It threw before we posted the delayed
3703 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003704 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003705 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003706 }
3707 }
3708
3709 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003710 if (DEBUG_WAKELOCK) {
3711 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3712 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003713 if (mBroadcastRefCount == 0) {
3714 setWakelockWorkSource(alarm.operation, alarm.workSource,
3715 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3716 true);
3717 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003718 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003719 }
3720 final InFlight inflight = new InFlight(AlarmManagerService.this,
3721 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3722 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3723 mInFlight.add(inflight);
3724 mBroadcastRefCount++;
3725
3726 if (allowWhileIdle) {
3727 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3728 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3729 if (RECORD_DEVICE_IDLE_ALARMS) {
3730 IdleDispatchEntry ent = new IdleDispatchEntry();
3731 ent.uid = alarm.uid;
3732 ent.pkg = alarm.packageName;
3733 ent.tag = alarm.statsTag;
3734 ent.op = "DELIVER";
3735 ent.elapsedRealtime = nowELAPSED;
3736 mAllowWhileIdleDispatches.add(ent);
3737 }
3738 }
3739
3740 final BroadcastStats bs = inflight.mBroadcastStats;
3741 bs.count++;
3742 if (bs.nesting == 0) {
3743 bs.nesting = 1;
3744 bs.startTime = nowELAPSED;
3745 } else {
3746 bs.nesting++;
3747 }
3748 final FilterStats fs = inflight.mFilterStats;
3749 fs.count++;
3750 if (fs.nesting == 0) {
3751 fs.nesting = 1;
3752 fs.startTime = nowELAPSED;
3753 } else {
3754 fs.nesting++;
3755 }
3756 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3757 || alarm.type == RTC_WAKEUP) {
3758 bs.numWakeup++;
3759 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00003760 ActivityManager.noteWakeupAlarm(
3761 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
3762 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003763 }
3764 }
3765 }
3766}