blob: a024d5a8e3ff0c78b4a0b9cfa4a0a0c55253c43f [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;
Christopher Tate12cf0b62018-01-05 18:40:14 -0800152 private long mLastTickSet;
153 private long mLastTickIssued; // elapsed
154 private long mLastTickReceived;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800155 int mBroadcastRefCount = 0;
156 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700157 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700158 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
159 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800160 final AlarmHandler mHandler = new AlarmHandler();
161 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700162 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700164 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800165 PendingIntent mTimeTickSender;
166 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700167 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700168 boolean mInteractive = true;
169 long mNonInteractiveStartTime;
170 long mNonInteractiveTime;
171 long mLastAlarmDeliveryTime;
172 long mStartCurrentDelayTime;
173 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700174 long mLastTimeChangeClockTime;
175 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700176 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700177 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800178
Christopher Tatebb9cce52017-04-18 14:19:43 -0700179 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
180
181 /**
182 * This permission must be defined by the canonical System UI package,
183 * with protection level "signature".
184 */
185 private static final String SYSTEM_UI_SELF_PERMISSION =
186 "android.permission.systemui.IDENTITY";
187
188 /**
189 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
190 */
191 int mSystemUiUid;
192
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700193 /**
194 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700195 * used to determine the earliest we can dispatch the next such alarm. Times are in the
196 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700197 */
198 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
199
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700200 final static class IdleDispatchEntry {
201 int uid;
202 String pkg;
203 String tag;
204 String op;
205 long elapsedRealtime;
206 long argRealtime;
207 }
208 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
209
Dianne Hackborna750a632015-06-16 17:18:23 -0700210 /**
211 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
212 */
213 Bundle mIdleOptions;
214
Jose Lima235510e2014-08-13 12:50:01 -0700215 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
216 new SparseArray<>();
217 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
218 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200219 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
220 new SparseBooleanArray();
221 private boolean mNextAlarmClockMayChange;
222
223 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700224 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
225 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200226
Makoto Onuki2206af32017-11-21 16:25:35 -0800227 private final ForceAppStandbyTracker mForceAppStandbyTracker;
228
Dianne Hackborna750a632015-06-16 17:18:23 -0700229 /**
230 * All times are in milliseconds. These constants are kept synchronized with the system
231 * global Settings. Any access to this class or its fields should be done while
232 * holding the AlarmManagerService.mLock lock.
233 */
234 private final class Constants extends ContentObserver {
235 // Key names stored in the settings value.
236 private static final String KEY_MIN_FUTURITY = "min_futurity";
237 private static final String KEY_MIN_INTERVAL = "min_interval";
238 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
239 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
240 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
241 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700242 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700243 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700244
245 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
246 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700247 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700248 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700249 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
250
Christopher Tate14a7bb02015-10-01 10:24:31 -0700251 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
252
Dianne Hackborna750a632015-06-16 17:18:23 -0700253 // Minimum futurity of a new alarm
254 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
255
256 // Minimum alarm recurrence interval
257 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
258
259 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
260 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
261
262 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
263 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
264
265 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
266 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
267 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
268
Christopher Tate14a7bb02015-10-01 10:24:31 -0700269 // Direct alarm listener callback timeout
270 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
271
Dianne Hackborna750a632015-06-16 17:18:23 -0700272 private ContentResolver mResolver;
273 private final KeyValueListParser mParser = new KeyValueListParser(',');
274 private long mLastAllowWhileIdleWhitelistDuration = -1;
275
276 public Constants(Handler handler) {
277 super(handler);
278 updateAllowWhileIdleMinTimeLocked();
279 updateAllowWhileIdleWhitelistDurationLocked();
280 }
281
282 public void start(ContentResolver resolver) {
283 mResolver = resolver;
284 mResolver.registerContentObserver(Settings.Global.getUriFor(
285 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
286 updateConstants();
287 }
288
289 public void updateAllowWhileIdleMinTimeLocked() {
290 mAllowWhileIdleMinTime = mPendingIdleUntil != null
291 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
292 }
293
294 public void updateAllowWhileIdleWhitelistDurationLocked() {
295 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
296 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
297 BroadcastOptions opts = BroadcastOptions.makeBasic();
298 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
299 mIdleOptions = opts.toBundle();
300 }
301 }
302
303 @Override
304 public void onChange(boolean selfChange, Uri uri) {
305 updateConstants();
306 }
307
308 private void updateConstants() {
309 synchronized (mLock) {
310 try {
311 mParser.setString(Settings.Global.getString(mResolver,
312 Settings.Global.ALARM_MANAGER_CONSTANTS));
313 } catch (IllegalArgumentException e) {
314 // Failed to parse the settings string, log this and move on
315 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800316 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700317 }
318
319 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
320 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
321 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
322 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
323 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
324 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
325 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
326 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
327 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700328 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
329 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700330
331 updateAllowWhileIdleMinTimeLocked();
332 updateAllowWhileIdleWhitelistDurationLocked();
333 }
334 }
335
336 void dump(PrintWriter pw) {
337 pw.println(" Settings:");
338
339 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
340 TimeUtils.formatDuration(MIN_FUTURITY, pw);
341 pw.println();
342
343 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
344 TimeUtils.formatDuration(MIN_INTERVAL, pw);
345 pw.println();
346
Christopher Tate14a7bb02015-10-01 10:24:31 -0700347 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
348 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
349 pw.println();
350
Dianne Hackborna750a632015-06-16 17:18:23 -0700351 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
352 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
353 pw.println();
354
355 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
356 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
357 pw.println();
358
359 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
360 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
361 pw.println();
362 }
Kweku Adams61e03292017-10-19 14:27:12 -0700363
364 void dumpProto(ProtoOutputStream proto, long fieldId) {
365 final long token = proto.start(fieldId);
366
367 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
368 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
369 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
370 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
371 ALLOW_WHILE_IDLE_SHORT_TIME);
372 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
373 ALLOW_WHILE_IDLE_LONG_TIME);
374 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
375 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
376
377 proto.end(token);
378 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700379 }
380
381 final Constants mConstants;
382
Christopher Tate1590f1e2014-10-02 17:27:57 -0700383 // Alarm delivery ordering bookkeeping
384 static final int PRIO_TICK = 0;
385 static final int PRIO_WAKEUP = 1;
386 static final int PRIO_NORMAL = 2;
387
Dianne Hackborna750a632015-06-16 17:18:23 -0700388 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700389 int seq;
390 int priority;
391
392 PriorityClass() {
393 seq = mCurrentSeq - 1;
394 priority = PRIO_NORMAL;
395 }
396 }
397
Dianne Hackborna750a632015-06-16 17:18:23 -0700398 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700399 int mCurrentSeq = 0;
400
Dianne Hackborna750a632015-06-16 17:18:23 -0700401 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700402 public long when;
403 public int uid;
404 public String action;
405
406 public WakeupEvent(long theTime, int theUid, String theAction) {
407 when = theTime;
408 uid = theUid;
409 action = theAction;
410 }
411 }
412
Adam Lesinski182f73f2013-12-05 16:48:06 -0800413 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
414 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700415
Adrian Roosc42a1e12014-07-07 23:35:53 +0200416 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700417 long start; // These endpoints are always in ELAPSED
418 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700419 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700420
421 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
422
423 Batch() {
424 start = 0;
425 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700426 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700427 }
428
429 Batch(Alarm seed) {
430 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700431 end = seed.maxWhenElapsed;
432 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700433 alarms.add(seed);
434 }
435
436 int size() {
437 return alarms.size();
438 }
439
440 Alarm get(int index) {
441 return alarms.get(index);
442 }
443
444 boolean canHold(long whenElapsed, long maxWhen) {
445 return (end >= whenElapsed) && (start <= maxWhen);
446 }
447
448 boolean add(Alarm alarm) {
449 boolean newStart = false;
450 // narrows the batch if necessary; presumes that canHold(alarm) is true
451 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
452 if (index < 0) {
453 index = 0 - index - 1;
454 }
455 alarms.add(index, alarm);
456 if (DEBUG_BATCH) {
457 Slog.v(TAG, "Adding " + alarm + " to " + this);
458 }
459 if (alarm.whenElapsed > start) {
460 start = alarm.whenElapsed;
461 newStart = true;
462 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700463 if (alarm.maxWhenElapsed < end) {
464 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700466 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700467
468 if (DEBUG_BATCH) {
469 Slog.v(TAG, " => now " + this);
470 }
471 return newStart;
472 }
473
Christopher Tate1d99c392017-12-07 16:54:04 -0800474 boolean remove(Predicate<Alarm> predicate) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700475 boolean didRemove = false;
476 long newStart = 0; // recalculate endpoints as we go
477 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700478 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700479 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700480 Alarm alarm = alarms.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -0800481 if (predicate.test(alarm)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700482 alarms.remove(i);
483 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200484 if (alarm.alarmClock != null) {
485 mNextAlarmClockMayChange = true;
486 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 } else {
488 if (alarm.whenElapsed > newStart) {
489 newStart = alarm.whenElapsed;
490 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700491 if (alarm.maxWhenElapsed < newEnd) {
492 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700493 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700494 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700495 i++;
496 }
497 }
498 if (didRemove) {
499 // commit the new batch bounds
500 start = newStart;
501 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700502 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700503 }
504 return didRemove;
505 }
506
Christopher Tatee0a22b32013-07-11 14:43:13 -0700507 boolean hasPackage(final String packageName) {
508 final int N = alarms.size();
509 for (int i = 0; i < N; i++) {
510 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700511 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700512 return true;
513 }
514 }
515 return false;
516 }
517
518 boolean hasWakeups() {
519 final int N = alarms.size();
520 for (int i = 0; i < N; i++) {
521 Alarm a = alarms.get(i);
522 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
523 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
524 return true;
525 }
526 }
527 return false;
528 }
529
530 @Override
531 public String toString() {
532 StringBuilder b = new StringBuilder(40);
533 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
534 b.append(" num="); b.append(size());
535 b.append(" start="); b.append(start);
536 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700537 if (flags != 0) {
538 b.append(" flgs=0x");
539 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700540 }
541 b.append('}');
542 return b.toString();
543 }
Kweku Adams61e03292017-10-19 14:27:12 -0700544
545 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
546 long nowRTC) {
547 final long token = proto.start(fieldId);
548
549 proto.write(BatchProto.START_REALTIME, start);
550 proto.write(BatchProto.END_REALTIME, end);
551 proto.write(BatchProto.FLAGS, flags);
552 for (Alarm a : alarms) {
553 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
554 }
555
556 proto.end(token);
557 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700558 }
559
560 static class BatchTimeOrder implements Comparator<Batch> {
561 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800562 long when1 = b1.start;
563 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800564 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700565 return 1;
566 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800567 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700568 return -1;
569 }
570 return 0;
571 }
572 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800573
574 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
575 @Override
576 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700577 // priority class trumps everything. TICK < WAKEUP < NORMAL
578 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
579 return -1;
580 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
581 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800582 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700583
584 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800585 if (lhs.whenElapsed < rhs.whenElapsed) {
586 return -1;
587 } else if (lhs.whenElapsed > rhs.whenElapsed) {
588 return 1;
589 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700590
591 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800592 return 0;
593 }
594 };
595
Christopher Tate1590f1e2014-10-02 17:27:57 -0700596 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
597 final int N = alarms.size();
598 for (int i = 0; i < N; i++) {
599 Alarm a = alarms.get(i);
600
601 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700602 if (a.operation != null
603 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700604 alarmPrio = PRIO_TICK;
605 } else if (a.wakeup) {
606 alarmPrio = PRIO_WAKEUP;
607 } else {
608 alarmPrio = PRIO_NORMAL;
609 }
610
611 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700612 String alarmPackage = (a.operation != null)
613 ? a.operation.getCreatorPackage()
614 : a.packageName;
615 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700616 if (packagePrio == null) {
617 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700618 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700619 }
620 a.priorityClass = packagePrio;
621
622 if (packagePrio.seq != mCurrentSeq) {
623 // first alarm we've seen in the current delivery generation from this package
624 packagePrio.priority = alarmPrio;
625 packagePrio.seq = mCurrentSeq;
626 } else {
627 // Multiple alarms from this package being delivered in this generation;
628 // bump the package's delivery class if it's warranted.
629 // TICK < WAKEUP < NORMAL
630 if (alarmPrio < packagePrio.priority) {
631 packagePrio.priority = alarmPrio;
632 }
633 }
634 }
635 }
636
Christopher Tatee0a22b32013-07-11 14:43:13 -0700637 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800638 static final long MIN_FUZZABLE_INTERVAL = 10000;
639 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700640 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
641
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700642 // 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 -0700643 // to run during this time are placed in mPendingWhileIdleAlarms
644 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700645 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700646 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700647
Jeff Brownb880d882014-02-10 19:47:07 -0800648 public AlarmManagerService(Context context) {
649 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700650 mConstants = new Constants(mHandler);
Makoto Onuki2206af32017-11-21 16:25:35 -0800651
652 mForceAppStandbyTracker = ForceAppStandbyTracker.getInstance(context);
653 mForceAppStandbyTracker.addListener(mForceAppStandbyListener);
Christopher Tate1d99c392017-12-07 16:54:04 -0800654
655 publishLocalService(AlarmManagerInternal.class, new LocalService());
Jeff Brownb880d882014-02-10 19:47:07 -0800656 }
657
Christopher Tatee0a22b32013-07-11 14:43:13 -0700658 static long convertToElapsed(long when, int type) {
659 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
660 if (isRtc) {
661 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
662 }
663 return when;
664 }
665
666 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
667 // calculate the end of our nominal delivery window for the alarm.
668 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
669 // Current heuristic: batchable window is 75% of either the recurrence interval
670 // [for a periodic alarm] or of the time from now to the desired delivery time,
671 // with a minimum delay/interval of 10 seconds, under which we will simply not
672 // defer the alarm.
673 long futurity = (interval == 0)
674 ? (triggerAtTime - now)
675 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700676 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700677 futurity = 0;
678 }
679 return triggerAtTime + (long)(.75 * futurity);
680 }
681
682 // returns true if the batch was added at the head
683 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
684 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
685 if (index < 0) {
686 index = 0 - index - 1;
687 }
688 list.add(index, newBatch);
689 return (index == 0);
690 }
691
Christopher Tate385e4982013-07-23 18:22:29 -0700692 // Return the index of the matching batch, or -1 if none found.
693 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700694 final int N = mAlarmBatches.size();
695 for (int i = 0; i < N; i++) {
696 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700697 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700698 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700699 }
700 }
Christopher Tate385e4982013-07-23 18:22:29 -0700701 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700702 }
703
704 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
705 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700706 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700707 rebatchAllAlarmsLocked(true);
708 }
709 }
710
711 void rebatchAllAlarmsLocked(boolean doValidate) {
712 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
713 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700714 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700715 final long nowElapsed = SystemClock.elapsedRealtime();
716 final int oldBatches = oldSet.size();
717 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
718 Batch batch = oldSet.get(batchNum);
719 final int N = batch.size();
720 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700721 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700722 }
723 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700724 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
725 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
726 + " to " + mPendingIdleUntil);
727 if (mPendingIdleUntil == null) {
728 // Somehow we lost this... we need to restore all of the pending alarms.
729 restorePendingWhileIdleAlarmsLocked();
730 }
731 }
732 rescheduleKernelAlarmsLocked();
733 updateNextAlarmClockLocked();
734 }
735
736 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
737 a.when = a.origWhen;
738 long whenElapsed = convertToElapsed(a.when, a.type);
739 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700740 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700741 // Exact
742 maxElapsed = whenElapsed;
743 } else {
744 // Not exact. Preserve any explicit window, otherwise recalculate
745 // the window based on the alarm's new futurity. Note that this
746 // reflects a policy of preferring timely to deferred delivery.
747 maxElapsed = (a.windowLength > 0)
748 ? (whenElapsed + a.windowLength)
749 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
750 }
751 a.whenElapsed = whenElapsed;
752 a.maxWhenElapsed = maxElapsed;
753 setImplLocked(a, true, doValidate);
754 }
755
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700756 /**
757 * Sends alarms that were blocked due to user applied background restrictions - either because
758 * the user lifted those or the uid came to foreground.
759 *
760 * @param uid uid to filter on
761 * @param packageName package to filter on, or null for all packages in uid
762 */
763 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
764 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
765 if (alarmsForUid == null || alarmsForUid.size() == 0) {
766 return;
767 }
768 final ArrayList<Alarm> alarmsToDeliver;
769 if (packageName != null) {
770 if (DEBUG_BG_LIMIT) {
771 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
772 }
773 alarmsToDeliver = new ArrayList<>();
774 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
775 final Alarm a = alarmsForUid.get(i);
776 if (a.matches(packageName)) {
777 alarmsToDeliver.add(alarmsForUid.remove(i));
778 }
779 }
780 if (alarmsForUid.size() == 0) {
781 mPendingBackgroundAlarms.remove(uid);
782 }
783 } else {
784 if (DEBUG_BG_LIMIT) {
785 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
786 }
787 alarmsToDeliver = alarmsForUid;
788 mPendingBackgroundAlarms.remove(uid);
789 }
790 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
791 }
792
Makoto Onuki2206af32017-11-21 16:25:35 -0800793 /**
794 * Check all alarms in {@link #mPendingBackgroundAlarms} and send the ones that are not
795 * restricted.
796 *
797 * This is only called when the global "force all apps-standby" flag changes or when the
798 * power save whitelist changes, so it's okay to be slow.
799 */
800 void sendAllUnrestrictedPendingBackgroundAlarmsLocked() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700801 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
Makoto Onuki2206af32017-11-21 16:25:35 -0800802
803 findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
804 mPendingBackgroundAlarms, alarmsToDeliver, this::isBackgroundRestricted);
805
806 if (alarmsToDeliver.size() > 0) {
807 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
808 }
809 }
810
811 @VisibleForTesting
812 static void findAllUnrestrictedPendingBackgroundAlarmsLockedInner(
813 SparseArray<ArrayList<Alarm>> pendingAlarms, ArrayList<Alarm> unrestrictedAlarms,
814 Predicate<Alarm> isBackgroundRestricted) {
815
816 for (int uidIndex = pendingAlarms.size() - 1; uidIndex >= 0; uidIndex--) {
817 final int uid = pendingAlarms.keyAt(uidIndex);
818 final ArrayList<Alarm> alarmsForUid = pendingAlarms.valueAt(uidIndex);
819
820 for (int alarmIndex = alarmsForUid.size() - 1; alarmIndex >= 0; alarmIndex--) {
821 final Alarm alarm = alarmsForUid.get(alarmIndex);
822
823 if (isBackgroundRestricted.test(alarm)) {
824 continue;
825 }
826
827 unrestrictedAlarms.add(alarm);
828 alarmsForUid.remove(alarmIndex);
829 }
830
831 if (alarmsForUid.size() == 0) {
832 pendingAlarms.removeAt(uidIndex);
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700833 }
834 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700835 }
836
837 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
838 final int N = alarms.size();
839 boolean hasWakeup = false;
840 for (int i = 0; i < N; i++) {
841 final Alarm alarm = alarms.get(i);
842 if (alarm.wakeup) {
843 hasWakeup = true;
844 }
845 alarm.count = 1;
846 // Recurring alarms may have passed several alarm intervals while the
847 // alarm was kept pending. Send the appropriate trigger count.
848 if (alarm.repeatInterval > 0) {
849 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
850 // Also schedule its next recurrence
851 final long delta = alarm.count * alarm.repeatInterval;
852 final long nextElapsed = alarm.whenElapsed + delta;
853 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
854 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
855 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
856 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
857 // Kernel alarms will be rescheduled as needed in setImplLocked
858 }
859 }
860 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
861 // No need to wakeup for non wakeup alarms
862 if (mPendingNonWakeupAlarms.size() == 0) {
863 mStartCurrentDelayTime = nowELAPSED;
864 mNextNonWakeupDeliveryTime = nowELAPSED
865 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
866 }
867 mPendingNonWakeupAlarms.addAll(alarms);
868 mNumDelayedAlarms += alarms.size();
869 } else {
870 if (DEBUG_BG_LIMIT) {
871 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
872 }
873 // Since we are waking up, also deliver any pending non wakeup alarms we have.
874 if (mPendingNonWakeupAlarms.size() > 0) {
875 alarms.addAll(mPendingNonWakeupAlarms);
876 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
877 mTotalDelayTime += thisDelayTime;
878 if (mMaxDelayTime < thisDelayTime) {
879 mMaxDelayTime = thisDelayTime;
880 }
881 mPendingNonWakeupAlarms.clear();
882 }
883 calculateDeliveryPriorities(alarms);
884 Collections.sort(alarms, mAlarmDispatchComparator);
885 deliverAlarmsLocked(alarms, nowELAPSED);
886 }
887 }
888
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700889 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700890 if (RECORD_DEVICE_IDLE_ALARMS) {
891 IdleDispatchEntry ent = new IdleDispatchEntry();
892 ent.uid = 0;
893 ent.pkg = "FINISH IDLE";
894 ent.elapsedRealtime = SystemClock.elapsedRealtime();
895 mAllowWhileIdleDispatches.add(ent);
896 }
897
Dianne Hackborn35d54032015-04-23 10:30:43 -0700898 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700899 if (mPendingWhileIdleAlarms.size() > 0) {
900 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
901 mPendingWhileIdleAlarms = new ArrayList<>();
902 final long nowElapsed = SystemClock.elapsedRealtime();
903 for (int i=alarms.size() - 1; i >= 0; i--) {
904 Alarm a = alarms.get(i);
905 reAddAlarmLocked(a, nowElapsed, false);
906 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700907 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700908
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700909 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700910 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700911
Dianne Hackborn35d54032015-04-23 10:30:43 -0700912 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700913 rescheduleKernelAlarmsLocked();
914 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700915
916 // And send a TIME_TICK right now, since it is important to get the UI updated.
917 try {
918 mTimeTickSender.send();
919 } catch (PendingIntent.CanceledException e) {
920 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700921 }
922
Christopher Tate14a7bb02015-10-01 10:24:31 -0700923 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800924 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700925 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700926 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -0700927 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700928 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700929 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800930 final BroadcastStats mBroadcastStats;
931 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800932 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800933
Christopher Tate14a7bb02015-10-01 10:24:31 -0700934 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
935 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
936 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -0800937 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700938 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700939 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -0700940 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700941 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700942 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700943 mBroadcastStats = (pendingIntent != null)
944 ? service.getStatsLocked(pendingIntent)
945 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700946 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -0800947 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700948 fs = new FilterStats(mBroadcastStats, mTag);
949 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -0800950 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700951 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -0800952 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -0800953 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -0800954 }
Makoto Onuki33955e12017-03-01 18:11:00 -0800955
956 @Override
957 public String toString() {
958 return "InFlight{"
959 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -0700960 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -0800961 + ", workSource=" + mWorkSource
962 + ", uid=" + mUid
963 + ", tag=" + mTag
964 + ", broadcastStats=" + mBroadcastStats
965 + ", filterStats=" + mFilterStats
966 + ", alarmType=" + mAlarmType
967 + "}";
968 }
Kweku Adams61e03292017-10-19 14:27:12 -0700969
970 public void writeToProto(ProtoOutputStream proto, long fieldId) {
971 final long token = proto.start(fieldId);
972
973 proto.write(InFlightProto.UID, mUid);
974 proto.write(InFlightProto.TAG, mTag);
975 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
976 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
977 if (mPendingIntent != null) {
978 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
979 }
980 if (mBroadcastStats != null) {
981 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
982 }
983 if (mFilterStats != null) {
984 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
985 }
986 if (mWorkSource != null) {
987 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
988 }
989
990 proto.end(token);
991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
Dianne Hackborn81038902012-11-26 17:04:09 -0800993
Adam Lesinski182f73f2013-12-05 16:48:06 -0800994 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -0800995 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700996 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -0800997
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700998 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001000 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001001 int numWakeup;
1002 long startTime;
1003 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001004
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001005 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001006 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001007 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001008 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001009
1010 @Override
1011 public String toString() {
1012 return "FilterStats{"
1013 + "tag=" + mTag
1014 + ", lastTime=" + lastTime
1015 + ", aggregateTime=" + aggregateTime
1016 + ", count=" + count
1017 + ", numWakeup=" + numWakeup
1018 + ", startTime=" + startTime
1019 + ", nesting=" + nesting
1020 + "}";
1021 }
Kweku Adams61e03292017-10-19 14:27:12 -07001022
1023 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1024 final long token = proto.start(fieldId);
1025
1026 proto.write(FilterStatsProto.TAG, mTag);
1027 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1028 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1029 proto.write(FilterStatsProto.COUNT, count);
1030 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1031 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1032 proto.write(FilterStatsProto.NESTING, nesting);
1033
1034 proto.end(token);
1035 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001036 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001037
Adam Lesinski182f73f2013-12-05 16:48:06 -08001038 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001039 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001040 final String mPackageName;
1041
1042 long aggregateTime;
1043 int count;
1044 int numWakeup;
1045 long startTime;
1046 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001047 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001048
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001049 BroadcastStats(int uid, String packageName) {
1050 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001051 mPackageName = packageName;
1052 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001053
1054 @Override
1055 public String toString() {
1056 return "BroadcastStats{"
1057 + "uid=" + mUid
1058 + ", packageName=" + mPackageName
1059 + ", aggregateTime=" + aggregateTime
1060 + ", count=" + count
1061 + ", numWakeup=" + numWakeup
1062 + ", startTime=" + startTime
1063 + ", nesting=" + nesting
1064 + "}";
1065 }
Kweku Adams61e03292017-10-19 14:27:12 -07001066
1067 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1068 final long token = proto.start(fieldId);
1069
1070 proto.write(BroadcastStatsProto.UID, mUid);
1071 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1072 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1073 proto.write(BroadcastStatsProto.COUNT, count);
1074 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1075 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1076 proto.write(BroadcastStatsProto.NESTING, nesting);
1077
1078 proto.end(token);
1079 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001080 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001081
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001082 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1083 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001084
1085 int mNumDelayedAlarms = 0;
1086 long mTotalDelayTime = 0;
1087 long mMaxDelayTime = 0;
1088
Adam Lesinski182f73f2013-12-05 16:48:06 -08001089 @Override
1090 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001091 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001092 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001093
1094 // We have to set current TimeZone info to kernel
1095 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001096 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001097
Christopher Tate247571462017-04-10 11:45:05 -07001098 // Also sure that we're booting with a halfway sensible current time
1099 if (mNativeData != 0) {
1100 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1101 if (System.currentTimeMillis() < systemBuildTime) {
1102 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1103 + ", advancing to build time " + systemBuildTime);
1104 setKernelTime(mNativeData, systemBuildTime);
1105 }
1106 }
1107
Christopher Tatebb9cce52017-04-18 14:19:43 -07001108 // Determine SysUI's uid
1109 final PackageManager packMan = getContext().getPackageManager();
1110 try {
1111 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1112 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1113 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1114 mSystemUiUid = sysUi.uid;
1115 } else {
1116 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1117 + " defined by non-privileged app " + sysUi.packageName
1118 + " - ignoring");
1119 }
1120 } catch (NameNotFoundException e) {
1121 }
1122
1123 if (mSystemUiUid <= 0) {
1124 Slog.wtf(TAG, "SysUI package not found!");
1125 }
1126
Adam Lesinski182f73f2013-12-05 16:48:06 -08001127 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001128 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001129
Adam Lesinski182f73f2013-12-05 16:48:06 -08001130 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001132 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001133 | Intent.FLAG_RECEIVER_FOREGROUND
1134 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001135 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001136 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001137 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1138 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001139 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001140 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001141
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001143 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 mClockReceiver.scheduleTimeTickEvent();
1145 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001146 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001147 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001148
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001149 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001150 AlarmThread waitThread = new AlarmThread();
1151 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001152 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001153 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001155
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001156 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001157 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001158 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1159 | ActivityManager.UID_OBSERVER_ACTIVE,
1160 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001161 } catch (RemoteException e) {
1162 // ignored; both services live in system_server
1163 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001164 publishBinderService(Context.ALARM_SERVICE, mService);
Makoto Onuki2206af32017-11-21 16:25:35 -08001165 mForceAppStandbyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001167
1168 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001169 public void onBootPhase(int phase) {
1170 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1171 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001172 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001173 mLocalDeviceIdleController
1174 = LocalServices.getService(DeviceIdleController.LocalService.class);
Dianne Hackborna750a632015-06-16 17:18:23 -07001175 }
1176 }
1177
1178 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001179 protected void finalize() throws Throwable {
1180 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001181 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001182 } finally {
1183 super.finalize();
1184 }
1185 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001186
Adam Lesinski182f73f2013-12-05 16:48:06 -08001187 void setTimeZoneImpl(String tz) {
1188 if (TextUtils.isEmpty(tz)) {
1189 return;
David Christieebe51fc2013-07-26 13:23:29 -07001190 }
1191
Adam Lesinski182f73f2013-12-05 16:48:06 -08001192 TimeZone zone = TimeZone.getTimeZone(tz);
1193 // Prevent reentrant calls from stepping on each other when writing
1194 // the time zone property
1195 boolean timeZoneWasChanged = false;
1196 synchronized (this) {
1197 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1198 if (current == null || !current.equals(zone.getID())) {
1199 if (localLOGV) {
1200 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1201 }
1202 timeZoneWasChanged = true;
1203 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1204 }
1205
1206 // Update the kernel timezone information
1207 // Kernel tracks time offsets as 'minutes west of GMT'
1208 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001209 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001210 }
1211
1212 TimeZone.setDefault(null);
1213
1214 if (timeZoneWasChanged) {
1215 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001216 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001217 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001218 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001219 intent.putExtra("time-zone", zone.getID());
1220 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1221 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001223
Adam Lesinski182f73f2013-12-05 16:48:06 -08001224 void removeImpl(PendingIntent operation) {
1225 if (operation == null) {
1226 return;
1227 }
1228 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001229 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001230 }
1231 }
1232
1233 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001234 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1235 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1236 int callingUid, String callingPackage) {
1237 // must be *either* PendingIntent or AlarmReceiver, but not both
1238 if ((operation == null && directReceiver == null)
1239 || (operation != null && directReceiver != null)) {
1240 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1241 // NB: previous releases failed silently here, so we are continuing to do the same
1242 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 return;
1244 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001245
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001246 // Sanity check the window length. This will catch people mistakenly
1247 // trying to pass an end-of-window timestamp rather than a duration.
1248 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1249 Slog.w(TAG, "Window length " + windowLength
1250 + "ms suspiciously long; limiting to 1 hour");
1251 windowLength = AlarmManager.INTERVAL_HOUR;
1252 }
1253
Christopher Tate498c6cb2014-11-17 16:09:27 -08001254 // Sanity check the recurrence interval. This will catch people who supply
1255 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001256 final long minInterval = mConstants.MIN_INTERVAL;
1257 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001258 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001259 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001260 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001261 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001262 }
1263
Christopher Tatee0a22b32013-07-11 14:43:13 -07001264 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1265 throw new IllegalArgumentException("Invalid alarm type " + type);
1266 }
1267
Christopher Tate5f221e82013-07-30 17:13:15 -07001268 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001269 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001270 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001271 + " pid=" + what);
1272 triggerAtTime = 0;
1273 }
1274
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001275 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001276 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1277 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001278 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001279 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1280
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001281 final long maxElapsed;
1282 if (windowLength == AlarmManager.WINDOW_EXACT) {
1283 maxElapsed = triggerElapsed;
1284 } else if (windowLength < 0) {
1285 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001286 // Fix this window in place, so that as time approaches we don't collapse it.
1287 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001288 } else {
1289 maxElapsed = triggerElapsed + windowLength;
1290 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001291
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001293 if (DEBUG_BATCH) {
1294 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001295 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001296 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001297 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001299 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001300 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1301 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001302 }
1303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304
Christopher Tate3e04b472013-10-21 17:51:31 -07001305 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001306 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1307 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1308 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001309 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001310 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1311 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001312 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001313 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001314 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1315 + " -- package not allowed to start");
1316 return;
1317 }
1318 } catch (RemoteException e) {
1319 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001320 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001321 setImplLocked(a, false, doValidate);
1322 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001323
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001324 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1325 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001326 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001327 // The caller has given the time they want this to happen at, however we need
1328 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001329 // bring us out of idle at an earlier time.
1330 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001331 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001332 }
1333 // Add fuzz to make the alarm go off some time before the actual desired time.
1334 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001335 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001336 if (fuzz > 0) {
1337 if (mRandom == null) {
1338 mRandom = new Random();
1339 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001340 final int delta = mRandom.nextInt(fuzz);
1341 a.whenElapsed -= delta;
1342 if (false) {
1343 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1344 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1345 Slog.d(TAG, "Applied fuzz: " + fuzz);
1346 Slog.d(TAG, "Final delta: " + delta);
1347 Slog.d(TAG, "Final when: " + a.whenElapsed);
1348 }
1349 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001350 }
1351
1352 } else if (mPendingIdleUntil != null) {
1353 // We currently have an idle until alarm scheduled; if the new alarm has
1354 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001355 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1356 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1357 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001358 == 0) {
1359 mPendingWhileIdleAlarms.add(a);
1360 return;
1361 }
1362 }
1363
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001364 if (RECORD_DEVICE_IDLE_ALARMS) {
1365 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1366 IdleDispatchEntry ent = new IdleDispatchEntry();
1367 ent.uid = a.uid;
1368 ent.pkg = a.operation.getCreatorPackage();
1369 ent.tag = a.operation.getTag("");
1370 ent.op = "SET";
1371 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1372 ent.argRealtime = a.whenElapsed;
1373 mAllowWhileIdleDispatches.add(ent);
1374 }
1375 }
1376
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001377 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1378 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001379 if (whichBatch < 0) {
1380 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001381 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001382 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001383 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001384 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001385 // The start time of this batch advanced, so batch ordering may
1386 // have just been broken. Move it to where it now belongs.
1387 mAlarmBatches.remove(whichBatch);
1388 addBatchLocked(mAlarmBatches, batch);
1389 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001390 }
1391
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001392 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001393 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001394 }
1395
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001396 boolean needRebatch = false;
1397
1398 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001399 if (RECORD_DEVICE_IDLE_ALARMS) {
1400 if (mPendingIdleUntil == null) {
1401 IdleDispatchEntry ent = new IdleDispatchEntry();
1402 ent.uid = 0;
1403 ent.pkg = "START IDLE";
1404 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1405 mAllowWhileIdleDispatches.add(ent);
1406 }
1407 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001408 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1409 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1410 + " to " + a);
1411 }
1412
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001413 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001414 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001415 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001416 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1417 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1418 mNextWakeFromIdle = a;
1419 // If this wake from idle is earlier than whatever was previously scheduled,
1420 // and we are currently idling, then we need to rebatch alarms in case the idle
1421 // until time needs to be updated.
1422 if (mPendingIdleUntil != null) {
1423 needRebatch = true;
1424 }
1425 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001426 }
1427
1428 if (!rebatching) {
1429 if (DEBUG_VALIDATE) {
1430 if (doValidate && !validateConsistencyLocked()) {
1431 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1432 + " when(hex)=" + Long.toHexString(a.when)
1433 + " whenElapsed=" + a.whenElapsed
1434 + " maxWhenElapsed=" + a.maxWhenElapsed
1435 + " interval=" + a.repeatInterval + " op=" + a.operation
1436 + " flags=0x" + Integer.toHexString(a.flags));
1437 rebatchAllAlarmsLocked(false);
1438 needRebatch = false;
1439 }
1440 }
1441
1442 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001443 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001444 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001445
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001446 rescheduleKernelAlarmsLocked();
1447 updateNextAlarmClockLocked();
1448 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001449 }
1450
Christopher Tate1d99c392017-12-07 16:54:04 -08001451 /**
1452 * System-process internal API
1453 */
1454 private final class LocalService implements AlarmManagerInternal {
1455 @Override
1456 public void removeAlarmsForUid(int uid) {
1457 synchronized (mLock) {
1458 removeLocked(uid);
1459 }
1460 }
1461 }
1462
1463 /**
1464 * Public-facing binder interface
1465 */
Adam Lesinski182f73f2013-12-05 16:48:06 -08001466 private final IBinder mService = new IAlarmManager.Stub() {
1467 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001468 public void set(String callingPackage,
1469 int type, long triggerAtTime, long windowLength, long interval, int flags,
1470 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1471 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001472 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001473
1474 // make sure the caller is not lying about which package should be blamed for
1475 // wakelock time spent in alarm delivery
1476 mAppOps.checkPackage(callingUid, callingPackage);
1477
1478 // Repeating alarms must use PendingIntent, not direct listener
1479 if (interval != 0) {
1480 if (directReceiver != null) {
1481 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1482 }
1483 }
1484
Adam Lesinski182f73f2013-12-05 16:48:06 -08001485 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001486 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001487 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001488 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001489 }
1490
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001491 // No incoming callers can request either WAKE_FROM_IDLE or
1492 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1493 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1494 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1495
1496 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1497 // manager when to come out of idle mode, which is only for DeviceIdleController.
1498 if (callingUid != Process.SYSTEM_UID) {
1499 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1500 }
1501
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001502 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001503 if (windowLength == AlarmManager.WINDOW_EXACT) {
1504 flags |= AlarmManager.FLAG_STANDALONE;
1505 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001506
1507 // If this alarm is for an alarm clock, then it must be standalone and we will
1508 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001509 if (alarmClock != null) {
1510 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001511
1512 // If the caller is a core system component or on the user's whitelist, and not calling
1513 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1514 // This means we will allow these alarms to go off as normal even while idle, with no
1515 // timing restrictions.
1516 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001517 || callingUid == mSystemUiUid
Makoto Onuki2206af32017-11-21 16:25:35 -08001518 || mForceAppStandbyTracker.isUidPowerSaveWhitelisted(callingUid))) {
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001519 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1520 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001521 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001522
Christopher Tate14a7bb02015-10-01 10:24:31 -07001523 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1524 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001525 }
Christopher Tate89779822012-08-31 14:40:03 -07001526
Adam Lesinski182f73f2013-12-05 16:48:06 -08001527 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001528 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001529 getContext().enforceCallingOrSelfPermission(
1530 "android.permission.SET_TIME",
1531 "setTime");
1532
Greg Hackmann0cab8962014-02-21 16:35:52 -08001533 if (mNativeData == 0) {
1534 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1535 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001536 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001537
1538 synchronized (mLock) {
1539 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001542
1543 @Override
1544 public void setTimeZone(String tz) {
1545 getContext().enforceCallingOrSelfPermission(
1546 "android.permission.SET_TIME_ZONE",
1547 "setTimeZone");
1548
1549 final long oldId = Binder.clearCallingIdentity();
1550 try {
1551 setTimeZoneImpl(tz);
1552 } finally {
1553 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001556
Adam Lesinski182f73f2013-12-05 16:48:06 -08001557 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001558 public void remove(PendingIntent operation, IAlarmListener listener) {
1559 if (operation == null && listener == null) {
1560 Slog.w(TAG, "remove() with no intent or listener");
1561 return;
1562 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001563
Christopher Tate14a7bb02015-10-01 10:24:31 -07001564 synchronized (mLock) {
1565 removeLocked(operation, listener);
1566 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001567 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001568
Adam Lesinski182f73f2013-12-05 16:48:06 -08001569 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001570 public long getNextWakeFromIdleTime() {
1571 return getNextWakeFromIdleTimeImpl();
1572 }
1573
1574 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001575 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001576 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1577 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1578 "getNextAlarmClock", null);
1579
1580 return getNextAlarmClockImpl(userId);
1581 }
1582
1583 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001584 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001585 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001586
1587 if (args.length > 0 && "--proto".equals(args[0])) {
1588 dumpProto(fd);
1589 } else {
1590 dumpImpl(pw);
1591 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001592 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001593 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001594
Adam Lesinski182f73f2013-12-05 16:48:06 -08001595 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 synchronized (mLock) {
1597 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001598 mConstants.dump(pw);
1599 pw.println();
1600
Makoto Onuki2206af32017-11-21 16:25:35 -08001601 mForceAppStandbyTracker.dump(pw, " ");
Christopher Tate12cf0b62018-01-05 18:40:14 -08001602 pw.println();
Makoto Onuki2206af32017-11-21 16:25:35 -08001603
Christopher Tatee0a22b32013-07-11 14:43:13 -07001604 final long nowRTC = System.currentTimeMillis();
1605 final long nowELAPSED = SystemClock.elapsedRealtime();
1606 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1607
Dianne Hackborna750a632015-06-16 17:18:23 -07001608 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001609 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001610 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001611 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001612 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001613 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Christopher Tate12cf0b62018-01-05 18:40:14 -08001614 pw.print(" mLastTimeChangeRealtime="); pw.println(mLastTimeChangeRealtime);
1615 pw.print(" mLastTickIssued=");
1616 TimeUtils.formatDuration(mLastTickIssued - nowELAPSED, pw);
1617 pw.println();
1618 pw.print(" mLastTickReceived="); pw.println(sdf.format(new Date(mLastTickReceived)));
1619 pw.print(" mLastTickSet="); pw.println(sdf.format(new Date(mLastTickSet)));
Dianne Hackbornc3527222015-05-13 14:03:20 -07001620 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001621 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001622 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001623 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1624 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001625 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001626 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1627 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001628 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001629 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1630 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001631 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001632 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1633 pw.println();
1634 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001635
1636 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1637 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001638 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001639 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001640 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001641 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001642 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001643 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1644 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1645 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001646 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001647
John Spurlock604a5ee2015-06-01 12:27:22 -04001648 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001649 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001650 final TreeSet<Integer> users = new TreeSet<>();
1651 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1652 users.add(mNextAlarmClockForUser.keyAt(i));
1653 }
1654 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1655 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1656 }
1657 for (int user : users) {
1658 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1659 final long time = next != null ? next.getTriggerTime() : 0;
1660 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001661 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001662 pw.print(" pendingSend:"); pw.print(pendingSend);
1663 pw.print(" time:"); pw.print(time);
1664 if (time > 0) {
1665 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1666 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1667 }
1668 pw.println();
1669 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001670 if (mAlarmBatches.size() > 0) {
1671 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001672 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001673 pw.println(mAlarmBatches.size());
1674 for (Batch b : mAlarmBatches) {
1675 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001676 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001677 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001678 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001679 pw.println();
1680 pw.println(" Pending user blocked background alarms: ");
1681 boolean blocked = false;
1682 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1683 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1684 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1685 blocked = true;
1686 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1687 }
1688 }
1689 if (!blocked) {
1690 pw.println(" none");
1691 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001692 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001693 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001694 pw.println(" Idle mode state:");
1695 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001696 if (mPendingIdleUntil != null) {
1697 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001698 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001699 } else {
1700 pw.println("null");
1701 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001702 pw.println(" Pending alarms:");
1703 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001704 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001705 if (mNextWakeFromIdle != null) {
1706 pw.println();
1707 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001708 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001709 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001710
1711 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001712 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001713 if (mPendingNonWakeupAlarms.size() > 0) {
1714 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001715 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001716 } else {
1717 pw.println("(none)");
1718 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001719 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001720 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1721 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001722 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001723 pw.print(", max non-interactive time: ");
1724 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1725 pw.println();
1726
1727 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001728 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001729 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1730 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1731 pw.print(" Listener send count: "); pw.println(mListenerCount);
1732 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001733 pw.println();
1734
Christopher Tate7f2a0352015-12-08 10:24:33 -08001735 if (mInFlight.size() > 0) {
1736 pw.println("Outstanding deliveries:");
1737 for (int i = 0; i < mInFlight.size(); i++) {
1738 pw.print(" #"); pw.print(i); pw.print(": ");
1739 pw.println(mInFlight.get(i));
1740 }
1741 pw.println();
1742 }
1743
Dianne Hackborna750a632015-06-16 17:18:23 -07001744 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001745 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1746 pw.println();
1747 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001748 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001749 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1750 pw.print(" UID ");
1751 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1752 pw.print(": ");
1753 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1754 nowELAPSED, pw);
1755 pw.println();
1756 }
1757 }
1758 pw.println();
1759
Dianne Hackborn81038902012-11-26 17:04:09 -08001760 if (mLog.dump(pw, " Recent problems", " ")) {
1761 pw.println();
1762 }
1763
1764 final FilterStats[] topFilters = new FilterStats[10];
1765 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1766 @Override
1767 public int compare(FilterStats lhs, FilterStats rhs) {
1768 if (lhs.aggregateTime < rhs.aggregateTime) {
1769 return 1;
1770 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1771 return -1;
1772 }
1773 return 0;
1774 }
1775 };
1776 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001777 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001778 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1779 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1780 for (int ip=0; ip<uidStats.size(); ip++) {
1781 BroadcastStats bs = uidStats.valueAt(ip);
1782 for (int is=0; is<bs.filterStats.size(); is++) {
1783 FilterStats fs = bs.filterStats.valueAt(is);
1784 int pos = len > 0
1785 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1786 if (pos < 0) {
1787 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001788 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001789 if (pos < topFilters.length) {
1790 int copylen = topFilters.length - pos - 1;
1791 if (copylen > 0) {
1792 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1793 }
1794 topFilters[pos] = fs;
1795 if (len < topFilters.length) {
1796 len++;
1797 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001798 }
1799 }
1800 }
1801 }
1802 if (len > 0) {
1803 pw.println(" Top Alarms:");
1804 for (int i=0; i<len; i++) {
1805 FilterStats fs = topFilters[i];
1806 pw.print(" ");
1807 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1808 TimeUtils.formatDuration(fs.aggregateTime, pw);
1809 pw.print(" running, "); pw.print(fs.numWakeup);
1810 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001811 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1812 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001813 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001814 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001815 pw.println();
1816 }
1817 }
1818
1819 pw.println(" ");
1820 pw.println(" Alarm Stats:");
1821 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001822 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1823 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1824 for (int ip=0; ip<uidStats.size(); ip++) {
1825 BroadcastStats bs = uidStats.valueAt(ip);
1826 pw.print(" ");
1827 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1828 UserHandle.formatUid(pw, bs.mUid);
1829 pw.print(":");
1830 pw.print(bs.mPackageName);
1831 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1832 pw.print(" running, "); pw.print(bs.numWakeup);
1833 pw.println(" wakeups:");
1834 tmpFilters.clear();
1835 for (int is=0; is<bs.filterStats.size(); is++) {
1836 tmpFilters.add(bs.filterStats.valueAt(is));
1837 }
1838 Collections.sort(tmpFilters, comparator);
1839 for (int i=0; i<tmpFilters.size(); i++) {
1840 FilterStats fs = tmpFilters.get(i);
1841 pw.print(" ");
1842 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1843 TimeUtils.formatDuration(fs.aggregateTime, pw);
1844 pw.print(" "); pw.print(fs.numWakeup);
1845 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001846 pw.print(" alarms, last ");
1847 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1848 pw.println(":");
1849 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001850 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001851 pw.println();
1852 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001853 }
1854 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001855
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001856 if (RECORD_DEVICE_IDLE_ALARMS) {
1857 pw.println();
1858 pw.println(" Allow while idle dispatches:");
1859 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1860 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1861 pw.print(" ");
1862 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1863 pw.print(": ");
1864 UserHandle.formatUid(pw, ent.uid);
1865 pw.print(":");
1866 pw.println(ent.pkg);
1867 if (ent.op != null) {
1868 pw.print(" ");
1869 pw.print(ent.op);
1870 pw.print(" / ");
1871 pw.print(ent.tag);
1872 if (ent.argRealtime != 0) {
1873 pw.print(" (");
1874 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1875 pw.print(")");
1876 }
1877 pw.println();
1878 }
1879 }
1880 }
1881
Christopher Tate18a75f12013-07-01 18:18:59 -07001882 if (WAKEUP_STATS) {
1883 pw.println();
1884 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001885 long last = -1;
1886 for (WakeupEvent event : mRecentWakeups) {
1887 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1888 pw.print('|');
1889 if (last < 0) {
1890 pw.print('0');
1891 } else {
1892 pw.print(event.when - last);
1893 }
1894 last = event.when;
1895 pw.print('|'); pw.print(event.uid);
1896 pw.print('|'); pw.print(event.action);
1897 pw.println();
1898 }
1899 pw.println();
1900 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
1902 }
1903
Kweku Adams61e03292017-10-19 14:27:12 -07001904 void dumpProto(FileDescriptor fd) {
1905 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1906
1907 synchronized (mLock) {
1908 final long nowRTC = System.currentTimeMillis();
1909 final long nowElapsed = SystemClock.elapsedRealtime();
1910 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1911 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1912 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1913 mLastTimeChangeClockTime);
1914 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
1915 mLastTimeChangeRealtime);
1916
1917 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
1918
Makoto Onuki2206af32017-11-21 16:25:35 -08001919 mForceAppStandbyTracker.dumpProto(proto,
1920 AlarmManagerServiceProto.FORCE_APP_STANDBY_TRACKER);
Kweku Adams61e03292017-10-19 14:27:12 -07001921
1922 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
1923 if (!mInteractive) {
1924 // Durations
1925 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
1926 nowElapsed - mNonInteractiveStartTime);
1927 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
1928 currentNonWakeupFuzzLocked(nowElapsed));
1929 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
1930 nowElapsed - mLastAlarmDeliveryTime);
1931 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
1932 nowElapsed - mNextNonWakeupDeliveryTime);
1933 }
1934
1935 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
1936 mNextNonWakeup - nowElapsed);
1937 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
1938 mNextWakeup - nowElapsed);
1939 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
1940 nowElapsed - mLastWakeup);
1941 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
1942 nowElapsed - mLastWakeupSet);
1943 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
Kweku Adams61e03292017-10-19 14:27:12 -07001944
1945 final TreeSet<Integer> users = new TreeSet<>();
1946 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
1947 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
1948 users.add(mNextAlarmClockForUser.keyAt(i));
1949 }
1950 final int pendingSendNextAlarmClockChangedForUserSize =
1951 mPendingSendNextAlarmClockChangedForUser.size();
1952 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
1953 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1954 }
1955 for (int user : users) {
1956 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1957 final long time = next != null ? next.getTriggerTime() : 0;
1958 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
1959 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
1960 proto.write(AlarmClockMetadataProto.USER, user);
1961 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
1962 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
1963 proto.end(aToken);
1964 }
1965 for (Batch b : mAlarmBatches) {
1966 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
1967 nowElapsed, nowRTC);
1968 }
1969 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1970 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1971 if (blockedAlarms != null) {
1972 for (Alarm a : blockedAlarms) {
1973 a.writeToProto(proto,
1974 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
1975 nowElapsed, nowRTC);
1976 }
1977 }
1978 }
1979 if (mPendingIdleUntil != null) {
1980 mPendingIdleUntil.writeToProto(
1981 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
1982 }
1983 for (Alarm a : mPendingWhileIdleAlarms) {
1984 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
1985 nowElapsed, nowRTC);
1986 }
1987 if (mNextWakeFromIdle != null) {
1988 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
1989 nowElapsed, nowRTC);
1990 }
1991
1992 for (Alarm a : mPendingNonWakeupAlarms) {
1993 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
1994 nowElapsed, nowRTC);
1995 }
1996
1997 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
1998 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
1999 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2000 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2001 mNonInteractiveTime);
2002
2003 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2004 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2005 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2006 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2007 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2008
2009 for (InFlight f : mInFlight) {
2010 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2011 }
2012
2013 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2014 mAllowWhileIdleMinTime);
2015 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2016 final long token = proto.start(
2017 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2018 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2019 mLastAllowWhileIdleDispatch.keyAt(i));
2020 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2021 mLastAllowWhileIdleDispatch.valueAt(i));
2022 proto.end(token);
2023 }
2024
2025 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2026
2027 final FilterStats[] topFilters = new FilterStats[10];
2028 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2029 @Override
2030 public int compare(FilterStats lhs, FilterStats rhs) {
2031 if (lhs.aggregateTime < rhs.aggregateTime) {
2032 return 1;
2033 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2034 return -1;
2035 }
2036 return 0;
2037 }
2038 };
2039 int len = 0;
2040 // Get the top 10 FilterStats, ordered by aggregateTime.
2041 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2042 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2043 for (int ip = 0; ip < uidStats.size(); ++ip) {
2044 BroadcastStats bs = uidStats.valueAt(ip);
2045 for (int is = 0; is < bs.filterStats.size(); ++is) {
2046 FilterStats fs = bs.filterStats.valueAt(is);
2047 int pos = len > 0
2048 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2049 if (pos < 0) {
2050 pos = -pos - 1;
2051 }
2052 if (pos < topFilters.length) {
2053 int copylen = topFilters.length - pos - 1;
2054 if (copylen > 0) {
2055 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2056 }
2057 topFilters[pos] = fs;
2058 if (len < topFilters.length) {
2059 len++;
2060 }
2061 }
2062 }
2063 }
2064 }
2065 for (int i = 0; i < len; ++i) {
2066 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2067 FilterStats fs = topFilters[i];
2068
2069 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2070 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2071 fs.mBroadcastStats.mPackageName);
2072 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2073
2074 proto.end(token);
2075 }
2076
2077 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2078 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2079 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2080 for (int ip = 0; ip < uidStats.size(); ++ip) {
2081 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2082
2083 BroadcastStats bs = uidStats.valueAt(ip);
2084 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2085
2086 // uidStats is an ArrayMap, which we can't sort.
2087 tmpFilters.clear();
2088 for (int is = 0; is < bs.filterStats.size(); ++is) {
2089 tmpFilters.add(bs.filterStats.valueAt(is));
2090 }
2091 Collections.sort(tmpFilters, comparator);
2092 for (FilterStats fs : tmpFilters) {
2093 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2094 }
2095
2096 proto.end(token);
2097 }
2098 }
2099
2100 if (RECORD_DEVICE_IDLE_ALARMS) {
2101 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2102 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2103 final long token = proto.start(
2104 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2105
2106 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2107 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2108 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2109 proto.write(IdleDispatchEntryProto.OP, ent.op);
2110 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2111 ent.elapsedRealtime);
2112 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2113
2114 proto.end(token);
2115 }
2116 }
2117
2118 if (WAKEUP_STATS) {
2119 for (WakeupEvent event : mRecentWakeups) {
2120 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2121 proto.write(WakeupEventProto.UID, event.uid);
2122 proto.write(WakeupEventProto.ACTION, event.action);
2123 proto.write(WakeupEventProto.WHEN, event.when);
2124 proto.end(token);
2125 }
2126 }
2127 }
2128
2129 proto.flush();
2130 }
2131
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002132 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002133 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2134 PrintWriter pw = new PrintWriter(bs);
2135 final long nowRTC = System.currentTimeMillis();
2136 final long nowELAPSED = SystemClock.elapsedRealtime();
2137 final int NZ = mAlarmBatches.size();
2138 for (int iz = 0; iz < NZ; iz++) {
2139 Batch bz = mAlarmBatches.get(iz);
2140 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002141 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002142 pw.flush();
2143 Slog.v(TAG, bs.toString());
2144 bs.reset();
2145 }
2146 }
2147
2148 private boolean validateConsistencyLocked() {
2149 if (DEBUG_VALIDATE) {
2150 long lastTime = Long.MIN_VALUE;
2151 final int N = mAlarmBatches.size();
2152 for (int i = 0; i < N; i++) {
2153 Batch b = mAlarmBatches.get(i);
2154 if (b.start >= lastTime) {
2155 // duplicate start times are okay because of standalone batches
2156 lastTime = b.start;
2157 } else {
2158 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002159 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2160 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002161 return false;
2162 }
2163 }
2164 }
2165 return true;
2166 }
2167
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002168 private Batch findFirstWakeupBatchLocked() {
2169 final int N = mAlarmBatches.size();
2170 for (int i = 0; i < N; i++) {
2171 Batch b = mAlarmBatches.get(i);
2172 if (b.hasWakeups()) {
2173 return b;
2174 }
2175 }
2176 return null;
2177 }
2178
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002179 long getNextWakeFromIdleTimeImpl() {
2180 synchronized (mLock) {
2181 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2182 }
2183 }
2184
2185 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002186 synchronized (mLock) {
2187 return mNextAlarmClockForUser.get(userId);
2188 }
2189 }
2190
2191 /**
2192 * Recomputes the next alarm clock for all users.
2193 */
2194 private void updateNextAlarmClockLocked() {
2195 if (!mNextAlarmClockMayChange) {
2196 return;
2197 }
2198 mNextAlarmClockMayChange = false;
2199
Jose Lima235510e2014-08-13 12:50:01 -07002200 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002201 nextForUser.clear();
2202
2203 final int N = mAlarmBatches.size();
2204 for (int i = 0; i < N; i++) {
2205 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2206 final int M = alarms.size();
2207
2208 for (int j = 0; j < M; j++) {
2209 Alarm a = alarms.get(j);
2210 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002211 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002212 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002213
2214 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002215 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002216 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002217 " for user " + userId);
2218 }
2219
2220 // Alarms and batches are sorted by time, no need to compare times here.
2221 if (nextForUser.get(userId) == null) {
2222 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002223 } else if (a.alarmClock.equals(current)
2224 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2225 // same/earlier time and it's the one we cited before, so stick with it
2226 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002227 }
2228 }
2229 }
2230 }
2231
2232 // Update mNextAlarmForUser with new values.
2233 final int NN = nextForUser.size();
2234 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002235 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002236 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002237 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002238 if (!newAlarm.equals(currentAlarm)) {
2239 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2240 }
2241 }
2242
2243 // Remove users without any alarm clocks scheduled.
2244 final int NNN = mNextAlarmClockForUser.size();
2245 for (int i = NNN - 1; i >= 0; i--) {
2246 int userId = mNextAlarmClockForUser.keyAt(i);
2247 if (nextForUser.get(userId) == null) {
2248 updateNextAlarmInfoForUserLocked(userId, null);
2249 }
2250 }
2251 }
2252
Jose Lima235510e2014-08-13 12:50:01 -07002253 private void updateNextAlarmInfoForUserLocked(int userId,
2254 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002255 if (alarmClock != null) {
2256 if (DEBUG_ALARM_CLOCK) {
2257 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002258 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002259 }
2260 mNextAlarmClockForUser.put(userId, alarmClock);
2261 } else {
2262 if (DEBUG_ALARM_CLOCK) {
2263 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2264 }
2265 mNextAlarmClockForUser.remove(userId);
2266 }
2267
2268 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2269 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2270 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2271 }
2272
2273 /**
2274 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2275 * for which alarm clocks have changed since the last call to this.
2276 *
2277 * Do not call with a lock held. Only call from mHandler's thread.
2278 *
2279 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2280 */
2281 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002282 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002283 pendingUsers.clear();
2284
2285 synchronized (mLock) {
2286 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2287 for (int i = 0; i < N; i++) {
2288 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2289 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2290 }
2291 mPendingSendNextAlarmClockChangedForUser.clear();
2292 }
2293
2294 final int N = pendingUsers.size();
2295 for (int i = 0; i < N; i++) {
2296 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002297 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002298 Settings.System.putStringForUser(getContext().getContentResolver(),
2299 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002300 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002301 userId);
2302
2303 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2304 new UserHandle(userId));
2305 }
2306 }
2307
2308 /**
2309 * Formats an alarm like platform/packages/apps/DeskClock used to.
2310 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002311 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2312 int userId) {
2313 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002314 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2315 return (info == null) ? "" :
2316 DateFormat.format(pattern, info.getTriggerTime()).toString();
2317 }
2318
Adam Lesinski182f73f2013-12-05 16:48:06 -08002319 void rescheduleKernelAlarmsLocked() {
2320 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2321 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002322 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002323 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002324 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002325 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002326 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002327 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002328 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002329 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002330 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002331 if (firstBatch != firstWakeup) {
2332 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002333 }
2334 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002335 if (mPendingNonWakeupAlarms.size() > 0) {
2336 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2337 nextNonWakeup = mNextNonWakeupDeliveryTime;
2338 }
2339 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002340 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002341 mNextNonWakeup = nextNonWakeup;
2342 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2343 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002344 }
2345
Christopher Tate14a7bb02015-10-01 10:24:31 -07002346 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Christopher Tate1d99c392017-12-07 16:54:04 -08002347 if (operation == null && directReceiver == null) {
2348 if (localLOGV) {
2349 Slog.w(TAG, "requested remove() of null operation",
2350 new RuntimeException("here"));
2351 }
2352 return;
2353 }
2354
Adam Lesinski182f73f2013-12-05 16:48:06 -08002355 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002356 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002357 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2358 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002359 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002360 if (b.size() == 0) {
2361 mAlarmBatches.remove(i);
2362 }
2363 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002364 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002365 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002366 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2367 mPendingWhileIdleAlarms.remove(i);
2368 }
2369 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002370 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2371 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2372 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2373 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2374 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2375 alarmsForUid.remove(j);
2376 }
2377 }
2378 if (alarmsForUid.size() == 0) {
2379 mPendingBackgroundAlarms.removeAt(i);
2380 }
2381 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002382 if (didRemove) {
2383 if (DEBUG_BATCH) {
2384 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2385 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002386 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002387 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002388 mPendingIdleUntil = null;
2389 restorePending = true;
2390 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002391 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002392 mNextWakeFromIdle = null;
2393 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002394 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002395 if (restorePending) {
2396 restorePendingWhileIdleAlarmsLocked();
2397 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002398 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002399 }
2400 }
2401
Christopher Tate1d99c392017-12-07 16:54:04 -08002402 void removeLocked(final int uid) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002403 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002404 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.uid == uid;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002405 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2406 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002407 didRemove |= b.remove(whichAlarms);
2408 if (b.size() == 0) {
2409 mAlarmBatches.remove(i);
2410 }
2411 }
2412 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2413 final Alarm a = mPendingWhileIdleAlarms.get(i);
2414 if (a.uid == uid) {
2415 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2416 mPendingWhileIdleAlarms.remove(i);
2417 }
2418 }
2419 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2420 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2421 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2422 if (alarmsForUid.get(j).uid == uid) {
2423 alarmsForUid.remove(j);
2424 }
2425 }
2426 if (alarmsForUid.size() == 0) {
2427 mPendingBackgroundAlarms.removeAt(i);
2428 }
2429 }
2430 if (didRemove) {
2431 if (DEBUG_BATCH) {
2432 Slog.v(TAG, "remove(uid) changed bounds; rebatching");
2433 }
2434 rebatchAllAlarmsLocked(true);
2435 rescheduleKernelAlarmsLocked();
2436 updateNextAlarmClockLocked();
2437 }
2438 }
2439
2440 void removeLocked(final String packageName) {
2441 if (packageName == null) {
2442 if (localLOGV) {
2443 Slog.w(TAG, "requested remove() of null packageName",
2444 new RuntimeException("here"));
2445 }
2446 return;
2447 }
2448
2449 boolean didRemove = false;
2450 final Predicate<Alarm> whichAlarms = (Alarm a) -> a.matches(packageName);
2451 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2452 Batch b = mAlarmBatches.get(i);
2453 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002454 if (b.size() == 0) {
2455 mAlarmBatches.remove(i);
2456 }
2457 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002458 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002459 final Alarm a = mPendingWhileIdleAlarms.get(i);
2460 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002461 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2462 mPendingWhileIdleAlarms.remove(i);
2463 }
2464 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002465 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2466 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2467 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2468 if (alarmsForUid.get(j).matches(packageName)) {
2469 alarmsForUid.remove(j);
2470 }
2471 }
2472 if (alarmsForUid.size() == 0) {
2473 mPendingBackgroundAlarms.removeAt(i);
2474 }
2475 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002476 if (didRemove) {
2477 if (DEBUG_BATCH) {
2478 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2479 }
2480 rebatchAllAlarmsLocked(true);
2481 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002482 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002483 }
2484 }
2485
Christopher Tate1d99c392017-12-07 16:54:04 -08002486 void removeForStoppedLocked(final int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002487 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002488 final Predicate<Alarm> whichAlarms = (Alarm a) -> {
2489 try {
2490 if (a.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
2491 uid, a.packageName)) {
2492 return true;
2493 }
2494 } catch (RemoteException e) { /* fall through */}
2495 return false;
2496 };
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002497 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2498 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002499 didRemove |= b.remove(whichAlarms);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002500 if (b.size() == 0) {
2501 mAlarmBatches.remove(i);
2502 }
2503 }
2504 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2505 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002506 if (a.uid == uid) {
2507 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2508 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002509 }
2510 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002511 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2512 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2513 mPendingBackgroundAlarms.removeAt(i);
2514 }
2515 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002516 if (didRemove) {
2517 if (DEBUG_BATCH) {
2518 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2519 }
2520 rebatchAllAlarmsLocked(true);
2521 rescheduleKernelAlarmsLocked();
2522 updateNextAlarmClockLocked();
2523 }
2524 }
2525
Adam Lesinski182f73f2013-12-05 16:48:06 -08002526 void removeUserLocked(int userHandle) {
2527 boolean didRemove = false;
Christopher Tate1d99c392017-12-07 16:54:04 -08002528 final Predicate<Alarm> whichAlarms =
2529 (Alarm a) -> UserHandle.getUserId(a.creatorUid) == userHandle;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002530 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2531 Batch b = mAlarmBatches.get(i);
Christopher Tate1d99c392017-12-07 16:54:04 -08002532 didRemove |= b.remove(whichAlarms);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002533 if (b.size() == 0) {
2534 mAlarmBatches.remove(i);
2535 }
2536 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002537 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002538 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002539 == userHandle) {
2540 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2541 mPendingWhileIdleAlarms.remove(i);
2542 }
2543 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002544 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2545 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2546 mPendingBackgroundAlarms.removeAt(i);
2547 }
2548 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002549 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2550 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2551 mLastAllowWhileIdleDispatch.removeAt(i);
2552 }
2553 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002554
2555 if (didRemove) {
2556 if (DEBUG_BATCH) {
2557 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2558 }
2559 rebatchAllAlarmsLocked(true);
2560 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002561 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002562 }
2563 }
2564
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002565 void interactiveStateChangedLocked(boolean interactive) {
2566 if (mInteractive != interactive) {
2567 mInteractive = interactive;
2568 final long nowELAPSED = SystemClock.elapsedRealtime();
2569 if (interactive) {
2570 if (mPendingNonWakeupAlarms.size() > 0) {
2571 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2572 mTotalDelayTime += thisDelayTime;
2573 if (mMaxDelayTime < thisDelayTime) {
2574 mMaxDelayTime = thisDelayTime;
2575 }
2576 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2577 mPendingNonWakeupAlarms.clear();
2578 }
2579 if (mNonInteractiveStartTime > 0) {
2580 long dur = nowELAPSED - mNonInteractiveStartTime;
2581 if (dur > mNonInteractiveTime) {
2582 mNonInteractiveTime = dur;
2583 }
2584 }
2585 } else {
2586 mNonInteractiveStartTime = nowELAPSED;
2587 }
2588 }
2589 }
2590
Adam Lesinski182f73f2013-12-05 16:48:06 -08002591 boolean lookForPackageLocked(String packageName) {
2592 for (int i = 0; i < mAlarmBatches.size(); i++) {
2593 Batch b = mAlarmBatches.get(i);
2594 if (b.hasPackage(packageName)) {
2595 return true;
2596 }
2597 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002598 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002599 final Alarm a = mPendingWhileIdleAlarms.get(i);
2600 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002601 return true;
2602 }
2603 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002604 return false;
2605 }
2606
2607 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002608 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002609 // The kernel never triggers alarms with negative wakeup times
2610 // so we ensure they are positive.
2611 long alarmSeconds, alarmNanoseconds;
2612 if (when < 0) {
2613 alarmSeconds = 0;
2614 alarmNanoseconds = 0;
2615 } else {
2616 alarmSeconds = when / 1000;
2617 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2618 }
Kweku Adams61e03292017-10-19 14:27:12 -07002619
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002620 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002621 } else {
2622 Message msg = Message.obtain();
2623 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002624
Adam Lesinski182f73f2013-12-05 16:48:06 -08002625 mHandler.removeMessages(ALARM_EVENT);
2626 mHandler.sendMessageAtTime(msg, when);
2627 }
2628 }
2629
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002630 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002631 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002632 for (int i=list.size()-1; i>=0; i--) {
2633 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002634 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2635 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002636 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002637 }
2638 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002639
2640 private static final String labelForType(int type) {
2641 switch (type) {
2642 case RTC: return "RTC";
2643 case RTC_WAKEUP : return "RTC_WAKEUP";
2644 case ELAPSED_REALTIME : return "ELAPSED";
2645 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002646 }
2647 return "--unknown--";
2648 }
2649
2650 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002651 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002652 for (int i=list.size()-1; i>=0; i--) {
2653 Alarm a = list.get(i);
2654 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002655 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2656 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002657 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002658 }
2659 }
2660
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002661 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002662 if (alarm.alarmClock != null) {
2663 // Don't block alarm clocks
2664 return false;
2665 }
2666 if (alarm.operation != null
2667 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2668 // Don't block starting foreground components
2669 return false;
2670 }
2671 final String sourcePackage =
2672 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2673 final int sourceUid = alarm.creatorUid;
Makoto Onuki2206af32017-11-21 16:25:35 -08002674 return mForceAppStandbyTracker.areAlarmsRestricted(sourceUid, sourcePackage);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002675 }
2676
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002677 private native long init();
2678 private native void close(long nativeData);
2679 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2680 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002681 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002682 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002683
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002684 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002685 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002686 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002687 // batches are temporally sorted, so we need only pull from the
2688 // start of the list until we either empty it or hit a batch
2689 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002690 while (mAlarmBatches.size() > 0) {
2691 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002692 if (batch.start > nowELAPSED) {
2693 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002694 break;
2695 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002696
Christopher Tatee0a22b32013-07-11 14:43:13 -07002697 // We will (re)schedule some alarms now; don't let that interfere
2698 // with delivery of this current batch
2699 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002700
Christopher Tatee0a22b32013-07-11 14:43:13 -07002701 final int N = batch.size();
2702 for (int i = 0; i < N; i++) {
2703 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002704
2705 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2706 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2707 // schedule such alarms.
2708 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2709 long minTime = lastTime + mAllowWhileIdleMinTime;
2710 if (nowELAPSED < minTime) {
2711 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2712 // alarm went off for this app. Reschedule the alarm to be in the
2713 // correct time period.
2714 alarm.whenElapsed = minTime;
2715 if (alarm.maxWhenElapsed < minTime) {
2716 alarm.maxWhenElapsed = minTime;
2717 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002718 if (RECORD_DEVICE_IDLE_ALARMS) {
2719 IdleDispatchEntry ent = new IdleDispatchEntry();
2720 ent.uid = alarm.uid;
2721 ent.pkg = alarm.operation.getCreatorPackage();
2722 ent.tag = alarm.operation.getTag("");
2723 ent.op = "RESCHEDULE";
2724 ent.elapsedRealtime = nowELAPSED;
2725 ent.argRealtime = lastTime;
2726 mAllowWhileIdleDispatches.add(ent);
2727 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002728 setImplLocked(alarm, true, false);
2729 continue;
2730 }
2731 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002732 if (isBackgroundRestricted(alarm)) {
2733 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2734 if (DEBUG_BG_LIMIT) {
2735 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2736 }
2737 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2738 if (alarmsForUid == null) {
2739 alarmsForUid = new ArrayList<>();
2740 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2741 }
2742 alarmsForUid.add(alarm);
2743 continue;
2744 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002745
Christopher Tatee0a22b32013-07-11 14:43:13 -07002746 alarm.count = 1;
2747 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002748 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2749 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002750 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002751 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002752 if (mPendingIdleUntil == alarm) {
2753 mPendingIdleUntil = null;
2754 rebatchAllAlarmsLocked(false);
2755 restorePendingWhileIdleAlarmsLocked();
2756 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002757 if (mNextWakeFromIdle == alarm) {
2758 mNextWakeFromIdle = null;
2759 rebatchAllAlarmsLocked(false);
2760 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002761
2762 // Recurring alarms may have passed several alarm intervals while the
2763 // phone was asleep or off, so pass a trigger count when sending them.
2764 if (alarm.repeatInterval > 0) {
2765 // this adjustment will be zero if we're late by
2766 // less than one full repeat interval
2767 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2768
2769 // Also schedule its next recurrence
2770 final long delta = alarm.count * alarm.repeatInterval;
2771 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002772 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002773 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002774 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2775 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002776 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002777
Christopher Tate864d42e2014-12-02 11:48:53 -08002778 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002779 hasWakeup = true;
2780 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002781
2782 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2783 if (alarm.alarmClock != null) {
2784 mNextAlarmClockMayChange = true;
2785 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002786 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002787 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002788
Christopher Tate1590f1e2014-10-02 17:27:57 -07002789 // This is a new alarm delivery set; bump the sequence number to indicate that
2790 // all apps' alarm delivery classes should be recalculated.
2791 mCurrentSeq++;
2792 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002793 Collections.sort(triggerList, mAlarmDispatchComparator);
2794
2795 if (localLOGV) {
2796 for (int i=0; i<triggerList.size(); i++) {
2797 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2798 }
2799 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002800
2801 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002802 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002803
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002804 /**
2805 * This Comparator sorts Alarms into increasing time order.
2806 */
2807 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2808 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002809 long when1 = a1.whenElapsed;
2810 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002811 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002812 return 1;
2813 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002814 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002815 return -1;
2816 }
2817 return 0;
2818 }
2819 }
Kweku Adams61e03292017-10-19 14:27:12 -07002820
Makoto Onuki2206af32017-11-21 16:25:35 -08002821 @VisibleForTesting
2822 static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002823 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002824 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002825 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002826 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002827 public final IAlarmListener listener;
2828 public final String listenerTag;
2829 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002830 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002831 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002832 public final AlarmManager.AlarmClockInfo alarmClock;
2833 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002834 public final int creatorUid;
2835 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002836 public int count;
2837 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002838 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002839 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002840 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002841 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002842 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002843
Christopher Tate3e04b472013-10-21 17:51:31 -07002844 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002845 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2846 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2847 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002848 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002849 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002850 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2851 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002852 when = _when;
2853 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002854 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002855 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002856 repeatInterval = _interval;
2857 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002858 listener = _rec;
2859 listenerTag = _listenerTag;
2860 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002861 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002862 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002863 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002864 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002865 packageName = _pkgName;
2866
2867 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002868 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002869
Christopher Tate14a7bb02015-10-01 10:24:31 -07002870 public static String makeTag(PendingIntent pi, String tag, int type) {
2871 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2872 ? "*walarm*:" : "*alarm*:";
2873 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2874 }
2875
2876 public WakeupEvent makeWakeupEvent(long nowRTC) {
2877 return new WakeupEvent(nowRTC, creatorUid,
2878 (operation != null)
2879 ? operation.getIntent().getAction()
2880 : ("<listener>:" + listenerTag));
2881 }
2882
2883 // Returns true if either matches
2884 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2885 return (operation != null)
2886 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002887 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002888 }
2889
2890 public boolean matches(String packageName) {
2891 return (operation != null)
2892 ? packageName.equals(operation.getTargetPackage())
2893 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002894 }
2895
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002896 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002897 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002898 StringBuilder sb = new StringBuilder(128);
2899 sb.append("Alarm{");
2900 sb.append(Integer.toHexString(System.identityHashCode(this)));
2901 sb.append(" type ");
2902 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002903 sb.append(" when ");
2904 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002905 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002906 if (operation != null) {
2907 sb.append(operation.getTargetPackage());
2908 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002909 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002910 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002911 sb.append('}');
2912 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002913 }
2914
Kweku Adams61e03292017-10-19 14:27:12 -07002915 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002916 SimpleDateFormat sdf) {
2917 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002918 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002919 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002920 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2921 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002922 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002923 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002924 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002925 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002926 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002927 }
2928 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002929 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002930 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002931 pw.print(" count="); pw.print(count);
2932 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002933 if (alarmClock != null) {
2934 pw.print(prefix); pw.println("Alarm clock:");
2935 pw.print(prefix); pw.print(" triggerTime=");
2936 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2937 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2938 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002939 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002940 if (listener != null) {
2941 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002943 }
Kweku Adams61e03292017-10-19 14:27:12 -07002944
2945 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
2946 long nowRTC) {
2947 final long token = proto.start(fieldId);
2948
2949 proto.write(AlarmProto.TAG, statsTag);
2950 proto.write(AlarmProto.TYPE, type);
Kweku Adams923ec432017-12-11 18:05:38 -08002951 proto.write(AlarmProto.TIME_UNTIL_WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
Kweku Adams61e03292017-10-19 14:27:12 -07002952 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
2953 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
2954 proto.write(AlarmProto.COUNT, count);
2955 proto.write(AlarmProto.FLAGS, flags);
2956 if (alarmClock != null) {
2957 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
2958 }
2959 if (operation != null) {
2960 operation.writeToProto(proto, AlarmProto.OPERATION);
2961 }
2962 if (listener != null) {
2963 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
2964 }
2965
2966 proto.end(token);
2967 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002968 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002969
Christopher Tatee0a22b32013-07-11 14:43:13 -07002970 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
2971 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002972 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
2973 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002974 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07002975 break;
2976 }
2977
Christopher Tatee0a22b32013-07-11 14:43:13 -07002978 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07002979 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
2980 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002981 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07002982 }
Christopher Tate18a75f12013-07-01 18:18:59 -07002983 }
2984 }
2985
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002986 long currentNonWakeupFuzzLocked(long nowELAPSED) {
2987 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
2988 if (timeSinceOn < 5*60*1000) {
2989 // If the screen has been off for 5 minutes, only delay by at most two minutes.
2990 return 2*60*1000;
2991 } else if (timeSinceOn < 30*60*1000) {
2992 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
2993 return 15*60*1000;
2994 } else {
2995 // Otherwise, we will delay by at most an hour.
2996 return 60*60*1000;
2997 }
2998 }
2999
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003000 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003001 if (duration < 15*60*1000) {
3002 // If the duration until the time is less than 15 minutes, the maximum fuzz
3003 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003004 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003005 } else if (duration < 90*60*1000) {
3006 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3007 return 15*60*1000;
3008 } else {
3009 // Otherwise, we will fuzz by at most half an hour.
3010 return 30*60*1000;
3011 }
3012 }
3013
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003014 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3015 if (mInteractive) {
3016 return false;
3017 }
3018 if (mLastAlarmDeliveryTime <= 0) {
3019 return false;
3020 }
minho.choo649acab2014-12-12 16:13:55 +09003021 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003022 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3023 // and the next delivery time is in the past, then just deliver them all. This
3024 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3025 return false;
3026 }
3027 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3028 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3029 }
3030
3031 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3032 mLastAlarmDeliveryTime = nowELAPSED;
3033 for (int i=0; i<triggerList.size(); i++) {
3034 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003035 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003036 if (alarm.wakeup) {
3037 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3038 } else {
3039 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3040 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003041 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003042 if (localLOGV) {
3043 Slog.v(TAG, "sending alarm " + alarm);
3044 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003045 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003046 ActivityManager.noteAlarmStart(alarm.operation, alarm.workSource, alarm.uid,
3047 alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003048 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003049 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003050 } catch (RuntimeException e) {
3051 Slog.w(TAG, "Failure sending alarm.", e);
3052 }
Tim Murray175c0f92017-11-28 15:01:04 -08003053 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003054 }
3055 }
3056
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003057 private class AlarmThread extends Thread
3058 {
3059 public AlarmThread()
3060 {
3061 super("AlarmManager");
3062 }
Kweku Adams61e03292017-10-19 14:27:12 -07003063
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003064 public void run()
3065 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003066 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3067
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003068 while (true)
3069 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003070 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003071 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003072
3073 triggerList.clear();
3074
Dianne Hackbornc3527222015-05-13 14:03:20 -07003075 final long nowRTC = System.currentTimeMillis();
3076 final long nowELAPSED = SystemClock.elapsedRealtime();
3077
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003078 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003079 // The kernel can give us spurious time change notifications due to
3080 // small adjustments it makes internally; we want to filter those out.
3081 final long lastTimeChangeClockTime;
3082 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003083 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003084 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3085 expectedClockTime = lastTimeChangeClockTime
3086 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003087 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003088 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3089 || nowRTC > (expectedClockTime+1000)) {
3090 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003091 // let's do it!
3092 if (DEBUG_BATCH) {
3093 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3094 }
3095 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003096 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003097 rebatchAllAlarms();
3098 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003099 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003100 synchronized (mLock) {
3101 mNumTimeChanged++;
3102 mLastTimeChangeClockTime = nowRTC;
3103 mLastTimeChangeRealtime = nowELAPSED;
3104 }
3105 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3106 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003107 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003108 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3109 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003110 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3111
3112 // The world has changed on us, so we need to re-evaluate alarms
3113 // regardless of whether the kernel has told us one went off.
3114 result |= IS_WAKEUP_MASK;
3115 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003117
Dianne Hackbornc3527222015-05-13 14:03:20 -07003118 if (result != TIME_CHANGED_MASK) {
3119 // If this was anything besides just a time change, then figure what if
3120 // anything to do about alarms.
3121 synchronized (mLock) {
3122 if (localLOGV) Slog.v(
3123 TAG, "Checking for alarms... rtc=" + nowRTC
3124 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003125
Dianne Hackbornc3527222015-05-13 14:03:20 -07003126 if (WAKEUP_STATS) {
3127 if ((result & IS_WAKEUP_MASK) != 0) {
3128 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3129 int n = 0;
3130 for (WakeupEvent event : mRecentWakeups) {
3131 if (event.when > newEarliest) break;
3132 n++; // number of now-stale entries at the list head
3133 }
3134 for (int i = 0; i < n; i++) {
3135 mRecentWakeups.remove();
3136 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003137
Dianne Hackbornc3527222015-05-13 14:03:20 -07003138 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003139 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003140 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003141
3142 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3143 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3144 // if there are no wakeup alarms and the screen is off, we can
3145 // delay what we have so far until the future.
3146 if (mPendingNonWakeupAlarms.size() == 0) {
3147 mStartCurrentDelayTime = nowELAPSED;
3148 mNextNonWakeupDeliveryTime = nowELAPSED
3149 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3150 }
3151 mPendingNonWakeupAlarms.addAll(triggerList);
3152 mNumDelayedAlarms += triggerList.size();
3153 rescheduleKernelAlarmsLocked();
3154 updateNextAlarmClockLocked();
3155 } else {
3156 // now deliver the alarm intents; if there are pending non-wakeup
3157 // alarms, we need to merge them in to the list. note we don't
3158 // just deliver them first because we generally want non-wakeup
3159 // alarms delivered after wakeup alarms.
3160 rescheduleKernelAlarmsLocked();
3161 updateNextAlarmClockLocked();
3162 if (mPendingNonWakeupAlarms.size() > 0) {
3163 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3164 triggerList.addAll(mPendingNonWakeupAlarms);
3165 Collections.sort(triggerList, mAlarmDispatchComparator);
3166 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3167 mTotalDelayTime += thisDelayTime;
3168 if (mMaxDelayTime < thisDelayTime) {
3169 mMaxDelayTime = thisDelayTime;
3170 }
3171 mPendingNonWakeupAlarms.clear();
3172 }
3173 deliverAlarmsLocked(triggerList, nowELAPSED);
3174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003175 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003176
3177 } else {
3178 // Just in case -- even though no wakeup flag was set, make sure
3179 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003180 synchronized (mLock) {
3181 rescheduleKernelAlarmsLocked();
3182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003183 }
3184 }
3185 }
3186 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003187
David Christieebe51fc2013-07-26 13:23:29 -07003188 /**
3189 * Attribute blame for a WakeLock.
3190 * @param pi PendingIntent to attribute blame to if ws is null.
3191 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003192 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003193 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003194 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003195 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003196 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003197 final boolean unimportant = pi == mTimeTickSender;
3198 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003199 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003200 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003201 } else {
3202 mWakeLock.setHistoryTag(null);
3203 }
3204 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003205 if (ws != null) {
3206 mWakeLock.setWorkSource(ws);
3207 return;
3208 }
3209
Christopher Tate14a7bb02015-10-01 10:24:31 -07003210 final int uid = (knownUid >= 0)
3211 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003212 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003213 if (uid >= 0) {
3214 mWakeLock.setWorkSource(new WorkSource(uid));
3215 return;
3216 }
3217 } catch (Exception e) {
3218 }
3219
3220 // Something went wrong; fall back to attributing the lock to the OS
3221 mWakeLock.setWorkSource(null);
3222 }
3223
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 private class AlarmHandler extends Handler {
3225 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003226 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3227 public static final int LISTENER_TIMEOUT = 3;
3228 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003229
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003230 public AlarmHandler() {
3231 }
Kweku Adams61e03292017-10-19 14:27:12 -07003232
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003233 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003234 switch (msg.what) {
3235 case ALARM_EVENT: {
3236 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3237 synchronized (mLock) {
3238 final long nowRTC = System.currentTimeMillis();
3239 final long nowELAPSED = SystemClock.elapsedRealtime();
3240 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3241 updateNextAlarmClockLocked();
3242 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003243
Christopher Tate14a7bb02015-10-01 10:24:31 -07003244 // now trigger the alarms without the lock held
3245 for (int i=0; i<triggerList.size(); i++) {
3246 Alarm alarm = triggerList.get(i);
3247 try {
3248 alarm.operation.send();
3249 } catch (PendingIntent.CanceledException e) {
3250 if (alarm.repeatInterval > 0) {
3251 // This IntentSender is no longer valid, but this
3252 // is a repeating alarm, so toss the hoser.
3253 removeImpl(alarm.operation);
3254 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003255 }
3256 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003257 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003258 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003259
3260 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3261 sendNextAlarmClockChanged();
3262 break;
3263
3264 case LISTENER_TIMEOUT:
3265 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3266 break;
3267
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003268 case REPORT_ALARMS_ACTIVE:
3269 if (mLocalDeviceIdleController != null) {
3270 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3271 }
3272 break;
3273
Christopher Tate14a7bb02015-10-01 10:24:31 -07003274 default:
3275 // nope, just ignore it
3276 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003277 }
3278 }
3279 }
Kweku Adams61e03292017-10-19 14:27:12 -07003280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 class ClockReceiver extends BroadcastReceiver {
3282 public ClockReceiver() {
3283 IntentFilter filter = new IntentFilter();
3284 filter.addAction(Intent.ACTION_TIME_TICK);
3285 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003286 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003287 }
Kweku Adams61e03292017-10-19 14:27:12 -07003288
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003289 @Override
3290 public void onReceive(Context context, Intent intent) {
3291 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003292 if (DEBUG_BATCH) {
3293 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3294 }
Christopher Tate12cf0b62018-01-05 18:40:14 -08003295 synchronized (mLock) {
3296 mLastTickReceived = System.currentTimeMillis();
3297 }
Christopher Tate385e4982013-07-23 18:22:29 -07003298 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3300 // Since the kernel does not keep track of DST, we need to
3301 // reset the TZ information at the beginning of each day
3302 // based off of the current Zone gmt offset + userspace tracked
3303 // daylight savings information.
3304 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003305 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003306 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003307 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003308 }
3309 }
Kweku Adams61e03292017-10-19 14:27:12 -07003310
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003311 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003312 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003313 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003314
3315 // Schedule this event for the amount of time that it would take to get to
3316 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003317 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003318
David Christieebe51fc2013-07-26 13:23:29 -07003319 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003320 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003321 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3322 null, Process.myUid(), "android");
Christopher Tate12cf0b62018-01-05 18:40:14 -08003323
3324 // Finally, remember when we set the tick alarm
3325 synchronized (mLock) {
3326 mLastTickSet = currentTime;
3327 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 }
Christopher Tate385e4982013-07-23 18:22:29 -07003329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 public void scheduleDateChangedEvent() {
3331 Calendar calendar = Calendar.getInstance();
3332 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003333 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003334 calendar.set(Calendar.MINUTE, 0);
3335 calendar.set(Calendar.SECOND, 0);
3336 calendar.set(Calendar.MILLISECOND, 0);
3337 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003338
3339 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003340 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3341 AlarmManager.FLAG_STANDALONE, workSource, null,
3342 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003343 }
3344 }
Kweku Adams61e03292017-10-19 14:27:12 -07003345
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003346 class InteractiveStateReceiver extends BroadcastReceiver {
3347 public InteractiveStateReceiver() {
3348 IntentFilter filter = new IntentFilter();
3349 filter.addAction(Intent.ACTION_SCREEN_OFF);
3350 filter.addAction(Intent.ACTION_SCREEN_ON);
3351 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3352 getContext().registerReceiver(this, filter);
3353 }
3354
3355 @Override
3356 public void onReceive(Context context, Intent intent) {
3357 synchronized (mLock) {
3358 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3359 }
3360 }
3361 }
3362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 class UninstallReceiver extends BroadcastReceiver {
3364 public UninstallReceiver() {
3365 IntentFilter filter = new IntentFilter();
3366 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3367 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003368 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003369 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003370 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003371 // Register for events related to sdcard installation.
3372 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003373 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003374 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003375 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003376 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003377 }
Kweku Adams61e03292017-10-19 14:27:12 -07003378
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003379 @Override
3380 public void onReceive(Context context, Intent intent) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003381 final int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003382 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003383 String action = intent.getAction();
3384 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003385 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3386 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3387 for (String packageName : pkgList) {
3388 if (lookForPackageLocked(packageName)) {
3389 setResultCode(Activity.RESULT_OK);
3390 return;
3391 }
3392 }
3393 return;
3394 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003395 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003396 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3397 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3398 if (userHandle >= 0) {
3399 removeUserLocked(userHandle);
3400 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003401 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003402 if (uid >= 0) {
3403 mLastAllowWhileIdleDispatch.delete(uid);
3404 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003405 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003406 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3407 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3408 // This package is being updated; don't kill its alarms.
3409 return;
3410 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003411 Uri data = intent.getData();
3412 if (data != null) {
3413 String pkg = data.getSchemeSpecificPart();
3414 if (pkg != null) {
3415 pkgList = new String[]{pkg};
3416 }
3417 }
3418 }
3419 if (pkgList != null && (pkgList.length > 0)) {
3420 for (String pkg : pkgList) {
Christopher Tate1d99c392017-12-07 16:54:04 -08003421 if (uid >= 0) {
3422 // package-removed case
3423 removeLocked(uid);
3424 } else {
3425 // external-applications-unavailable etc case
3426 removeLocked(pkg);
3427 }
Christopher Tate1590f1e2014-10-02 17:27:57 -07003428 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003429 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3430 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3431 if (uidStats.remove(pkg) != null) {
3432 if (uidStats.size() <= 0) {
3433 mBroadcastStats.removeAt(i);
3434 }
3435 }
3436 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003437 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003438 }
3439 }
3440 }
3441 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003442
3443 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003444 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003445 }
3446
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003447 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003448 synchronized (mLock) {
3449 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003450 removeForStoppedLocked(uid);
3451 }
3452 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003453 }
3454
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003455 @Override public void onUidActive(int uid) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003456 }
3457
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003458 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003459 synchronized (mLock) {
3460 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003461 removeForStoppedLocked(uid);
3462 }
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003463 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003464 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003465
3466 @Override public void onUidCachedChanged(int uid, boolean cached) {
3467 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003468 };
3469
Makoto Onuki2206af32017-11-21 16:25:35 -08003470
3471 private final Listener mForceAppStandbyListener = new Listener() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003472 @Override
Makoto Onuki2206af32017-11-21 16:25:35 -08003473 public void unblockAllUnrestrictedAlarms() {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003474 synchronized (mLock) {
Makoto Onuki2206af32017-11-21 16:25:35 -08003475 sendAllUnrestrictedPendingBackgroundAlarmsLocked();
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003476 }
3477 }
Makoto Onuki2206af32017-11-21 16:25:35 -08003478
3479 @Override
3480 public void unblockAlarmsForUid(int uid) {
3481 synchronized (mLock) {
3482 sendPendingBackgroundAlarmsLocked(uid, null);
3483 }
3484 }
3485
3486 @Override
3487 public void unblockAlarmsForUidPackage(int uid, String packageName) {
3488 synchronized (mLock) {
3489 sendPendingBackgroundAlarmsLocked(uid, packageName);
3490 }
3491 }
3492 };
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003493
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003494 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003495 String pkg = pi.getCreatorPackage();
3496 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003497 return getStatsLocked(uid, pkg);
3498 }
3499
3500 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003501 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3502 if (uidStats == null) {
3503 uidStats = new ArrayMap<String, BroadcastStats>();
3504 mBroadcastStats.put(uid, uidStats);
3505 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003506 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003507 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003508 bs = new BroadcastStats(uid, pkgName);
3509 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003510 }
3511 return bs;
3512 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003513
Christopher Tate21e9f192017-08-08 13:49:11 -07003514 /**
3515 * Canonical count of (operation.send() - onSendFinished()) and
3516 * listener send/complete/timeout invocations.
3517 * Guarded by the usual lock.
3518 */
3519 @GuardedBy("mLock")
3520 private int mSendCount = 0;
3521 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003522 private int mSendFinishCount = 0;
3523 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003524 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003525 @GuardedBy("mLock")
3526 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003527
Christopher Tate14a7bb02015-10-01 10:24:31 -07003528 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003529
Christopher Tate14a7bb02015-10-01 10:24:31 -07003530 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3531 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003532 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003533 return mInFlight.remove(i);
3534 }
3535 }
3536 mLog.w("No in-flight alarm for " + pi + " " + intent);
3537 return null;
3538 }
3539
3540 private InFlight removeLocked(IBinder listener) {
3541 for (int i = 0; i < mInFlight.size(); i++) {
3542 if (mInFlight.get(i).mListener == listener) {
3543 return mInFlight.remove(i);
3544 }
3545 }
3546 mLog.w("No in-flight alarm for listener " + listener);
3547 return null;
3548 }
3549
3550 private void updateStatsLocked(InFlight inflight) {
3551 final long nowELAPSED = SystemClock.elapsedRealtime();
3552 BroadcastStats bs = inflight.mBroadcastStats;
3553 bs.nesting--;
3554 if (bs.nesting <= 0) {
3555 bs.nesting = 0;
3556 bs.aggregateTime += nowELAPSED - bs.startTime;
3557 }
3558 FilterStats fs = inflight.mFilterStats;
3559 fs.nesting--;
3560 if (fs.nesting <= 0) {
3561 fs.nesting = 0;
3562 fs.aggregateTime += nowELAPSED - fs.startTime;
3563 }
3564 if (RECORD_ALARMS_IN_HISTORY) {
Narayan Kamath695cf722017-12-21 18:32:47 +00003565 ActivityManager.noteAlarmFinish(inflight.mPendingIntent, inflight.mWorkSource,
3566 inflight.mUid, inflight.mTag);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003567 }
3568 }
3569
3570 private void updateTrackingLocked(InFlight inflight) {
3571 if (inflight != null) {
3572 updateStatsLocked(inflight);
3573 }
3574 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003575 if (DEBUG_WAKELOCK) {
3576 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3577 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003578 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003579 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003580 mWakeLock.release();
3581 if (mInFlight.size() > 0) {
3582 mLog.w("Finished all dispatches with " + mInFlight.size()
3583 + " remaining inflights");
3584 for (int i=0; i<mInFlight.size(); i++) {
3585 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3586 }
3587 mInFlight.clear();
3588 }
3589 } else {
3590 // the next of our alarms is now in flight. reattribute the wakelock.
3591 if (mInFlight.size() > 0) {
3592 InFlight inFlight = mInFlight.get(0);
3593 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3594 inFlight.mAlarmType, inFlight.mTag, -1, false);
3595 } else {
3596 // should never happen
3597 mLog.w("Alarm wakelock still held but sent queue empty");
3598 mWakeLock.setWorkSource(null);
3599 }
3600 }
3601 }
3602
3603 /**
3604 * Callback that arrives when a direct-call alarm reports that delivery has finished
3605 */
3606 @Override
3607 public void alarmComplete(IBinder who) {
3608 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003609 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003610 + " pid=" + Binder.getCallingPid());
3611 return;
3612 }
3613
3614 final long ident = Binder.clearCallingIdentity();
3615 try {
3616 synchronized (mLock) {
3617 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3618 InFlight inflight = removeLocked(who);
3619 if (inflight != null) {
3620 if (DEBUG_LISTENER_CALLBACK) {
3621 Slog.i(TAG, "alarmComplete() from " + who);
3622 }
3623 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003624 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003625 } else {
3626 // Delivery timed out, and the timeout handling already took care of
3627 // updating our tracking here, so we needn't do anything further.
3628 if (DEBUG_LISTENER_CALLBACK) {
3629 Slog.i(TAG, "Late alarmComplete() from " + who);
3630 }
3631 }
3632 }
3633 } finally {
3634 Binder.restoreCallingIdentity(ident);
3635 }
3636 }
3637
3638 /**
3639 * Callback that arrives when a PendingIntent alarm has finished delivery
3640 */
3641 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003642 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3643 String resultData, Bundle resultExtras) {
3644 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003645 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003646 updateTrackingLocked(removeLocked(pi, intent));
3647 }
3648 }
3649
3650 /**
3651 * Timeout of a direct-call alarm delivery
3652 */
3653 public void alarmTimedOut(IBinder who) {
3654 synchronized (mLock) {
3655 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003656 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003657 // TODO: implement ANR policy for the target
3658 if (DEBUG_LISTENER_CALLBACK) {
3659 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003660 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003661 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003662 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003663 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003664 if (DEBUG_LISTENER_CALLBACK) {
3665 Slog.i(TAG, "Spurious timeout of listener " + who);
3666 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003667 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003668 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003669 }
3670 }
3671
3672 /**
3673 * Deliver an alarm and set up the post-delivery handling appropriately
3674 */
3675 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3676 if (alarm.operation != null) {
3677 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003678 mSendCount++;
Christopher Tate12cf0b62018-01-05 18:40:14 -08003679
3680 if (alarm.priorityClass.priority == PRIO_TICK) {
3681 mLastTickIssued = nowELAPSED;
3682 }
3683
Christopher Tate14a7bb02015-10-01 10:24:31 -07003684 try {
3685 alarm.operation.send(getContext(), 0,
3686 mBackgroundIntent.putExtra(
3687 Intent.EXTRA_ALARM_COUNT, alarm.count),
3688 mDeliveryTracker, mHandler, null,
3689 allowWhileIdle ? mIdleOptions : null);
3690 } catch (PendingIntent.CanceledException e) {
3691 if (alarm.repeatInterval > 0) {
3692 // This IntentSender is no longer valid, but this
3693 // is a repeating alarm, so toss it
3694 removeImpl(alarm.operation);
3695 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003696 // No actual delivery was possible, so the delivery tracker's
3697 // 'finished' callback won't be invoked. We also don't need
3698 // to do any wakelock or stats tracking, so we have nothing
3699 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003700 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003701 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003702 }
3703 } else {
3704 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003705 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003706 try {
3707 if (DEBUG_LISTENER_CALLBACK) {
3708 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3709 + " listener=" + alarm.listener.asBinder());
3710 }
3711 alarm.listener.doAlarm(this);
3712 mHandler.sendMessageDelayed(
3713 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3714 alarm.listener.asBinder()),
3715 mConstants.LISTENER_TIMEOUT);
3716 } catch (Exception e) {
3717 if (DEBUG_LISTENER_CALLBACK) {
3718 Slog.i(TAG, "Alarm undeliverable to listener "
3719 + alarm.listener.asBinder(), e);
3720 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003721 // As in the PendingIntent.CanceledException case, delivery of the
3722 // alarm was not possible, so we have no wakelock or timeout or
3723 // stats management to do. It threw before we posted the delayed
3724 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003725 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003726 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003727 }
3728 }
3729
3730 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003731 if (DEBUG_WAKELOCK) {
3732 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3733 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003734 if (mBroadcastRefCount == 0) {
3735 setWakelockWorkSource(alarm.operation, alarm.workSource,
3736 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3737 true);
3738 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003739 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003740 }
3741 final InFlight inflight = new InFlight(AlarmManagerService.this,
3742 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3743 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3744 mInFlight.add(inflight);
3745 mBroadcastRefCount++;
3746
3747 if (allowWhileIdle) {
3748 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3749 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3750 if (RECORD_DEVICE_IDLE_ALARMS) {
3751 IdleDispatchEntry ent = new IdleDispatchEntry();
3752 ent.uid = alarm.uid;
3753 ent.pkg = alarm.packageName;
3754 ent.tag = alarm.statsTag;
3755 ent.op = "DELIVER";
3756 ent.elapsedRealtime = nowELAPSED;
3757 mAllowWhileIdleDispatches.add(ent);
3758 }
3759 }
3760
3761 final BroadcastStats bs = inflight.mBroadcastStats;
3762 bs.count++;
3763 if (bs.nesting == 0) {
3764 bs.nesting = 1;
3765 bs.startTime = nowELAPSED;
3766 } else {
3767 bs.nesting++;
3768 }
3769 final FilterStats fs = inflight.mFilterStats;
3770 fs.count++;
3771 if (fs.nesting == 0) {
3772 fs.nesting = 1;
3773 fs.startTime = nowELAPSED;
3774 } else {
3775 fs.nesting++;
3776 }
3777 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3778 || alarm.type == RTC_WAKEUP) {
3779 bs.numWakeup++;
3780 fs.numWakeup++;
Narayan Kamath695cf722017-12-21 18:32:47 +00003781 ActivityManager.noteWakeupAlarm(
3782 alarm.operation, alarm.workSource, alarm.uid, alarm.packageName,
3783 alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003784 }
3785 }
3786 }
3787}