blob: 3904fc96cacafdb8308d24471cd4f9fbc430329a [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;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070049import android.os.ServiceManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.os.SystemClock;
51import android.os.SystemProperties;
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;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070058import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070059import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020060import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080061import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080062import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020063import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070064import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070065import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070066import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067
Christopher Tate4cb338d2013-07-26 13:11:31 -070068import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080069import java.io.FileDescriptor;
70import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070071import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080073import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import java.util.Calendar;
75import java.util.Collections;
76import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050077import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070078import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070079import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020080import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070081import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040083import java.util.TreeSet;
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;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070091import com.android.internal.app.IAppOpsCallback;
92import com.android.internal.app.IAppOpsService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060093import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080094import com.android.internal.util.LocalLog;
95
Adam Lesinski182f73f2013-12-05 16:48:06 -080096class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070097 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
98 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -080099 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700100 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800101 static final int TIME_CHANGED_MASK = 1 << 16;
102 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800103
Christopher Tatee0a22b32013-07-11 14:43:13 -0700104 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800105 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800106
Adam Lesinski182f73f2013-12-05 16:48:06 -0800107 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final boolean localLOGV = false;
109 static final boolean DEBUG_BATCH = localLOGV || false;
110 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200111 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700112 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800113 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700114 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700115 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700116 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800117 static final int ALARM_EVENT = 1;
118 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200119
Christopher Tate14a7bb02015-10-01 10:24:31 -0700120 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800121 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800122 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700123
Adam Lesinski182f73f2013-12-05 16:48:06 -0800124 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700125
Christopher Tate24cd46f2016-02-02 14:28:01 -0800126 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
127 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700128 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
129 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200130
Adam Lesinski182f73f2013-12-05 16:48:06 -0800131 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800132
Christopher Tate14a7bb02015-10-01 10:24:31 -0700133 AppOpsManager mAppOps;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700134 IAppOpsService mAppOpsService;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800135 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700136
Adam Lesinski182f73f2013-12-05 16:48:06 -0800137 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800138
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700139 ArraySet<String> mForcedAppStandbyPackages = new ArraySet<>();
140 SparseBooleanArray mForegroundUids = new SparseBooleanArray();
141 // List of alarms per uid deferred due to user applied background restrictions on the source app
142 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800143 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800144 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700145 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700146 private long mLastWakeupSet;
147 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800148 int mBroadcastRefCount = 0;
149 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700150 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700151 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
152 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800153 final AlarmHandler mHandler = new AlarmHandler();
154 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700155 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700157 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800158 PendingIntent mTimeTickSender;
159 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700160 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700161 boolean mInteractive = true;
162 long mNonInteractiveStartTime;
163 long mNonInteractiveTime;
164 long mLastAlarmDeliveryTime;
165 long mStartCurrentDelayTime;
166 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700167 long mLastTimeChangeClockTime;
168 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700169 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700170 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800171
Christopher Tatebb9cce52017-04-18 14:19:43 -0700172 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
173
174 /**
175 * This permission must be defined by the canonical System UI package,
176 * with protection level "signature".
177 */
178 private static final String SYSTEM_UI_SELF_PERMISSION =
179 "android.permission.systemui.IDENTITY";
180
181 /**
182 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
183 */
184 int mSystemUiUid;
185
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700186 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800187 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
188 * to freely schedule alarms.
189 */
190 int[] mDeviceIdleUserWhitelist = new int[0];
191
192 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700193 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700194 * used to determine the earliest we can dispatch the next such alarm. Times are in the
195 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700196 */
197 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
198
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700199 final static class IdleDispatchEntry {
200 int uid;
201 String pkg;
202 String tag;
203 String op;
204 long elapsedRealtime;
205 long argRealtime;
206 }
207 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
208
Dianne Hackborna750a632015-06-16 17:18:23 -0700209 /**
210 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
211 */
212 Bundle mIdleOptions;
213
Jose Lima235510e2014-08-13 12:50:01 -0700214 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
215 new SparseArray<>();
216 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
217 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200218 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
219 new SparseBooleanArray();
220 private boolean mNextAlarmClockMayChange;
221
222 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700223 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
224 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200225
Dianne Hackborna750a632015-06-16 17:18:23 -0700226 /**
227 * All times are in milliseconds. These constants are kept synchronized with the system
228 * global Settings. Any access to this class or its fields should be done while
229 * holding the AlarmManagerService.mLock lock.
230 */
231 private final class Constants extends ContentObserver {
232 // Key names stored in the settings value.
233 private static final String KEY_MIN_FUTURITY = "min_futurity";
234 private static final String KEY_MIN_INTERVAL = "min_interval";
235 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
236 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
237 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
238 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700239 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700240 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700241
242 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
243 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700244 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700245 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700246 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
247
Christopher Tate14a7bb02015-10-01 10:24:31 -0700248 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
249
Dianne Hackborna750a632015-06-16 17:18:23 -0700250 // Minimum futurity of a new alarm
251 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
252
253 // Minimum alarm recurrence interval
254 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
255
256 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
257 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
258
259 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
260 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
261
262 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
263 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
264 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
265
Christopher Tate14a7bb02015-10-01 10:24:31 -0700266 // Direct alarm listener callback timeout
267 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
268
Dianne Hackborna750a632015-06-16 17:18:23 -0700269 private ContentResolver mResolver;
270 private final KeyValueListParser mParser = new KeyValueListParser(',');
271 private long mLastAllowWhileIdleWhitelistDuration = -1;
272
273 public Constants(Handler handler) {
274 super(handler);
275 updateAllowWhileIdleMinTimeLocked();
276 updateAllowWhileIdleWhitelistDurationLocked();
277 }
278
279 public void start(ContentResolver resolver) {
280 mResolver = resolver;
281 mResolver.registerContentObserver(Settings.Global.getUriFor(
282 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
283 updateConstants();
284 }
285
286 public void updateAllowWhileIdleMinTimeLocked() {
287 mAllowWhileIdleMinTime = mPendingIdleUntil != null
288 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
289 }
290
291 public void updateAllowWhileIdleWhitelistDurationLocked() {
292 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
293 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
294 BroadcastOptions opts = BroadcastOptions.makeBasic();
295 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
296 mIdleOptions = opts.toBundle();
297 }
298 }
299
300 @Override
301 public void onChange(boolean selfChange, Uri uri) {
302 updateConstants();
303 }
304
305 private void updateConstants() {
306 synchronized (mLock) {
307 try {
308 mParser.setString(Settings.Global.getString(mResolver,
309 Settings.Global.ALARM_MANAGER_CONSTANTS));
310 } catch (IllegalArgumentException e) {
311 // Failed to parse the settings string, log this and move on
312 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800313 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700314 }
315
316 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
317 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
318 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
319 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
320 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
321 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
322 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
323 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
324 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700325 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
326 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700327
328 updateAllowWhileIdleMinTimeLocked();
329 updateAllowWhileIdleWhitelistDurationLocked();
330 }
331 }
332
333 void dump(PrintWriter pw) {
334 pw.println(" Settings:");
335
336 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
337 TimeUtils.formatDuration(MIN_FUTURITY, pw);
338 pw.println();
339
340 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
341 TimeUtils.formatDuration(MIN_INTERVAL, pw);
342 pw.println();
343
Christopher Tate14a7bb02015-10-01 10:24:31 -0700344 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
345 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
346 pw.println();
347
Dianne Hackborna750a632015-06-16 17:18:23 -0700348 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
349 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
350 pw.println();
351
352 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
353 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
354 pw.println();
355
356 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
357 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
358 pw.println();
359 }
Kweku Adams61e03292017-10-19 14:27:12 -0700360
361 void dumpProto(ProtoOutputStream proto, long fieldId) {
362 final long token = proto.start(fieldId);
363
364 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
365 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
366 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
367 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
368 ALLOW_WHILE_IDLE_SHORT_TIME);
369 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
370 ALLOW_WHILE_IDLE_LONG_TIME);
371 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
372 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
373
374 proto.end(token);
375 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700376 }
377
378 final Constants mConstants;
379
Christopher Tate1590f1e2014-10-02 17:27:57 -0700380 // Alarm delivery ordering bookkeeping
381 static final int PRIO_TICK = 0;
382 static final int PRIO_WAKEUP = 1;
383 static final int PRIO_NORMAL = 2;
384
Dianne Hackborna750a632015-06-16 17:18:23 -0700385 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700386 int seq;
387 int priority;
388
389 PriorityClass() {
390 seq = mCurrentSeq - 1;
391 priority = PRIO_NORMAL;
392 }
393 }
394
Dianne Hackborna750a632015-06-16 17:18:23 -0700395 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700396 int mCurrentSeq = 0;
397
Dianne Hackborna750a632015-06-16 17:18:23 -0700398 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700399 public long when;
400 public int uid;
401 public String action;
402
403 public WakeupEvent(long theTime, int theUid, String theAction) {
404 when = theTime;
405 uid = theUid;
406 action = theAction;
407 }
408 }
409
Adam Lesinski182f73f2013-12-05 16:48:06 -0800410 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
411 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700412
Adrian Roosc42a1e12014-07-07 23:35:53 +0200413 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700414 long start; // These endpoints are always in ELAPSED
415 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700416 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700417
418 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
419
420 Batch() {
421 start = 0;
422 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700423 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700424 }
425
426 Batch(Alarm seed) {
427 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700428 end = seed.maxWhenElapsed;
429 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700430 alarms.add(seed);
431 }
432
433 int size() {
434 return alarms.size();
435 }
436
437 Alarm get(int index) {
438 return alarms.get(index);
439 }
440
441 boolean canHold(long whenElapsed, long maxWhen) {
442 return (end >= whenElapsed) && (start <= maxWhen);
443 }
444
445 boolean add(Alarm alarm) {
446 boolean newStart = false;
447 // narrows the batch if necessary; presumes that canHold(alarm) is true
448 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
449 if (index < 0) {
450 index = 0 - index - 1;
451 }
452 alarms.add(index, alarm);
453 if (DEBUG_BATCH) {
454 Slog.v(TAG, "Adding " + alarm + " to " + this);
455 }
456 if (alarm.whenElapsed > start) {
457 start = alarm.whenElapsed;
458 newStart = true;
459 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700460 if (alarm.maxWhenElapsed < end) {
461 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700462 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700463 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700464
465 if (DEBUG_BATCH) {
466 Slog.v(TAG, " => now " + this);
467 }
468 return newStart;
469 }
470
Christopher Tate14a7bb02015-10-01 10:24:31 -0700471 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
472 if (operation == null && listener == null) {
473 if (localLOGV) {
474 Slog.w(TAG, "requested remove() of null operation",
475 new RuntimeException("here"));
476 }
477 return false;
478 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700479 boolean didRemove = false;
480 long newStart = 0; // recalculate endpoints as we go
481 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700482 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700483 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700484 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700485 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700486 alarms.remove(i);
487 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200488 if (alarm.alarmClock != null) {
489 mNextAlarmClockMayChange = true;
490 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700491 } else {
492 if (alarm.whenElapsed > newStart) {
493 newStart = alarm.whenElapsed;
494 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700495 if (alarm.maxWhenElapsed < newEnd) {
496 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700497 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700498 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700499 i++;
500 }
501 }
502 if (didRemove) {
503 // commit the new batch bounds
504 start = newStart;
505 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700506 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700507 }
508 return didRemove;
509 }
510
511 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700512 if (packageName == null) {
513 if (localLOGV) {
514 Slog.w(TAG, "requested remove() of null packageName",
515 new RuntimeException("here"));
516 }
517 return false;
518 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700519 boolean didRemove = false;
520 long newStart = 0; // recalculate endpoints as we go
521 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700522 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700523 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700524 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700525 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700526 alarms.remove(i);
527 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200528 if (alarm.alarmClock != null) {
529 mNextAlarmClockMayChange = true;
530 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700531 } else {
532 if (alarm.whenElapsed > newStart) {
533 newStart = alarm.whenElapsed;
534 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700535 if (alarm.maxWhenElapsed < newEnd) {
536 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700537 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700538 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700539 }
540 }
541 if (didRemove) {
542 // commit the new batch bounds
543 start = newStart;
544 end = newEnd;
545 flags = newFlags;
546 }
547 return didRemove;
548 }
549
550 boolean removeForStopped(final int uid) {
551 boolean didRemove = false;
552 long newStart = 0; // recalculate endpoints as we go
553 long newEnd = Long.MAX_VALUE;
554 int newFlags = 0;
555 for (int i = alarms.size()-1; i >= 0; i--) {
556 Alarm alarm = alarms.get(i);
557 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800558 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
559 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700560 alarms.remove(i);
561 didRemove = true;
562 if (alarm.alarmClock != null) {
563 mNextAlarmClockMayChange = true;
564 }
565 } else {
566 if (alarm.whenElapsed > newStart) {
567 newStart = alarm.whenElapsed;
568 }
569 if (alarm.maxWhenElapsed < newEnd) {
570 newEnd = alarm.maxWhenElapsed;
571 }
572 newFlags |= alarm.flags;
573 }
574 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700575 }
576 }
577 if (didRemove) {
578 // commit the new batch bounds
579 start = newStart;
580 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700581 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700582 }
583 return didRemove;
584 }
585
586 boolean remove(final int userHandle) {
587 boolean didRemove = false;
588 long newStart = 0; // recalculate endpoints as we go
589 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700590 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700591 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700592 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700593 alarms.remove(i);
594 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200595 if (alarm.alarmClock != null) {
596 mNextAlarmClockMayChange = true;
597 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700598 } else {
599 if (alarm.whenElapsed > newStart) {
600 newStart = alarm.whenElapsed;
601 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700602 if (alarm.maxWhenElapsed < newEnd) {
603 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700604 }
605 i++;
606 }
607 }
608 if (didRemove) {
609 // commit the new batch bounds
610 start = newStart;
611 end = newEnd;
612 }
613 return didRemove;
614 }
615
616 boolean hasPackage(final String packageName) {
617 final int N = alarms.size();
618 for (int i = 0; i < N; i++) {
619 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700620 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700621 return true;
622 }
623 }
624 return false;
625 }
626
627 boolean hasWakeups() {
628 final int N = alarms.size();
629 for (int i = 0; i < N; i++) {
630 Alarm a = alarms.get(i);
631 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
632 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
633 return true;
634 }
635 }
636 return false;
637 }
638
639 @Override
640 public String toString() {
641 StringBuilder b = new StringBuilder(40);
642 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
643 b.append(" num="); b.append(size());
644 b.append(" start="); b.append(start);
645 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700646 if (flags != 0) {
647 b.append(" flgs=0x");
648 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700649 }
650 b.append('}');
651 return b.toString();
652 }
Kweku Adams61e03292017-10-19 14:27:12 -0700653
654 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
655 long nowRTC) {
656 final long token = proto.start(fieldId);
657
658 proto.write(BatchProto.START_REALTIME, start);
659 proto.write(BatchProto.END_REALTIME, end);
660 proto.write(BatchProto.FLAGS, flags);
661 for (Alarm a : alarms) {
662 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
663 }
664
665 proto.end(token);
666 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700667 }
668
669 static class BatchTimeOrder implements Comparator<Batch> {
670 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800671 long when1 = b1.start;
672 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800673 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700674 return 1;
675 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800676 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700677 return -1;
678 }
679 return 0;
680 }
681 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800682
683 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
684 @Override
685 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700686 // priority class trumps everything. TICK < WAKEUP < NORMAL
687 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
688 return -1;
689 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
690 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800691 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700692
693 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800694 if (lhs.whenElapsed < rhs.whenElapsed) {
695 return -1;
696 } else if (lhs.whenElapsed > rhs.whenElapsed) {
697 return 1;
698 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700699
700 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800701 return 0;
702 }
703 };
704
Christopher Tate1590f1e2014-10-02 17:27:57 -0700705 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
706 final int N = alarms.size();
707 for (int i = 0; i < N; i++) {
708 Alarm a = alarms.get(i);
709
710 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700711 if (a.operation != null
712 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700713 alarmPrio = PRIO_TICK;
714 } else if (a.wakeup) {
715 alarmPrio = PRIO_WAKEUP;
716 } else {
717 alarmPrio = PRIO_NORMAL;
718 }
719
720 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700721 String alarmPackage = (a.operation != null)
722 ? a.operation.getCreatorPackage()
723 : a.packageName;
724 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700725 if (packagePrio == null) {
726 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700727 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700728 }
729 a.priorityClass = packagePrio;
730
731 if (packagePrio.seq != mCurrentSeq) {
732 // first alarm we've seen in the current delivery generation from this package
733 packagePrio.priority = alarmPrio;
734 packagePrio.seq = mCurrentSeq;
735 } else {
736 // Multiple alarms from this package being delivered in this generation;
737 // bump the package's delivery class if it's warranted.
738 // TICK < WAKEUP < NORMAL
739 if (alarmPrio < packagePrio.priority) {
740 packagePrio.priority = alarmPrio;
741 }
742 }
743 }
744 }
745
Christopher Tatee0a22b32013-07-11 14:43:13 -0700746 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800747 static final long MIN_FUZZABLE_INTERVAL = 10000;
748 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700749 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
750
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700751 // 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 -0700752 // to run during this time are placed in mPendingWhileIdleAlarms
753 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700754 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700755 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700756
Jeff Brownb880d882014-02-10 19:47:07 -0800757 public AlarmManagerService(Context context) {
758 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700759 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800760 }
761
Christopher Tatee0a22b32013-07-11 14:43:13 -0700762 static long convertToElapsed(long when, int type) {
763 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
764 if (isRtc) {
765 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
766 }
767 return when;
768 }
769
770 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
771 // calculate the end of our nominal delivery window for the alarm.
772 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
773 // Current heuristic: batchable window is 75% of either the recurrence interval
774 // [for a periodic alarm] or of the time from now to the desired delivery time,
775 // with a minimum delay/interval of 10 seconds, under which we will simply not
776 // defer the alarm.
777 long futurity = (interval == 0)
778 ? (triggerAtTime - now)
779 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700780 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700781 futurity = 0;
782 }
783 return triggerAtTime + (long)(.75 * futurity);
784 }
785
786 // returns true if the batch was added at the head
787 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
788 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
789 if (index < 0) {
790 index = 0 - index - 1;
791 }
792 list.add(index, newBatch);
793 return (index == 0);
794 }
795
Christopher Tate385e4982013-07-23 18:22:29 -0700796 // Return the index of the matching batch, or -1 if none found.
797 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700798 final int N = mAlarmBatches.size();
799 for (int i = 0; i < N; i++) {
800 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700801 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700802 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700803 }
804 }
Christopher Tate385e4982013-07-23 18:22:29 -0700805 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700806 }
807
808 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
809 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700810 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700811 rebatchAllAlarmsLocked(true);
812 }
813 }
814
815 void rebatchAllAlarmsLocked(boolean doValidate) {
816 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
817 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700818 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700819 final long nowElapsed = SystemClock.elapsedRealtime();
820 final int oldBatches = oldSet.size();
821 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
822 Batch batch = oldSet.get(batchNum);
823 final int N = batch.size();
824 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700825 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700826 }
827 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700828 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
829 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
830 + " to " + mPendingIdleUntil);
831 if (mPendingIdleUntil == null) {
832 // Somehow we lost this... we need to restore all of the pending alarms.
833 restorePendingWhileIdleAlarmsLocked();
834 }
835 }
836 rescheduleKernelAlarmsLocked();
837 updateNextAlarmClockLocked();
838 }
839
840 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
841 a.when = a.origWhen;
842 long whenElapsed = convertToElapsed(a.when, a.type);
843 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700844 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700845 // Exact
846 maxElapsed = whenElapsed;
847 } else {
848 // Not exact. Preserve any explicit window, otherwise recalculate
849 // the window based on the alarm's new futurity. Note that this
850 // reflects a policy of preferring timely to deferred delivery.
851 maxElapsed = (a.windowLength > 0)
852 ? (whenElapsed + a.windowLength)
853 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
854 }
855 a.whenElapsed = whenElapsed;
856 a.maxWhenElapsed = maxElapsed;
857 setImplLocked(a, true, doValidate);
858 }
859
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700860 /**
861 * Sends alarms that were blocked due to user applied background restrictions - either because
862 * the user lifted those or the uid came to foreground.
863 *
864 * @param uid uid to filter on
865 * @param packageName package to filter on, or null for all packages in uid
866 */
867 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
868 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
869 if (alarmsForUid == null || alarmsForUid.size() == 0) {
870 return;
871 }
872 final ArrayList<Alarm> alarmsToDeliver;
873 if (packageName != null) {
874 if (DEBUG_BG_LIMIT) {
875 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
876 }
877 alarmsToDeliver = new ArrayList<>();
878 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
879 final Alarm a = alarmsForUid.get(i);
880 if (a.matches(packageName)) {
881 alarmsToDeliver.add(alarmsForUid.remove(i));
882 }
883 }
884 if (alarmsForUid.size() == 0) {
885 mPendingBackgroundAlarms.remove(uid);
886 }
887 } else {
888 if (DEBUG_BG_LIMIT) {
889 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
890 }
891 alarmsToDeliver = alarmsForUid;
892 mPendingBackgroundAlarms.remove(uid);
893 }
894 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
895 }
896
897 void sendPendingBackgroundAlarmsForAppIdLocked(int appId) {
898 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
899 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
900 final int uid = mPendingBackgroundAlarms.keyAt(i);
901 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
902 if (UserHandle.getAppId(uid) == appId) {
903 alarmsToDeliver.addAll(alarmsForUid);
904 mPendingBackgroundAlarms.removeAt(i);
905 }
906 }
907 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
908 }
909
910 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
911 final int N = alarms.size();
912 boolean hasWakeup = false;
913 for (int i = 0; i < N; i++) {
914 final Alarm alarm = alarms.get(i);
915 if (alarm.wakeup) {
916 hasWakeup = true;
917 }
918 alarm.count = 1;
919 // Recurring alarms may have passed several alarm intervals while the
920 // alarm was kept pending. Send the appropriate trigger count.
921 if (alarm.repeatInterval > 0) {
922 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
923 // Also schedule its next recurrence
924 final long delta = alarm.count * alarm.repeatInterval;
925 final long nextElapsed = alarm.whenElapsed + delta;
926 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
927 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
928 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
929 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
930 // Kernel alarms will be rescheduled as needed in setImplLocked
931 }
932 }
933 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
934 // No need to wakeup for non wakeup alarms
935 if (mPendingNonWakeupAlarms.size() == 0) {
936 mStartCurrentDelayTime = nowELAPSED;
937 mNextNonWakeupDeliveryTime = nowELAPSED
938 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
939 }
940 mPendingNonWakeupAlarms.addAll(alarms);
941 mNumDelayedAlarms += alarms.size();
942 } else {
943 if (DEBUG_BG_LIMIT) {
944 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
945 }
946 // Since we are waking up, also deliver any pending non wakeup alarms we have.
947 if (mPendingNonWakeupAlarms.size() > 0) {
948 alarms.addAll(mPendingNonWakeupAlarms);
949 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
950 mTotalDelayTime += thisDelayTime;
951 if (mMaxDelayTime < thisDelayTime) {
952 mMaxDelayTime = thisDelayTime;
953 }
954 mPendingNonWakeupAlarms.clear();
955 }
956 calculateDeliveryPriorities(alarms);
957 Collections.sort(alarms, mAlarmDispatchComparator);
958 deliverAlarmsLocked(alarms, nowELAPSED);
959 }
960 }
961
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700962 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700963 if (RECORD_DEVICE_IDLE_ALARMS) {
964 IdleDispatchEntry ent = new IdleDispatchEntry();
965 ent.uid = 0;
966 ent.pkg = "FINISH IDLE";
967 ent.elapsedRealtime = SystemClock.elapsedRealtime();
968 mAllowWhileIdleDispatches.add(ent);
969 }
970
Dianne Hackborn35d54032015-04-23 10:30:43 -0700971 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700972 if (mPendingWhileIdleAlarms.size() > 0) {
973 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
974 mPendingWhileIdleAlarms = new ArrayList<>();
975 final long nowElapsed = SystemClock.elapsedRealtime();
976 for (int i=alarms.size() - 1; i >= 0; i--) {
977 Alarm a = alarms.get(i);
978 reAddAlarmLocked(a, nowElapsed, false);
979 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700980 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700981
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700982 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700983 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700984
Dianne Hackborn35d54032015-04-23 10:30:43 -0700985 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700986 rescheduleKernelAlarmsLocked();
987 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700988
989 // And send a TIME_TICK right now, since it is important to get the UI updated.
990 try {
991 mTimeTickSender.send();
992 } catch (PendingIntent.CanceledException e) {
993 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700994 }
995
Christopher Tate14a7bb02015-10-01 10:24:31 -0700996 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800997 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700998 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700999 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001000 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001001 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001002 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001003 final BroadcastStats mBroadcastStats;
1004 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001005 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001006
Christopher Tate14a7bb02015-10-01 10:24:31 -07001007 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1008 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1009 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001010 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001011 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001012 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001013 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001014 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001015 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001016 mBroadcastStats = (pendingIntent != null)
1017 ? service.getStatsLocked(pendingIntent)
1018 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001019 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001020 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001021 fs = new FilterStats(mBroadcastStats, mTag);
1022 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001023 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001024 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001025 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001026 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001027 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001028
1029 @Override
1030 public String toString() {
1031 return "InFlight{"
1032 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001033 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001034 + ", workSource=" + mWorkSource
1035 + ", uid=" + mUid
1036 + ", tag=" + mTag
1037 + ", broadcastStats=" + mBroadcastStats
1038 + ", filterStats=" + mFilterStats
1039 + ", alarmType=" + mAlarmType
1040 + "}";
1041 }
Kweku Adams61e03292017-10-19 14:27:12 -07001042
1043 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1044 final long token = proto.start(fieldId);
1045
1046 proto.write(InFlightProto.UID, mUid);
1047 proto.write(InFlightProto.TAG, mTag);
1048 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1049 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1050 if (mPendingIntent != null) {
1051 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1052 }
1053 if (mBroadcastStats != null) {
1054 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1055 }
1056 if (mFilterStats != null) {
1057 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1058 }
1059 if (mWorkSource != null) {
1060 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1061 }
1062
1063 proto.end(token);
1064 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001065 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001066
Adam Lesinski182f73f2013-12-05 16:48:06 -08001067 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001068 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001069 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001070
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001071 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001073 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 int numWakeup;
1075 long startTime;
1076 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001077
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001078 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001079 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001080 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001081 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001082
1083 @Override
1084 public String toString() {
1085 return "FilterStats{"
1086 + "tag=" + mTag
1087 + ", lastTime=" + lastTime
1088 + ", aggregateTime=" + aggregateTime
1089 + ", count=" + count
1090 + ", numWakeup=" + numWakeup
1091 + ", startTime=" + startTime
1092 + ", nesting=" + nesting
1093 + "}";
1094 }
Kweku Adams61e03292017-10-19 14:27:12 -07001095
1096 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1097 final long token = proto.start(fieldId);
1098
1099 proto.write(FilterStatsProto.TAG, mTag);
1100 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1101 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1102 proto.write(FilterStatsProto.COUNT, count);
1103 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1104 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1105 proto.write(FilterStatsProto.NESTING, nesting);
1106
1107 proto.end(token);
1108 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001109 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001110
Adam Lesinski182f73f2013-12-05 16:48:06 -08001111 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001112 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001113 final String mPackageName;
1114
1115 long aggregateTime;
1116 int count;
1117 int numWakeup;
1118 long startTime;
1119 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001120 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001121
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001122 BroadcastStats(int uid, String packageName) {
1123 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001124 mPackageName = packageName;
1125 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001126
1127 @Override
1128 public String toString() {
1129 return "BroadcastStats{"
1130 + "uid=" + mUid
1131 + ", packageName=" + mPackageName
1132 + ", aggregateTime=" + aggregateTime
1133 + ", count=" + count
1134 + ", numWakeup=" + numWakeup
1135 + ", startTime=" + startTime
1136 + ", nesting=" + nesting
1137 + "}";
1138 }
Kweku Adams61e03292017-10-19 14:27:12 -07001139
1140 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1141 final long token = proto.start(fieldId);
1142
1143 proto.write(BroadcastStatsProto.UID, mUid);
1144 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1145 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1146 proto.write(BroadcastStatsProto.COUNT, count);
1147 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1148 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1149 proto.write(BroadcastStatsProto.NESTING, nesting);
1150
1151 proto.end(token);
1152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001154
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001155 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1156 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001157
1158 int mNumDelayedAlarms = 0;
1159 long mTotalDelayTime = 0;
1160 long mMaxDelayTime = 0;
1161
Adam Lesinski182f73f2013-12-05 16:48:06 -08001162 @Override
1163 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001164 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001165 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001166
1167 // We have to set current TimeZone info to kernel
1168 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001169 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001170
Christopher Tate247571462017-04-10 11:45:05 -07001171 // Also sure that we're booting with a halfway sensible current time
1172 if (mNativeData != 0) {
1173 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1174 if (System.currentTimeMillis() < systemBuildTime) {
1175 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1176 + ", advancing to build time " + systemBuildTime);
1177 setKernelTime(mNativeData, systemBuildTime);
1178 }
1179 }
1180
Christopher Tatebb9cce52017-04-18 14:19:43 -07001181 // Determine SysUI's uid
1182 final PackageManager packMan = getContext().getPackageManager();
1183 try {
1184 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1185 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1186 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1187 mSystemUiUid = sysUi.uid;
1188 } else {
1189 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1190 + " defined by non-privileged app " + sysUi.packageName
1191 + " - ignoring");
1192 }
1193 } catch (NameNotFoundException e) {
1194 }
1195
1196 if (mSystemUiUid <= 0) {
1197 Slog.wtf(TAG, "SysUI package not found!");
1198 }
1199
Adam Lesinski182f73f2013-12-05 16:48:06 -08001200 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001201 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001202
Adam Lesinski182f73f2013-12-05 16:48:06 -08001203 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001205 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001206 | Intent.FLAG_RECEIVER_FOREGROUND
1207 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001208 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001209 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001210 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1211 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001212 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001213 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001214
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001215 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001216 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001217 mClockReceiver.scheduleTimeTickEvent();
1218 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001219 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001221
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001222 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001223 AlarmThread waitThread = new AlarmThread();
1224 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001226 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001228
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001229 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001230 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001231 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1232 | ActivityManager.UID_OBSERVER_ACTIVE,
1233 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001234 } catch (RemoteException e) {
1235 // ignored; both services live in system_server
1236 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001237 mAppOpsService = IAppOpsService.Stub.asInterface(
1238 ServiceManager.getService(Context.APP_OPS_SERVICE));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001239 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001240 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001242
1243 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001244 public void onBootPhase(int phase) {
1245 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1246 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001247 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001248 mLocalDeviceIdleController
1249 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001250 try {
1251 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, null,
1252 new AppOpsWatcher());
1253 } catch (RemoteException rexc) {
1254 // Shouldn't happen as they are in the same process.
1255 Slog.e(TAG, "AppOps service not reachable", rexc);
1256 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001257 }
1258 }
1259
1260 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001261 protected void finalize() throws Throwable {
1262 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001263 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 } finally {
1265 super.finalize();
1266 }
1267 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001268
Adam Lesinski182f73f2013-12-05 16:48:06 -08001269 void setTimeZoneImpl(String tz) {
1270 if (TextUtils.isEmpty(tz)) {
1271 return;
David Christieebe51fc2013-07-26 13:23:29 -07001272 }
1273
Adam Lesinski182f73f2013-12-05 16:48:06 -08001274 TimeZone zone = TimeZone.getTimeZone(tz);
1275 // Prevent reentrant calls from stepping on each other when writing
1276 // the time zone property
1277 boolean timeZoneWasChanged = false;
1278 synchronized (this) {
1279 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1280 if (current == null || !current.equals(zone.getID())) {
1281 if (localLOGV) {
1282 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1283 }
1284 timeZoneWasChanged = true;
1285 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1286 }
1287
1288 // Update the kernel timezone information
1289 // Kernel tracks time offsets as 'minutes west of GMT'
1290 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001291 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001292 }
1293
1294 TimeZone.setDefault(null);
1295
1296 if (timeZoneWasChanged) {
1297 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001298 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001299 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001300 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001301 intent.putExtra("time-zone", zone.getID());
1302 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1303 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001304 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001305
Adam Lesinski182f73f2013-12-05 16:48:06 -08001306 void removeImpl(PendingIntent operation) {
1307 if (operation == null) {
1308 return;
1309 }
1310 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001311 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001312 }
1313 }
1314
1315 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001316 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1317 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1318 int callingUid, String callingPackage) {
1319 // must be *either* PendingIntent or AlarmReceiver, but not both
1320 if ((operation == null && directReceiver == null)
1321 || (operation != null && directReceiver != null)) {
1322 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1323 // NB: previous releases failed silently here, so we are continuing to do the same
1324 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001325 return;
1326 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001327
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001328 // Sanity check the window length. This will catch people mistakenly
1329 // trying to pass an end-of-window timestamp rather than a duration.
1330 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1331 Slog.w(TAG, "Window length " + windowLength
1332 + "ms suspiciously long; limiting to 1 hour");
1333 windowLength = AlarmManager.INTERVAL_HOUR;
1334 }
1335
Christopher Tate498c6cb2014-11-17 16:09:27 -08001336 // Sanity check the recurrence interval. This will catch people who supply
1337 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001338 final long minInterval = mConstants.MIN_INTERVAL;
1339 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001340 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001341 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001342 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001343 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001344 }
1345
Christopher Tatee0a22b32013-07-11 14:43:13 -07001346 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1347 throw new IllegalArgumentException("Invalid alarm type " + type);
1348 }
1349
Christopher Tate5f221e82013-07-30 17:13:15 -07001350 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001351 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001352 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001353 + " pid=" + what);
1354 triggerAtTime = 0;
1355 }
1356
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001357 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001358 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1359 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001360 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001361 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1362
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001363 final long maxElapsed;
1364 if (windowLength == AlarmManager.WINDOW_EXACT) {
1365 maxElapsed = triggerElapsed;
1366 } else if (windowLength < 0) {
1367 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001368 // Fix this window in place, so that as time approaches we don't collapse it.
1369 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001370 } else {
1371 maxElapsed = triggerElapsed + windowLength;
1372 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001373
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001375 if (DEBUG_BATCH) {
1376 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001377 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001378 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001379 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001381 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001382 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1383 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001384 }
1385 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001386
Christopher Tate3e04b472013-10-21 17:51:31 -07001387 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001388 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1389 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1390 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001391 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001392 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1393 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001394 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001395 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001396 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1397 + " -- package not allowed to start");
1398 return;
1399 }
1400 } catch (RemoteException e) {
1401 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001402 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001403 setImplLocked(a, false, doValidate);
1404 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001405
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001406 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1407 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001408 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001409 // The caller has given the time they want this to happen at, however we need
1410 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001411 // bring us out of idle at an earlier time.
1412 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001413 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001414 }
1415 // Add fuzz to make the alarm go off some time before the actual desired time.
1416 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001417 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001418 if (fuzz > 0) {
1419 if (mRandom == null) {
1420 mRandom = new Random();
1421 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001422 final int delta = mRandom.nextInt(fuzz);
1423 a.whenElapsed -= delta;
1424 if (false) {
1425 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1426 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1427 Slog.d(TAG, "Applied fuzz: " + fuzz);
1428 Slog.d(TAG, "Final delta: " + delta);
1429 Slog.d(TAG, "Final when: " + a.whenElapsed);
1430 }
1431 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001432 }
1433
1434 } else if (mPendingIdleUntil != null) {
1435 // We currently have an idle until alarm scheduled; if the new alarm has
1436 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001437 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1438 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1439 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001440 == 0) {
1441 mPendingWhileIdleAlarms.add(a);
1442 return;
1443 }
1444 }
1445
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001446 if (RECORD_DEVICE_IDLE_ALARMS) {
1447 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1448 IdleDispatchEntry ent = new IdleDispatchEntry();
1449 ent.uid = a.uid;
1450 ent.pkg = a.operation.getCreatorPackage();
1451 ent.tag = a.operation.getTag("");
1452 ent.op = "SET";
1453 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1454 ent.argRealtime = a.whenElapsed;
1455 mAllowWhileIdleDispatches.add(ent);
1456 }
1457 }
1458
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001459 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1460 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001461 if (whichBatch < 0) {
1462 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001463 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001465 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001466 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001467 // The start time of this batch advanced, so batch ordering may
1468 // have just been broken. Move it to where it now belongs.
1469 mAlarmBatches.remove(whichBatch);
1470 addBatchLocked(mAlarmBatches, batch);
1471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 }
1473
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001474 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001475 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001476 }
1477
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001478 boolean needRebatch = false;
1479
1480 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001481 if (RECORD_DEVICE_IDLE_ALARMS) {
1482 if (mPendingIdleUntil == null) {
1483 IdleDispatchEntry ent = new IdleDispatchEntry();
1484 ent.uid = 0;
1485 ent.pkg = "START IDLE";
1486 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1487 mAllowWhileIdleDispatches.add(ent);
1488 }
1489 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001490 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1491 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1492 + " to " + a);
1493 }
1494
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001495 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001496 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001497 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001498 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1499 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1500 mNextWakeFromIdle = a;
1501 // If this wake from idle is earlier than whatever was previously scheduled,
1502 // and we are currently idling, then we need to rebatch alarms in case the idle
1503 // until time needs to be updated.
1504 if (mPendingIdleUntil != null) {
1505 needRebatch = true;
1506 }
1507 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001508 }
1509
1510 if (!rebatching) {
1511 if (DEBUG_VALIDATE) {
1512 if (doValidate && !validateConsistencyLocked()) {
1513 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1514 + " when(hex)=" + Long.toHexString(a.when)
1515 + " whenElapsed=" + a.whenElapsed
1516 + " maxWhenElapsed=" + a.maxWhenElapsed
1517 + " interval=" + a.repeatInterval + " op=" + a.operation
1518 + " flags=0x" + Integer.toHexString(a.flags));
1519 rebatchAllAlarmsLocked(false);
1520 needRebatch = false;
1521 }
1522 }
1523
1524 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001525 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001526 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001527
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001528 rescheduleKernelAlarmsLocked();
1529 updateNextAlarmClockLocked();
1530 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001531 }
1532
Adam Lesinski182f73f2013-12-05 16:48:06 -08001533 private final IBinder mService = new IAlarmManager.Stub() {
1534 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001535 public void set(String callingPackage,
1536 int type, long triggerAtTime, long windowLength, long interval, int flags,
1537 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1538 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001539 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001540
1541 // make sure the caller is not lying about which package should be blamed for
1542 // wakelock time spent in alarm delivery
1543 mAppOps.checkPackage(callingUid, callingPackage);
1544
1545 // Repeating alarms must use PendingIntent, not direct listener
1546 if (interval != 0) {
1547 if (directReceiver != null) {
1548 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1549 }
1550 }
1551
Adam Lesinski182f73f2013-12-05 16:48:06 -08001552 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001553 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001554 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001555 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001556 }
1557
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001558 // No incoming callers can request either WAKE_FROM_IDLE or
1559 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1560 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1561 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1562
1563 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1564 // manager when to come out of idle mode, which is only for DeviceIdleController.
1565 if (callingUid != Process.SYSTEM_UID) {
1566 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1567 }
1568
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001569 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001570 if (windowLength == AlarmManager.WINDOW_EXACT) {
1571 flags |= AlarmManager.FLAG_STANDALONE;
1572 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001573
1574 // If this alarm is for an alarm clock, then it must be standalone and we will
1575 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001576 if (alarmClock != null) {
1577 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001578
1579 // If the caller is a core system component or on the user's whitelist, and not calling
1580 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1581 // This means we will allow these alarms to go off as normal even while idle, with no
1582 // timing restrictions.
1583 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001584 || callingUid == mSystemUiUid
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001585 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1586 UserHandle.getAppId(callingUid)) >= 0)) {
1587 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1588 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001589 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001590
Christopher Tate14a7bb02015-10-01 10:24:31 -07001591 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1592 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001593 }
Christopher Tate89779822012-08-31 14:40:03 -07001594
Adam Lesinski182f73f2013-12-05 16:48:06 -08001595 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001596 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001597 getContext().enforceCallingOrSelfPermission(
1598 "android.permission.SET_TIME",
1599 "setTime");
1600
Greg Hackmann0cab8962014-02-21 16:35:52 -08001601 if (mNativeData == 0) {
1602 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1603 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001604 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001605
1606 synchronized (mLock) {
1607 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001608 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001610
1611 @Override
1612 public void setTimeZone(String tz) {
1613 getContext().enforceCallingOrSelfPermission(
1614 "android.permission.SET_TIME_ZONE",
1615 "setTimeZone");
1616
1617 final long oldId = Binder.clearCallingIdentity();
1618 try {
1619 setTimeZoneImpl(tz);
1620 } finally {
1621 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001622 }
1623 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001624
Adam Lesinski182f73f2013-12-05 16:48:06 -08001625 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001626 public void remove(PendingIntent operation, IAlarmListener listener) {
1627 if (operation == null && listener == null) {
1628 Slog.w(TAG, "remove() with no intent or listener");
1629 return;
1630 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001631
Christopher Tate14a7bb02015-10-01 10:24:31 -07001632 synchronized (mLock) {
1633 removeLocked(operation, listener);
1634 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001636
Adam Lesinski182f73f2013-12-05 16:48:06 -08001637 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001638 public long getNextWakeFromIdleTime() {
1639 return getNextWakeFromIdleTimeImpl();
1640 }
1641
1642 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001643 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001644 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1645 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1646 "getNextAlarmClock", null);
1647
1648 return getNextAlarmClockImpl(userId);
1649 }
1650
1651 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001652 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001653 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001654
1655 if (args.length > 0 && "--proto".equals(args[0])) {
1656 dumpProto(fd);
1657 } else {
1658 dumpImpl(pw);
1659 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001660 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001661 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001662
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001663 public final class LocalService {
1664 public void setDeviceIdleUserWhitelist(int[] appids) {
1665 setDeviceIdleUserWhitelistImpl(appids);
1666 }
1667 }
1668
Adam Lesinski182f73f2013-12-05 16:48:06 -08001669 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 synchronized (mLock) {
1671 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001672 mConstants.dump(pw);
1673 pw.println();
1674
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001675 pw.print(" Foreground uids: [");
1676 for (int i = 0; i < mForegroundUids.size(); i++) {
1677 if (mForegroundUids.valueAt(i)) pw.print(mForegroundUids.keyAt(i) + " ");
1678 }
1679 pw.println("]");
1680 pw.println(" Forced app standby packages: " + mForcedAppStandbyPackages);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001681 final long nowRTC = System.currentTimeMillis();
1682 final long nowELAPSED = SystemClock.elapsedRealtime();
1683 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1684
Dianne Hackborna750a632015-06-16 17:18:23 -07001685 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001686 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001687 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001688 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001689 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001690 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001691 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001692 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1693 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001694 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001695 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001696 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1697 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001698 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001699 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1700 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001701 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001702 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1703 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001704 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001705 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1706 pw.println();
1707 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001708
1709 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1710 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001711 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001712 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001713 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001714 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001715 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001716 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1717 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1718 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001719 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001720 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001721
John Spurlock604a5ee2015-06-01 12:27:22 -04001722 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001723 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001724 final TreeSet<Integer> users = new TreeSet<>();
1725 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1726 users.add(mNextAlarmClockForUser.keyAt(i));
1727 }
1728 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1729 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1730 }
1731 for (int user : users) {
1732 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1733 final long time = next != null ? next.getTriggerTime() : 0;
1734 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001735 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001736 pw.print(" pendingSend:"); pw.print(pendingSend);
1737 pw.print(" time:"); pw.print(time);
1738 if (time > 0) {
1739 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1740 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1741 }
1742 pw.println();
1743 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001744 if (mAlarmBatches.size() > 0) {
1745 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001746 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001747 pw.println(mAlarmBatches.size());
1748 for (Batch b : mAlarmBatches) {
1749 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001750 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001751 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001753 pw.println();
1754 pw.println(" Pending user blocked background alarms: ");
1755 boolean blocked = false;
1756 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1757 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1758 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1759 blocked = true;
1760 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1761 }
1762 }
1763 if (!blocked) {
1764 pw.println(" none");
1765 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001766 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001767 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001768 pw.println(" Idle mode state:");
1769 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001770 if (mPendingIdleUntil != null) {
1771 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001772 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001773 } else {
1774 pw.println("null");
1775 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001776 pw.println(" Pending alarms:");
1777 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001778 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001779 if (mNextWakeFromIdle != null) {
1780 pw.println();
1781 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001782 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001783 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001784
1785 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001786 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001787 if (mPendingNonWakeupAlarms.size() > 0) {
1788 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001789 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001790 } else {
1791 pw.println("(none)");
1792 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001793 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001794 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1795 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001796 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001797 pw.print(", max non-interactive time: ");
1798 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1799 pw.println();
1800
1801 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001802 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001803 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1804 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1805 pw.print(" Listener send count: "); pw.println(mListenerCount);
1806 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001807 pw.println();
1808
Christopher Tate7f2a0352015-12-08 10:24:33 -08001809 if (mInFlight.size() > 0) {
1810 pw.println("Outstanding deliveries:");
1811 for (int i = 0; i < mInFlight.size(); i++) {
1812 pw.print(" #"); pw.print(i); pw.print(": ");
1813 pw.println(mInFlight.get(i));
1814 }
1815 pw.println();
1816 }
1817
Dianne Hackborna750a632015-06-16 17:18:23 -07001818 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001819 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1820 pw.println();
1821 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001822 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001823 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1824 pw.print(" UID ");
1825 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1826 pw.print(": ");
1827 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1828 nowELAPSED, pw);
1829 pw.println();
1830 }
1831 }
1832 pw.println();
1833
Dianne Hackborn81038902012-11-26 17:04:09 -08001834 if (mLog.dump(pw, " Recent problems", " ")) {
1835 pw.println();
1836 }
1837
1838 final FilterStats[] topFilters = new FilterStats[10];
1839 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1840 @Override
1841 public int compare(FilterStats lhs, FilterStats rhs) {
1842 if (lhs.aggregateTime < rhs.aggregateTime) {
1843 return 1;
1844 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1845 return -1;
1846 }
1847 return 0;
1848 }
1849 };
1850 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001851 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001852 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1853 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1854 for (int ip=0; ip<uidStats.size(); ip++) {
1855 BroadcastStats bs = uidStats.valueAt(ip);
1856 for (int is=0; is<bs.filterStats.size(); is++) {
1857 FilterStats fs = bs.filterStats.valueAt(is);
1858 int pos = len > 0
1859 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1860 if (pos < 0) {
1861 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001862 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001863 if (pos < topFilters.length) {
1864 int copylen = topFilters.length - pos - 1;
1865 if (copylen > 0) {
1866 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1867 }
1868 topFilters[pos] = fs;
1869 if (len < topFilters.length) {
1870 len++;
1871 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001872 }
1873 }
1874 }
1875 }
1876 if (len > 0) {
1877 pw.println(" Top Alarms:");
1878 for (int i=0; i<len; i++) {
1879 FilterStats fs = topFilters[i];
1880 pw.print(" ");
1881 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1882 TimeUtils.formatDuration(fs.aggregateTime, pw);
1883 pw.print(" running, "); pw.print(fs.numWakeup);
1884 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001885 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1886 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001887 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001888 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001889 pw.println();
1890 }
1891 }
1892
1893 pw.println(" ");
1894 pw.println(" Alarm Stats:");
1895 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001896 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1897 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1898 for (int ip=0; ip<uidStats.size(); ip++) {
1899 BroadcastStats bs = uidStats.valueAt(ip);
1900 pw.print(" ");
1901 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1902 UserHandle.formatUid(pw, bs.mUid);
1903 pw.print(":");
1904 pw.print(bs.mPackageName);
1905 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1906 pw.print(" running, "); pw.print(bs.numWakeup);
1907 pw.println(" wakeups:");
1908 tmpFilters.clear();
1909 for (int is=0; is<bs.filterStats.size(); is++) {
1910 tmpFilters.add(bs.filterStats.valueAt(is));
1911 }
1912 Collections.sort(tmpFilters, comparator);
1913 for (int i=0; i<tmpFilters.size(); i++) {
1914 FilterStats fs = tmpFilters.get(i);
1915 pw.print(" ");
1916 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1917 TimeUtils.formatDuration(fs.aggregateTime, pw);
1918 pw.print(" "); pw.print(fs.numWakeup);
1919 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001920 pw.print(" alarms, last ");
1921 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1922 pw.println(":");
1923 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001924 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001925 pw.println();
1926 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 }
1928 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001929
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001930 if (RECORD_DEVICE_IDLE_ALARMS) {
1931 pw.println();
1932 pw.println(" Allow while idle dispatches:");
1933 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1934 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1935 pw.print(" ");
1936 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1937 pw.print(": ");
1938 UserHandle.formatUid(pw, ent.uid);
1939 pw.print(":");
1940 pw.println(ent.pkg);
1941 if (ent.op != null) {
1942 pw.print(" ");
1943 pw.print(ent.op);
1944 pw.print(" / ");
1945 pw.print(ent.tag);
1946 if (ent.argRealtime != 0) {
1947 pw.print(" (");
1948 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1949 pw.print(")");
1950 }
1951 pw.println();
1952 }
1953 }
1954 }
1955
Christopher Tate18a75f12013-07-01 18:18:59 -07001956 if (WAKEUP_STATS) {
1957 pw.println();
1958 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001959 long last = -1;
1960 for (WakeupEvent event : mRecentWakeups) {
1961 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1962 pw.print('|');
1963 if (last < 0) {
1964 pw.print('0');
1965 } else {
1966 pw.print(event.when - last);
1967 }
1968 last = event.when;
1969 pw.print('|'); pw.print(event.uid);
1970 pw.print('|'); pw.print(event.action);
1971 pw.println();
1972 }
1973 pw.println();
1974 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001975 }
1976 }
1977
Kweku Adams61e03292017-10-19 14:27:12 -07001978 void dumpProto(FileDescriptor fd) {
1979 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1980
1981 synchronized (mLock) {
1982 final long nowRTC = System.currentTimeMillis();
1983 final long nowElapsed = SystemClock.elapsedRealtime();
1984 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1985 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1986 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1987 mLastTimeChangeClockTime);
1988 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
1989 mLastTimeChangeRealtime);
1990
1991 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
1992
1993 final int foregroundUidsSize = mForegroundUids.size();
1994 for (int i = 0; i < foregroundUidsSize; i++) {
1995 if (mForegroundUids.valueAt(i)) {
1996 proto.write(AlarmManagerServiceProto.FOREGROUND_UIDS, mForegroundUids.keyAt(i));
1997 }
1998 }
1999 for (String pkg : mForcedAppStandbyPackages) {
2000 proto.write(AlarmManagerServiceProto.FORCED_APP_STANDBY_PACKAGES, pkg);
2001 }
2002
2003 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2004 if (!mInteractive) {
2005 // Durations
2006 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2007 nowElapsed - mNonInteractiveStartTime);
2008 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2009 currentNonWakeupFuzzLocked(nowElapsed));
2010 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2011 nowElapsed - mLastAlarmDeliveryTime);
2012 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2013 nowElapsed - mNextNonWakeupDeliveryTime);
2014 }
2015
2016 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2017 mNextNonWakeup - nowElapsed);
2018 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2019 mNextWakeup - nowElapsed);
2020 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2021 nowElapsed - mLastWakeup);
2022 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2023 nowElapsed - mLastWakeupSet);
2024 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
2025 for (int i : mDeviceIdleUserWhitelist) {
2026 proto.write(AlarmManagerServiceProto.DEVICE_IDLE_USER_WHITELIST_APP_IDS, i);
2027 }
2028
2029 final TreeSet<Integer> users = new TreeSet<>();
2030 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2031 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2032 users.add(mNextAlarmClockForUser.keyAt(i));
2033 }
2034 final int pendingSendNextAlarmClockChangedForUserSize =
2035 mPendingSendNextAlarmClockChangedForUser.size();
2036 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2037 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2038 }
2039 for (int user : users) {
2040 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2041 final long time = next != null ? next.getTriggerTime() : 0;
2042 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2043 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2044 proto.write(AlarmClockMetadataProto.USER, user);
2045 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2046 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2047 proto.end(aToken);
2048 }
2049 for (Batch b : mAlarmBatches) {
2050 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2051 nowElapsed, nowRTC);
2052 }
2053 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2054 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2055 if (blockedAlarms != null) {
2056 for (Alarm a : blockedAlarms) {
2057 a.writeToProto(proto,
2058 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2059 nowElapsed, nowRTC);
2060 }
2061 }
2062 }
2063 if (mPendingIdleUntil != null) {
2064 mPendingIdleUntil.writeToProto(
2065 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2066 }
2067 for (Alarm a : mPendingWhileIdleAlarms) {
2068 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2069 nowElapsed, nowRTC);
2070 }
2071 if (mNextWakeFromIdle != null) {
2072 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2073 nowElapsed, nowRTC);
2074 }
2075
2076 for (Alarm a : mPendingNonWakeupAlarms) {
2077 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2078 nowElapsed, nowRTC);
2079 }
2080
2081 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2082 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2083 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2084 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2085 mNonInteractiveTime);
2086
2087 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2088 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2089 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2090 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2091 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2092
2093 for (InFlight f : mInFlight) {
2094 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2095 }
2096
2097 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2098 mAllowWhileIdleMinTime);
2099 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2100 final long token = proto.start(
2101 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2102 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2103 mLastAllowWhileIdleDispatch.keyAt(i));
2104 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2105 mLastAllowWhileIdleDispatch.valueAt(i));
2106 proto.end(token);
2107 }
2108
2109 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2110
2111 final FilterStats[] topFilters = new FilterStats[10];
2112 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2113 @Override
2114 public int compare(FilterStats lhs, FilterStats rhs) {
2115 if (lhs.aggregateTime < rhs.aggregateTime) {
2116 return 1;
2117 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2118 return -1;
2119 }
2120 return 0;
2121 }
2122 };
2123 int len = 0;
2124 // Get the top 10 FilterStats, ordered by aggregateTime.
2125 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2126 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2127 for (int ip = 0; ip < uidStats.size(); ++ip) {
2128 BroadcastStats bs = uidStats.valueAt(ip);
2129 for (int is = 0; is < bs.filterStats.size(); ++is) {
2130 FilterStats fs = bs.filterStats.valueAt(is);
2131 int pos = len > 0
2132 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2133 if (pos < 0) {
2134 pos = -pos - 1;
2135 }
2136 if (pos < topFilters.length) {
2137 int copylen = topFilters.length - pos - 1;
2138 if (copylen > 0) {
2139 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2140 }
2141 topFilters[pos] = fs;
2142 if (len < topFilters.length) {
2143 len++;
2144 }
2145 }
2146 }
2147 }
2148 }
2149 for (int i = 0; i < len; ++i) {
2150 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2151 FilterStats fs = topFilters[i];
2152
2153 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2154 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2155 fs.mBroadcastStats.mPackageName);
2156 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2157
2158 proto.end(token);
2159 }
2160
2161 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2162 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2163 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2164 for (int ip = 0; ip < uidStats.size(); ++ip) {
2165 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2166
2167 BroadcastStats bs = uidStats.valueAt(ip);
2168 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2169
2170 // uidStats is an ArrayMap, which we can't sort.
2171 tmpFilters.clear();
2172 for (int is = 0; is < bs.filterStats.size(); ++is) {
2173 tmpFilters.add(bs.filterStats.valueAt(is));
2174 }
2175 Collections.sort(tmpFilters, comparator);
2176 for (FilterStats fs : tmpFilters) {
2177 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2178 }
2179
2180 proto.end(token);
2181 }
2182 }
2183
2184 if (RECORD_DEVICE_IDLE_ALARMS) {
2185 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2186 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2187 final long token = proto.start(
2188 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2189
2190 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2191 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2192 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2193 proto.write(IdleDispatchEntryProto.OP, ent.op);
2194 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2195 ent.elapsedRealtime);
2196 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2197
2198 proto.end(token);
2199 }
2200 }
2201
2202 if (WAKEUP_STATS) {
2203 for (WakeupEvent event : mRecentWakeups) {
2204 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2205 proto.write(WakeupEventProto.UID, event.uid);
2206 proto.write(WakeupEventProto.ACTION, event.action);
2207 proto.write(WakeupEventProto.WHEN, event.when);
2208 proto.end(token);
2209 }
2210 }
2211 }
2212
2213 proto.flush();
2214 }
2215
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002216 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002217 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2218 PrintWriter pw = new PrintWriter(bs);
2219 final long nowRTC = System.currentTimeMillis();
2220 final long nowELAPSED = SystemClock.elapsedRealtime();
2221 final int NZ = mAlarmBatches.size();
2222 for (int iz = 0; iz < NZ; iz++) {
2223 Batch bz = mAlarmBatches.get(iz);
2224 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002225 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002226 pw.flush();
2227 Slog.v(TAG, bs.toString());
2228 bs.reset();
2229 }
2230 }
2231
2232 private boolean validateConsistencyLocked() {
2233 if (DEBUG_VALIDATE) {
2234 long lastTime = Long.MIN_VALUE;
2235 final int N = mAlarmBatches.size();
2236 for (int i = 0; i < N; i++) {
2237 Batch b = mAlarmBatches.get(i);
2238 if (b.start >= lastTime) {
2239 // duplicate start times are okay because of standalone batches
2240 lastTime = b.start;
2241 } else {
2242 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002243 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2244 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002245 return false;
2246 }
2247 }
2248 }
2249 return true;
2250 }
2251
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002252 private Batch findFirstWakeupBatchLocked() {
2253 final int N = mAlarmBatches.size();
2254 for (int i = 0; i < N; i++) {
2255 Batch b = mAlarmBatches.get(i);
2256 if (b.hasWakeups()) {
2257 return b;
2258 }
2259 }
2260 return null;
2261 }
2262
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002263 long getNextWakeFromIdleTimeImpl() {
2264 synchronized (mLock) {
2265 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2266 }
2267 }
2268
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002269 void setDeviceIdleUserWhitelistImpl(int[] appids) {
2270 synchronized (mLock) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002271 // appids are sorted, just send pending alarms for any new appids added to the whitelist
2272 int i = 0, j = 0;
2273 while (i < appids.length) {
2274 while (j < mDeviceIdleUserWhitelist.length
2275 && mDeviceIdleUserWhitelist[j] < appids[i]) {
2276 j++;
2277 }
2278 if (j < mDeviceIdleUserWhitelist.length
2279 && appids[i] != mDeviceIdleUserWhitelist[j]) {
2280 if (DEBUG_BG_LIMIT) {
2281 Slog.d(TAG, "Sending blocked alarms for whitelisted appid " + appids[j]);
2282 }
2283 sendPendingBackgroundAlarmsForAppIdLocked(appids[j]);
2284 }
2285 i++;
2286 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002287 mDeviceIdleUserWhitelist = appids;
2288 }
2289 }
2290
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002291 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002292 synchronized (mLock) {
2293 return mNextAlarmClockForUser.get(userId);
2294 }
2295 }
2296
2297 /**
2298 * Recomputes the next alarm clock for all users.
2299 */
2300 private void updateNextAlarmClockLocked() {
2301 if (!mNextAlarmClockMayChange) {
2302 return;
2303 }
2304 mNextAlarmClockMayChange = false;
2305
Jose Lima235510e2014-08-13 12:50:01 -07002306 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002307 nextForUser.clear();
2308
2309 final int N = mAlarmBatches.size();
2310 for (int i = 0; i < N; i++) {
2311 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2312 final int M = alarms.size();
2313
2314 for (int j = 0; j < M; j++) {
2315 Alarm a = alarms.get(j);
2316 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002317 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002318 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002319
2320 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002321 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002322 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002323 " for user " + userId);
2324 }
2325
2326 // Alarms and batches are sorted by time, no need to compare times here.
2327 if (nextForUser.get(userId) == null) {
2328 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002329 } else if (a.alarmClock.equals(current)
2330 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2331 // same/earlier time and it's the one we cited before, so stick with it
2332 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002333 }
2334 }
2335 }
2336 }
2337
2338 // Update mNextAlarmForUser with new values.
2339 final int NN = nextForUser.size();
2340 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002341 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002342 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002343 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002344 if (!newAlarm.equals(currentAlarm)) {
2345 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2346 }
2347 }
2348
2349 // Remove users without any alarm clocks scheduled.
2350 final int NNN = mNextAlarmClockForUser.size();
2351 for (int i = NNN - 1; i >= 0; i--) {
2352 int userId = mNextAlarmClockForUser.keyAt(i);
2353 if (nextForUser.get(userId) == null) {
2354 updateNextAlarmInfoForUserLocked(userId, null);
2355 }
2356 }
2357 }
2358
Jose Lima235510e2014-08-13 12:50:01 -07002359 private void updateNextAlarmInfoForUserLocked(int userId,
2360 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002361 if (alarmClock != null) {
2362 if (DEBUG_ALARM_CLOCK) {
2363 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002364 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002365 }
2366 mNextAlarmClockForUser.put(userId, alarmClock);
2367 } else {
2368 if (DEBUG_ALARM_CLOCK) {
2369 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2370 }
2371 mNextAlarmClockForUser.remove(userId);
2372 }
2373
2374 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2375 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2376 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2377 }
2378
2379 /**
2380 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2381 * for which alarm clocks have changed since the last call to this.
2382 *
2383 * Do not call with a lock held. Only call from mHandler's thread.
2384 *
2385 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2386 */
2387 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002388 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002389 pendingUsers.clear();
2390
2391 synchronized (mLock) {
2392 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2393 for (int i = 0; i < N; i++) {
2394 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2395 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2396 }
2397 mPendingSendNextAlarmClockChangedForUser.clear();
2398 }
2399
2400 final int N = pendingUsers.size();
2401 for (int i = 0; i < N; i++) {
2402 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002403 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002404 Settings.System.putStringForUser(getContext().getContentResolver(),
2405 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002406 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002407 userId);
2408
2409 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2410 new UserHandle(userId));
2411 }
2412 }
2413
2414 /**
2415 * Formats an alarm like platform/packages/apps/DeskClock used to.
2416 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002417 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2418 int userId) {
2419 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002420 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2421 return (info == null) ? "" :
2422 DateFormat.format(pattern, info.getTriggerTime()).toString();
2423 }
2424
Adam Lesinski182f73f2013-12-05 16:48:06 -08002425 void rescheduleKernelAlarmsLocked() {
2426 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2427 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002428 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002429 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002430 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002431 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002432 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002433 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002434 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002435 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002436 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002437 if (firstBatch != firstWakeup) {
2438 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002439 }
2440 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002441 if (mPendingNonWakeupAlarms.size() > 0) {
2442 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2443 nextNonWakeup = mNextNonWakeupDeliveryTime;
2444 }
2445 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002446 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002447 mNextNonWakeup = nextNonWakeup;
2448 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2449 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002450 }
2451
Christopher Tate14a7bb02015-10-01 10:24:31 -07002452 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002453 boolean didRemove = false;
2454 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2455 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002456 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002457 if (b.size() == 0) {
2458 mAlarmBatches.remove(i);
2459 }
2460 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002461 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002462 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002463 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2464 mPendingWhileIdleAlarms.remove(i);
2465 }
2466 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002467 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2468 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2469 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2470 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2471 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2472 alarmsForUid.remove(j);
2473 }
2474 }
2475 if (alarmsForUid.size() == 0) {
2476 mPendingBackgroundAlarms.removeAt(i);
2477 }
2478 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002479 if (didRemove) {
2480 if (DEBUG_BATCH) {
2481 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2482 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002483 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002484 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002485 mPendingIdleUntil = null;
2486 restorePending = true;
2487 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002488 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002489 mNextWakeFromIdle = null;
2490 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002491 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002492 if (restorePending) {
2493 restorePendingWhileIdleAlarmsLocked();
2494 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002495 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002496 }
2497 }
2498
2499 void removeLocked(String packageName) {
2500 boolean didRemove = false;
2501 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2502 Batch b = mAlarmBatches.get(i);
2503 didRemove |= b.remove(packageName);
2504 if (b.size() == 0) {
2505 mAlarmBatches.remove(i);
2506 }
2507 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002508 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002509 final Alarm a = mPendingWhileIdleAlarms.get(i);
2510 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002511 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2512 mPendingWhileIdleAlarms.remove(i);
2513 }
2514 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002515 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2516 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2517 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2518 if (alarmsForUid.get(j).matches(packageName)) {
2519 alarmsForUid.remove(j);
2520 }
2521 }
2522 if (alarmsForUid.size() == 0) {
2523 mPendingBackgroundAlarms.removeAt(i);
2524 }
2525 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002526 if (didRemove) {
2527 if (DEBUG_BATCH) {
2528 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2529 }
2530 rebatchAllAlarmsLocked(true);
2531 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002532 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002533 }
2534 }
2535
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002536 void removeForStoppedLocked(int uid) {
2537 boolean didRemove = false;
2538 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2539 Batch b = mAlarmBatches.get(i);
2540 didRemove |= b.removeForStopped(uid);
2541 if (b.size() == 0) {
2542 mAlarmBatches.remove(i);
2543 }
2544 }
2545 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2546 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002547 if (a.uid == uid) {
2548 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2549 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002550 }
2551 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002552 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2553 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2554 mPendingBackgroundAlarms.removeAt(i);
2555 }
2556 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002557 if (didRemove) {
2558 if (DEBUG_BATCH) {
2559 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2560 }
2561 rebatchAllAlarmsLocked(true);
2562 rescheduleKernelAlarmsLocked();
2563 updateNextAlarmClockLocked();
2564 }
2565 }
2566
Adam Lesinski182f73f2013-12-05 16:48:06 -08002567 void removeUserLocked(int userHandle) {
2568 boolean didRemove = false;
2569 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2570 Batch b = mAlarmBatches.get(i);
2571 didRemove |= b.remove(userHandle);
2572 if (b.size() == 0) {
2573 mAlarmBatches.remove(i);
2574 }
2575 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002576 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002577 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002578 == userHandle) {
2579 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2580 mPendingWhileIdleAlarms.remove(i);
2581 }
2582 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002583 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2584 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2585 mPendingBackgroundAlarms.removeAt(i);
2586 }
2587 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002588 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2589 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2590 mLastAllowWhileIdleDispatch.removeAt(i);
2591 }
2592 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002593
2594 if (didRemove) {
2595 if (DEBUG_BATCH) {
2596 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2597 }
2598 rebatchAllAlarmsLocked(true);
2599 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002600 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002601 }
2602 }
2603
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002604 void interactiveStateChangedLocked(boolean interactive) {
2605 if (mInteractive != interactive) {
2606 mInteractive = interactive;
2607 final long nowELAPSED = SystemClock.elapsedRealtime();
2608 if (interactive) {
2609 if (mPendingNonWakeupAlarms.size() > 0) {
2610 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2611 mTotalDelayTime += thisDelayTime;
2612 if (mMaxDelayTime < thisDelayTime) {
2613 mMaxDelayTime = thisDelayTime;
2614 }
2615 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2616 mPendingNonWakeupAlarms.clear();
2617 }
2618 if (mNonInteractiveStartTime > 0) {
2619 long dur = nowELAPSED - mNonInteractiveStartTime;
2620 if (dur > mNonInteractiveTime) {
2621 mNonInteractiveTime = dur;
2622 }
2623 }
2624 } else {
2625 mNonInteractiveStartTime = nowELAPSED;
2626 }
2627 }
2628 }
2629
Adam Lesinski182f73f2013-12-05 16:48:06 -08002630 boolean lookForPackageLocked(String packageName) {
2631 for (int i = 0; i < mAlarmBatches.size(); i++) {
2632 Batch b = mAlarmBatches.get(i);
2633 if (b.hasPackage(packageName)) {
2634 return true;
2635 }
2636 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002637 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002638 final Alarm a = mPendingWhileIdleAlarms.get(i);
2639 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002640 return true;
2641 }
2642 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002643 return false;
2644 }
2645
2646 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002647 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002648 // The kernel never triggers alarms with negative wakeup times
2649 // so we ensure they are positive.
2650 long alarmSeconds, alarmNanoseconds;
2651 if (when < 0) {
2652 alarmSeconds = 0;
2653 alarmNanoseconds = 0;
2654 } else {
2655 alarmSeconds = when / 1000;
2656 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2657 }
Kweku Adams61e03292017-10-19 14:27:12 -07002658
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002659 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002660 } else {
2661 Message msg = Message.obtain();
2662 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002663
Adam Lesinski182f73f2013-12-05 16:48:06 -08002664 mHandler.removeMessages(ALARM_EVENT);
2665 mHandler.sendMessageAtTime(msg, when);
2666 }
2667 }
2668
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002669 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002670 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 for (int i=list.size()-1; i>=0; i--) {
2672 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002673 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2674 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002675 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002676 }
2677 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002678
2679 private static final String labelForType(int type) {
2680 switch (type) {
2681 case RTC: return "RTC";
2682 case RTC_WAKEUP : return "RTC_WAKEUP";
2683 case ELAPSED_REALTIME : return "ELAPSED";
2684 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002685 }
2686 return "--unknown--";
2687 }
2688
2689 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002690 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002691 for (int i=list.size()-1; i>=0; i--) {
2692 Alarm a = list.get(i);
2693 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002694 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2695 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002696 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002697 }
2698 }
2699
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002700 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002701 if (alarm.alarmClock != null) {
2702 // Don't block alarm clocks
2703 return false;
2704 }
2705 if (alarm.operation != null
2706 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2707 // Don't block starting foreground components
2708 return false;
2709 }
2710 final String sourcePackage =
2711 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2712 final int sourceUid = alarm.creatorUid;
2713 return mForcedAppStandbyPackages.contains(sourcePackage) && !mForegroundUids.get(sourceUid)
2714 && Arrays.binarySearch(mDeviceIdleUserWhitelist, UserHandle.getAppId(sourceUid))
2715 < 0;
2716 }
2717
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002718 private native long init();
2719 private native void close(long nativeData);
2720 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2721 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002722 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002723 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002724
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002725 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002726 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002727 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002728 // batches are temporally sorted, so we need only pull from the
2729 // start of the list until we either empty it or hit a batch
2730 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002731 while (mAlarmBatches.size() > 0) {
2732 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002733 if (batch.start > nowELAPSED) {
2734 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002735 break;
2736 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002737
Christopher Tatee0a22b32013-07-11 14:43:13 -07002738 // We will (re)schedule some alarms now; don't let that interfere
2739 // with delivery of this current batch
2740 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002741
Christopher Tatee0a22b32013-07-11 14:43:13 -07002742 final int N = batch.size();
2743 for (int i = 0; i < N; i++) {
2744 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002745
2746 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2747 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2748 // schedule such alarms.
2749 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2750 long minTime = lastTime + mAllowWhileIdleMinTime;
2751 if (nowELAPSED < minTime) {
2752 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2753 // alarm went off for this app. Reschedule the alarm to be in the
2754 // correct time period.
2755 alarm.whenElapsed = minTime;
2756 if (alarm.maxWhenElapsed < minTime) {
2757 alarm.maxWhenElapsed = minTime;
2758 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002759 if (RECORD_DEVICE_IDLE_ALARMS) {
2760 IdleDispatchEntry ent = new IdleDispatchEntry();
2761 ent.uid = alarm.uid;
2762 ent.pkg = alarm.operation.getCreatorPackage();
2763 ent.tag = alarm.operation.getTag("");
2764 ent.op = "RESCHEDULE";
2765 ent.elapsedRealtime = nowELAPSED;
2766 ent.argRealtime = lastTime;
2767 mAllowWhileIdleDispatches.add(ent);
2768 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002769 setImplLocked(alarm, true, false);
2770 continue;
2771 }
2772 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002773 if (isBackgroundRestricted(alarm)) {
2774 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2775 if (DEBUG_BG_LIMIT) {
2776 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2777 }
2778 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2779 if (alarmsForUid == null) {
2780 alarmsForUid = new ArrayList<>();
2781 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2782 }
2783 alarmsForUid.add(alarm);
2784 continue;
2785 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002786
Christopher Tatee0a22b32013-07-11 14:43:13 -07002787 alarm.count = 1;
2788 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002789 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2790 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002791 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002792 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002793 if (mPendingIdleUntil == alarm) {
2794 mPendingIdleUntil = null;
2795 rebatchAllAlarmsLocked(false);
2796 restorePendingWhileIdleAlarmsLocked();
2797 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002798 if (mNextWakeFromIdle == alarm) {
2799 mNextWakeFromIdle = null;
2800 rebatchAllAlarmsLocked(false);
2801 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002802
2803 // Recurring alarms may have passed several alarm intervals while the
2804 // phone was asleep or off, so pass a trigger count when sending them.
2805 if (alarm.repeatInterval > 0) {
2806 // this adjustment will be zero if we're late by
2807 // less than one full repeat interval
2808 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2809
2810 // Also schedule its next recurrence
2811 final long delta = alarm.count * alarm.repeatInterval;
2812 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002813 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002814 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002815 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2816 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002817 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002818
Christopher Tate864d42e2014-12-02 11:48:53 -08002819 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002820 hasWakeup = true;
2821 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002822
2823 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2824 if (alarm.alarmClock != null) {
2825 mNextAlarmClockMayChange = true;
2826 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002828 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002829
Christopher Tate1590f1e2014-10-02 17:27:57 -07002830 // This is a new alarm delivery set; bump the sequence number to indicate that
2831 // all apps' alarm delivery classes should be recalculated.
2832 mCurrentSeq++;
2833 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002834 Collections.sort(triggerList, mAlarmDispatchComparator);
2835
2836 if (localLOGV) {
2837 for (int i=0; i<triggerList.size(); i++) {
2838 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2839 }
2840 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002841
2842 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002843 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002845 /**
2846 * This Comparator sorts Alarms into increasing time order.
2847 */
2848 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2849 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002850 long when1 = a1.whenElapsed;
2851 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002852 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002853 return 1;
2854 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002855 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 return -1;
2857 }
2858 return 0;
2859 }
2860 }
Kweku Adams61e03292017-10-19 14:27:12 -07002861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002862 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002863 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002864 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002865 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002866 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002867 public final IAlarmListener listener;
2868 public final String listenerTag;
2869 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002870 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002871 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002872 public final AlarmManager.AlarmClockInfo alarmClock;
2873 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002874 public final int creatorUid;
2875 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002876 public int count;
2877 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002878 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002879 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002880 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002881 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002882 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002883
Christopher Tate3e04b472013-10-21 17:51:31 -07002884 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002885 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2886 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2887 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002888 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002889 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002890 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2891 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002892 when = _when;
2893 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002894 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002895 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002896 repeatInterval = _interval;
2897 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002898 listener = _rec;
2899 listenerTag = _listenerTag;
2900 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002901 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002902 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002903 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002904 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002905 packageName = _pkgName;
2906
2907 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002908 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002909
Christopher Tate14a7bb02015-10-01 10:24:31 -07002910 public static String makeTag(PendingIntent pi, String tag, int type) {
2911 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2912 ? "*walarm*:" : "*alarm*:";
2913 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2914 }
2915
2916 public WakeupEvent makeWakeupEvent(long nowRTC) {
2917 return new WakeupEvent(nowRTC, creatorUid,
2918 (operation != null)
2919 ? operation.getIntent().getAction()
2920 : ("<listener>:" + listenerTag));
2921 }
2922
2923 // Returns true if either matches
2924 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2925 return (operation != null)
2926 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002927 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002928 }
2929
2930 public boolean matches(String packageName) {
2931 return (operation != null)
2932 ? packageName.equals(operation.getTargetPackage())
2933 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002934 }
2935
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002936 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002937 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002938 StringBuilder sb = new StringBuilder(128);
2939 sb.append("Alarm{");
2940 sb.append(Integer.toHexString(System.identityHashCode(this)));
2941 sb.append(" type ");
2942 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002943 sb.append(" when ");
2944 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002945 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002946 if (operation != null) {
2947 sb.append(operation.getTargetPackage());
2948 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002949 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002950 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002951 sb.append('}');
2952 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002953 }
2954
Kweku Adams61e03292017-10-19 14:27:12 -07002955 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002956 SimpleDateFormat sdf) {
2957 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002958 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002959 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002960 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2961 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002962 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002963 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002964 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002965 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002966 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002967 }
2968 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002969 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002970 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002971 pw.print(" count="); pw.print(count);
2972 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002973 if (alarmClock != null) {
2974 pw.print(prefix); pw.println("Alarm clock:");
2975 pw.print(prefix); pw.print(" triggerTime=");
2976 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2977 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2978 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002979 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002980 if (listener != null) {
2981 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002983 }
Kweku Adams61e03292017-10-19 14:27:12 -07002984
2985 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
2986 long nowRTC) {
2987 final long token = proto.start(fieldId);
2988
2989 proto.write(AlarmProto.TAG, statsTag);
2990 proto.write(AlarmProto.TYPE, type);
2991 proto.write(AlarmProto.WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
2992 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
2993 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
2994 proto.write(AlarmProto.COUNT, count);
2995 proto.write(AlarmProto.FLAGS, flags);
2996 if (alarmClock != null) {
2997 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
2998 }
2999 if (operation != null) {
3000 operation.writeToProto(proto, AlarmProto.OPERATION);
3001 }
3002 if (listener != null) {
3003 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3004 }
3005
3006 proto.end(token);
3007 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003008 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003009
Christopher Tatee0a22b32013-07-11 14:43:13 -07003010 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3011 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003012 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3013 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003014 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003015 break;
3016 }
3017
Christopher Tatee0a22b32013-07-11 14:43:13 -07003018 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003019 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3020 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003021 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003022 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003023 }
3024 }
3025
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003026 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3027 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3028 if (timeSinceOn < 5*60*1000) {
3029 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3030 return 2*60*1000;
3031 } else if (timeSinceOn < 30*60*1000) {
3032 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3033 return 15*60*1000;
3034 } else {
3035 // Otherwise, we will delay by at most an hour.
3036 return 60*60*1000;
3037 }
3038 }
3039
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003040 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003041 if (duration < 15*60*1000) {
3042 // If the duration until the time is less than 15 minutes, the maximum fuzz
3043 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003044 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003045 } else if (duration < 90*60*1000) {
3046 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3047 return 15*60*1000;
3048 } else {
3049 // Otherwise, we will fuzz by at most half an hour.
3050 return 30*60*1000;
3051 }
3052 }
3053
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003054 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3055 if (mInteractive) {
3056 return false;
3057 }
3058 if (mLastAlarmDeliveryTime <= 0) {
3059 return false;
3060 }
minho.choo649acab2014-12-12 16:13:55 +09003061 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003062 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3063 // and the next delivery time is in the past, then just deliver them all. This
3064 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3065 return false;
3066 }
3067 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3068 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3069 }
3070
3071 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3072 mLastAlarmDeliveryTime = nowELAPSED;
3073 for (int i=0; i<triggerList.size(); i++) {
3074 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003075 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003076 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003077 if (localLOGV) {
3078 Slog.v(TAG, "sending alarm " + alarm);
3079 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003080 if (RECORD_ALARMS_IN_HISTORY) {
3081 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3082 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003083 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003084 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003085 }
3086 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003087 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003088 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003089 }
3090 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003091 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003092 } catch (RuntimeException e) {
3093 Slog.w(TAG, "Failure sending alarm.", e);
3094 }
3095 }
3096 }
3097
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003098 private class AlarmThread extends Thread
3099 {
3100 public AlarmThread()
3101 {
3102 super("AlarmManager");
3103 }
Kweku Adams61e03292017-10-19 14:27:12 -07003104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 public void run()
3106 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003107 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3108
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003109 while (true)
3110 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003111 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003112 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003113
3114 triggerList.clear();
3115
Dianne Hackbornc3527222015-05-13 14:03:20 -07003116 final long nowRTC = System.currentTimeMillis();
3117 final long nowELAPSED = SystemClock.elapsedRealtime();
3118
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003119 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003120 // The kernel can give us spurious time change notifications due to
3121 // small adjustments it makes internally; we want to filter those out.
3122 final long lastTimeChangeClockTime;
3123 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003124 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003125 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3126 expectedClockTime = lastTimeChangeClockTime
3127 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003128 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003129 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3130 || nowRTC > (expectedClockTime+1000)) {
3131 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003132 // let's do it!
3133 if (DEBUG_BATCH) {
3134 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3135 }
3136 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003137 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003138 rebatchAllAlarms();
3139 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003140 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003141 synchronized (mLock) {
3142 mNumTimeChanged++;
3143 mLastTimeChangeClockTime = nowRTC;
3144 mLastTimeChangeRealtime = nowELAPSED;
3145 }
3146 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3147 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003148 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003149 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3150 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003151 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3152
3153 // The world has changed on us, so we need to re-evaluate alarms
3154 // regardless of whether the kernel has told us one went off.
3155 result |= IS_WAKEUP_MASK;
3156 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003157 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003158
Dianne Hackbornc3527222015-05-13 14:03:20 -07003159 if (result != TIME_CHANGED_MASK) {
3160 // If this was anything besides just a time change, then figure what if
3161 // anything to do about alarms.
3162 synchronized (mLock) {
3163 if (localLOGV) Slog.v(
3164 TAG, "Checking for alarms... rtc=" + nowRTC
3165 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003166
Dianne Hackbornc3527222015-05-13 14:03:20 -07003167 if (WAKEUP_STATS) {
3168 if ((result & IS_WAKEUP_MASK) != 0) {
3169 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3170 int n = 0;
3171 for (WakeupEvent event : mRecentWakeups) {
3172 if (event.when > newEarliest) break;
3173 n++; // number of now-stale entries at the list head
3174 }
3175 for (int i = 0; i < n; i++) {
3176 mRecentWakeups.remove();
3177 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003178
Dianne Hackbornc3527222015-05-13 14:03:20 -07003179 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003180 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003181 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003182
3183 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3184 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3185 // if there are no wakeup alarms and the screen is off, we can
3186 // delay what we have so far until the future.
3187 if (mPendingNonWakeupAlarms.size() == 0) {
3188 mStartCurrentDelayTime = nowELAPSED;
3189 mNextNonWakeupDeliveryTime = nowELAPSED
3190 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3191 }
3192 mPendingNonWakeupAlarms.addAll(triggerList);
3193 mNumDelayedAlarms += triggerList.size();
3194 rescheduleKernelAlarmsLocked();
3195 updateNextAlarmClockLocked();
3196 } else {
3197 // now deliver the alarm intents; if there are pending non-wakeup
3198 // alarms, we need to merge them in to the list. note we don't
3199 // just deliver them first because we generally want non-wakeup
3200 // alarms delivered after wakeup alarms.
3201 rescheduleKernelAlarmsLocked();
3202 updateNextAlarmClockLocked();
3203 if (mPendingNonWakeupAlarms.size() > 0) {
3204 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3205 triggerList.addAll(mPendingNonWakeupAlarms);
3206 Collections.sort(triggerList, mAlarmDispatchComparator);
3207 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3208 mTotalDelayTime += thisDelayTime;
3209 if (mMaxDelayTime < thisDelayTime) {
3210 mMaxDelayTime = thisDelayTime;
3211 }
3212 mPendingNonWakeupAlarms.clear();
3213 }
3214 deliverAlarmsLocked(triggerList, nowELAPSED);
3215 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003216 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003217
3218 } else {
3219 // Just in case -- even though no wakeup flag was set, make sure
3220 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003221 synchronized (mLock) {
3222 rescheduleKernelAlarmsLocked();
3223 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003224 }
3225 }
3226 }
3227 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003228
David Christieebe51fc2013-07-26 13:23:29 -07003229 /**
3230 * Attribute blame for a WakeLock.
3231 * @param pi PendingIntent to attribute blame to if ws is null.
3232 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003233 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003234 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003235 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003236 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003237 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003238 final boolean unimportant = pi == mTimeTickSender;
3239 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003240 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003241 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003242 } else {
3243 mWakeLock.setHistoryTag(null);
3244 }
3245 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003246 if (ws != null) {
3247 mWakeLock.setWorkSource(ws);
3248 return;
3249 }
3250
Christopher Tate14a7bb02015-10-01 10:24:31 -07003251 final int uid = (knownUid >= 0)
3252 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003253 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003254 if (uid >= 0) {
3255 mWakeLock.setWorkSource(new WorkSource(uid));
3256 return;
3257 }
3258 } catch (Exception e) {
3259 }
3260
3261 // Something went wrong; fall back to attributing the lock to the OS
3262 mWakeLock.setWorkSource(null);
3263 }
3264
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003265 private class AlarmHandler extends Handler {
3266 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003267 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3268 public static final int LISTENER_TIMEOUT = 3;
3269 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003271 public AlarmHandler() {
3272 }
Kweku Adams61e03292017-10-19 14:27:12 -07003273
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003274 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003275 switch (msg.what) {
3276 case ALARM_EVENT: {
3277 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3278 synchronized (mLock) {
3279 final long nowRTC = System.currentTimeMillis();
3280 final long nowELAPSED = SystemClock.elapsedRealtime();
3281 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3282 updateNextAlarmClockLocked();
3283 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003284
Christopher Tate14a7bb02015-10-01 10:24:31 -07003285 // now trigger the alarms without the lock held
3286 for (int i=0; i<triggerList.size(); i++) {
3287 Alarm alarm = triggerList.get(i);
3288 try {
3289 alarm.operation.send();
3290 } catch (PendingIntent.CanceledException e) {
3291 if (alarm.repeatInterval > 0) {
3292 // This IntentSender is no longer valid, but this
3293 // is a repeating alarm, so toss the hoser.
3294 removeImpl(alarm.operation);
3295 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003296 }
3297 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003298 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003299 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003300
3301 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3302 sendNextAlarmClockChanged();
3303 break;
3304
3305 case LISTENER_TIMEOUT:
3306 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3307 break;
3308
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003309 case REPORT_ALARMS_ACTIVE:
3310 if (mLocalDeviceIdleController != null) {
3311 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3312 }
3313 break;
3314
Christopher Tate14a7bb02015-10-01 10:24:31 -07003315 default:
3316 // nope, just ignore it
3317 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003318 }
3319 }
3320 }
Kweku Adams61e03292017-10-19 14:27:12 -07003321
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003322 class ClockReceiver extends BroadcastReceiver {
3323 public ClockReceiver() {
3324 IntentFilter filter = new IntentFilter();
3325 filter.addAction(Intent.ACTION_TIME_TICK);
3326 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003327 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003328 }
Kweku Adams61e03292017-10-19 14:27:12 -07003329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003330 @Override
3331 public void onReceive(Context context, Intent intent) {
3332 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003333 if (DEBUG_BATCH) {
3334 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3335 }
3336 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3338 // Since the kernel does not keep track of DST, we need to
3339 // reset the TZ information at the beginning of each day
3340 // based off of the current Zone gmt offset + userspace tracked
3341 // daylight savings information.
3342 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003343 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003344 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003345 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003346 }
3347 }
Kweku Adams61e03292017-10-19 14:27:12 -07003348
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003349 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003350 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003351 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003352
3353 // Schedule this event for the amount of time that it would take to get to
3354 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003355 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003356
David Christieebe51fc2013-07-26 13:23:29 -07003357 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003358 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003359 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3360 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003361 }
Christopher Tate385e4982013-07-23 18:22:29 -07003362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003363 public void scheduleDateChangedEvent() {
3364 Calendar calendar = Calendar.getInstance();
3365 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003366 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003367 calendar.set(Calendar.MINUTE, 0);
3368 calendar.set(Calendar.SECOND, 0);
3369 calendar.set(Calendar.MILLISECOND, 0);
3370 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003371
3372 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003373 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3374 AlarmManager.FLAG_STANDALONE, workSource, null,
3375 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003376 }
3377 }
Kweku Adams61e03292017-10-19 14:27:12 -07003378
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003379 class InteractiveStateReceiver extends BroadcastReceiver {
3380 public InteractiveStateReceiver() {
3381 IntentFilter filter = new IntentFilter();
3382 filter.addAction(Intent.ACTION_SCREEN_OFF);
3383 filter.addAction(Intent.ACTION_SCREEN_ON);
3384 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3385 getContext().registerReceiver(this, filter);
3386 }
3387
3388 @Override
3389 public void onReceive(Context context, Intent intent) {
3390 synchronized (mLock) {
3391 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3392 }
3393 }
3394 }
3395
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003396 class UninstallReceiver extends BroadcastReceiver {
3397 public UninstallReceiver() {
3398 IntentFilter filter = new IntentFilter();
3399 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3400 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003401 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003402 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003403 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003404 // Register for events related to sdcard installation.
3405 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003406 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003407 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003408 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003409 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003410 }
Kweku Adams61e03292017-10-19 14:27:12 -07003411
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003412 @Override
3413 public void onReceive(Context context, Intent intent) {
3414 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003415 String action = intent.getAction();
3416 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003417 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3418 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3419 for (String packageName : pkgList) {
3420 if (lookForPackageLocked(packageName)) {
3421 setResultCode(Activity.RESULT_OK);
3422 return;
3423 }
3424 }
3425 return;
3426 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003427 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003428 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3429 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3430 if (userHandle >= 0) {
3431 removeUserLocked(userHandle);
3432 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003433 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
3434 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
3435 if (uid >= 0) {
3436 mLastAllowWhileIdleDispatch.delete(uid);
3437 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003438 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003439 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3440 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3441 // This package is being updated; don't kill its alarms.
3442 return;
3443 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003444 Uri data = intent.getData();
3445 if (data != null) {
3446 String pkg = data.getSchemeSpecificPart();
3447 if (pkg != null) {
3448 pkgList = new String[]{pkg};
3449 }
3450 }
3451 }
3452 if (pkgList != null && (pkgList.length > 0)) {
3453 for (String pkg : pkgList) {
3454 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07003455 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003456 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3457 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3458 if (uidStats.remove(pkg) != null) {
3459 if (uidStats.size() <= 0) {
3460 mBroadcastStats.removeAt(i);
3461 }
3462 }
3463 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003464 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003465 }
3466 }
3467 }
3468 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003469
3470 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003471 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003472 }
3473
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003474 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003475 synchronized (mLock) {
3476 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003477 removeForStoppedLocked(uid);
3478 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003479 mForegroundUids.delete(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003480 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003481 }
3482
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003483 @Override public void onUidActive(int uid) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003484 synchronized (mLock) {
3485 if (!mForegroundUids.get(uid)) {
3486 mForegroundUids.put(uid, true);
3487 sendPendingBackgroundAlarmsLocked(uid, null);
3488 }
3489 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003490 }
3491
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003492 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003493 synchronized (mLock) {
3494 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003495 removeForStoppedLocked(uid);
3496 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003497 mForegroundUids.delete(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003498 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003499 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003500
3501 @Override public void onUidCachedChanged(int uid, boolean cached) {
3502 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003503 };
3504
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003505 private final class AppOpsWatcher extends IAppOpsCallback.Stub {
3506 @Override
3507 public void opChanged(int op, int uid, String packageName) throws RemoteException {
3508 synchronized (mLock) {
3509 final int mode = mAppOpsService.checkOperation(op, uid, packageName);
3510 if (DEBUG_BG_LIMIT) {
3511 Slog.d(TAG,
3512 "Appop changed for " + uid + ", " + packageName + " to " + mode);
3513 }
3514 final boolean changed;
3515 if (mode != AppOpsManager.MODE_ALLOWED) {
3516 changed = mForcedAppStandbyPackages.add(packageName);
3517 } else {
3518 changed = mForcedAppStandbyPackages.remove(packageName);
3519 }
3520 if (changed && mode == AppOpsManager.MODE_ALLOWED) {
3521 sendPendingBackgroundAlarmsLocked(uid, packageName);
3522 }
3523 }
3524 }
3525 }
3526
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003527 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003528 String pkg = pi.getCreatorPackage();
3529 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003530 return getStatsLocked(uid, pkg);
3531 }
3532
3533 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003534 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3535 if (uidStats == null) {
3536 uidStats = new ArrayMap<String, BroadcastStats>();
3537 mBroadcastStats.put(uid, uidStats);
3538 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003539 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003540 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003541 bs = new BroadcastStats(uid, pkgName);
3542 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003543 }
3544 return bs;
3545 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003546
Christopher Tate21e9f192017-08-08 13:49:11 -07003547 /**
3548 * Canonical count of (operation.send() - onSendFinished()) and
3549 * listener send/complete/timeout invocations.
3550 * Guarded by the usual lock.
3551 */
3552 @GuardedBy("mLock")
3553 private int mSendCount = 0;
3554 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003555 private int mSendFinishCount = 0;
3556 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003557 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003558 @GuardedBy("mLock")
3559 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003560
Christopher Tate14a7bb02015-10-01 10:24:31 -07003561 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003562
Christopher Tate14a7bb02015-10-01 10:24:31 -07003563 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3564 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003565 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003566 return mInFlight.remove(i);
3567 }
3568 }
3569 mLog.w("No in-flight alarm for " + pi + " " + intent);
3570 return null;
3571 }
3572
3573 private InFlight removeLocked(IBinder listener) {
3574 for (int i = 0; i < mInFlight.size(); i++) {
3575 if (mInFlight.get(i).mListener == listener) {
3576 return mInFlight.remove(i);
3577 }
3578 }
3579 mLog.w("No in-flight alarm for listener " + listener);
3580 return null;
3581 }
3582
3583 private void updateStatsLocked(InFlight inflight) {
3584 final long nowELAPSED = SystemClock.elapsedRealtime();
3585 BroadcastStats bs = inflight.mBroadcastStats;
3586 bs.nesting--;
3587 if (bs.nesting <= 0) {
3588 bs.nesting = 0;
3589 bs.aggregateTime += nowELAPSED - bs.startTime;
3590 }
3591 FilterStats fs = inflight.mFilterStats;
3592 fs.nesting--;
3593 if (fs.nesting <= 0) {
3594 fs.nesting = 0;
3595 fs.aggregateTime += nowELAPSED - fs.startTime;
3596 }
3597 if (RECORD_ALARMS_IN_HISTORY) {
3598 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
3599 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003600 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003601 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
3602 }
3603 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003604 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003605 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
3606 }
3607 }
3608 }
3609
3610 private void updateTrackingLocked(InFlight inflight) {
3611 if (inflight != null) {
3612 updateStatsLocked(inflight);
3613 }
3614 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003615 if (DEBUG_WAKELOCK) {
3616 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3617 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003618 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003619 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003620 mWakeLock.release();
3621 if (mInFlight.size() > 0) {
3622 mLog.w("Finished all dispatches with " + mInFlight.size()
3623 + " remaining inflights");
3624 for (int i=0; i<mInFlight.size(); i++) {
3625 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3626 }
3627 mInFlight.clear();
3628 }
3629 } else {
3630 // the next of our alarms is now in flight. reattribute the wakelock.
3631 if (mInFlight.size() > 0) {
3632 InFlight inFlight = mInFlight.get(0);
3633 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3634 inFlight.mAlarmType, inFlight.mTag, -1, false);
3635 } else {
3636 // should never happen
3637 mLog.w("Alarm wakelock still held but sent queue empty");
3638 mWakeLock.setWorkSource(null);
3639 }
3640 }
3641 }
3642
3643 /**
3644 * Callback that arrives when a direct-call alarm reports that delivery has finished
3645 */
3646 @Override
3647 public void alarmComplete(IBinder who) {
3648 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003649 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003650 + " pid=" + Binder.getCallingPid());
3651 return;
3652 }
3653
3654 final long ident = Binder.clearCallingIdentity();
3655 try {
3656 synchronized (mLock) {
3657 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3658 InFlight inflight = removeLocked(who);
3659 if (inflight != null) {
3660 if (DEBUG_LISTENER_CALLBACK) {
3661 Slog.i(TAG, "alarmComplete() from " + who);
3662 }
3663 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003664 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003665 } else {
3666 // Delivery timed out, and the timeout handling already took care of
3667 // updating our tracking here, so we needn't do anything further.
3668 if (DEBUG_LISTENER_CALLBACK) {
3669 Slog.i(TAG, "Late alarmComplete() from " + who);
3670 }
3671 }
3672 }
3673 } finally {
3674 Binder.restoreCallingIdentity(ident);
3675 }
3676 }
3677
3678 /**
3679 * Callback that arrives when a PendingIntent alarm has finished delivery
3680 */
3681 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003682 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3683 String resultData, Bundle resultExtras) {
3684 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003685 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003686 updateTrackingLocked(removeLocked(pi, intent));
3687 }
3688 }
3689
3690 /**
3691 * Timeout of a direct-call alarm delivery
3692 */
3693 public void alarmTimedOut(IBinder who) {
3694 synchronized (mLock) {
3695 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003696 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003697 // TODO: implement ANR policy for the target
3698 if (DEBUG_LISTENER_CALLBACK) {
3699 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003700 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003701 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003702 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003703 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003704 if (DEBUG_LISTENER_CALLBACK) {
3705 Slog.i(TAG, "Spurious timeout of listener " + who);
3706 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003707 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003708 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003709 }
3710 }
3711
3712 /**
3713 * Deliver an alarm and set up the post-delivery handling appropriately
3714 */
3715 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3716 if (alarm.operation != null) {
3717 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003718 mSendCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003719 try {
3720 alarm.operation.send(getContext(), 0,
3721 mBackgroundIntent.putExtra(
3722 Intent.EXTRA_ALARM_COUNT, alarm.count),
3723 mDeliveryTracker, mHandler, null,
3724 allowWhileIdle ? mIdleOptions : null);
3725 } catch (PendingIntent.CanceledException e) {
3726 if (alarm.repeatInterval > 0) {
3727 // This IntentSender is no longer valid, but this
3728 // is a repeating alarm, so toss it
3729 removeImpl(alarm.operation);
3730 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003731 // No actual delivery was possible, so the delivery tracker's
3732 // 'finished' callback won't be invoked. We also don't need
3733 // to do any wakelock or stats tracking, so we have nothing
3734 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003735 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003736 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003737 }
3738 } else {
3739 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003740 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003741 try {
3742 if (DEBUG_LISTENER_CALLBACK) {
3743 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3744 + " listener=" + alarm.listener.asBinder());
3745 }
3746 alarm.listener.doAlarm(this);
3747 mHandler.sendMessageDelayed(
3748 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3749 alarm.listener.asBinder()),
3750 mConstants.LISTENER_TIMEOUT);
3751 } catch (Exception e) {
3752 if (DEBUG_LISTENER_CALLBACK) {
3753 Slog.i(TAG, "Alarm undeliverable to listener "
3754 + alarm.listener.asBinder(), e);
3755 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003756 // As in the PendingIntent.CanceledException case, delivery of the
3757 // alarm was not possible, so we have no wakelock or timeout or
3758 // stats management to do. It threw before we posted the delayed
3759 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003760 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003761 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003762 }
3763 }
3764
3765 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003766 if (DEBUG_WAKELOCK) {
3767 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3768 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003769 if (mBroadcastRefCount == 0) {
3770 setWakelockWorkSource(alarm.operation, alarm.workSource,
3771 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3772 true);
3773 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003774 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003775 }
3776 final InFlight inflight = new InFlight(AlarmManagerService.this,
3777 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3778 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3779 mInFlight.add(inflight);
3780 mBroadcastRefCount++;
3781
3782 if (allowWhileIdle) {
3783 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3784 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3785 if (RECORD_DEVICE_IDLE_ALARMS) {
3786 IdleDispatchEntry ent = new IdleDispatchEntry();
3787 ent.uid = alarm.uid;
3788 ent.pkg = alarm.packageName;
3789 ent.tag = alarm.statsTag;
3790 ent.op = "DELIVER";
3791 ent.elapsedRealtime = nowELAPSED;
3792 mAllowWhileIdleDispatches.add(ent);
3793 }
3794 }
3795
3796 final BroadcastStats bs = inflight.mBroadcastStats;
3797 bs.count++;
3798 if (bs.nesting == 0) {
3799 bs.nesting = 1;
3800 bs.startTime = nowELAPSED;
3801 } else {
3802 bs.nesting++;
3803 }
3804 final FilterStats fs = inflight.mFilterStats;
3805 fs.count++;
3806 if (fs.nesting == 0) {
3807 fs.nesting = 1;
3808 fs.startTime = nowELAPSED;
3809 } else {
3810 fs.nesting++;
3811 }
3812 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3813 || alarm.type == RTC_WAKEUP) {
3814 bs.numWakeup++;
3815 fs.numWakeup++;
3816 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3817 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003818 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003819 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003820 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003821 (wsName != null) ? wsName : alarm.packageName,
3822 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003823 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003824 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003825 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003826 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003827 }
3828 }
3829 }
3830 }
3831}