blob: ab252a43814ac13de71509d3facf7b3d154291a1 [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;
Tim Murray175c0f92017-11-28 15:01:04 -080052import android.os.Trace;
Dianne Hackborn80a4af22012-08-27 19:18:31 -070053import android.os.UserHandle;
Christopher Tatec4a07d12012-04-06 14:19:13 -070054import android.os.WorkSource;
Adrian Roosc42a1e12014-07-07 23:35:53 +020055import android.provider.Settings;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.text.TextUtils;
Adrian Roosc42a1e12014-07-07 23:35:53 +020057import android.text.format.DateFormat;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080058import android.util.ArrayMap;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070059import android.util.ArraySet;
Dianne Hackborna750a632015-06-16 17:18:23 -070060import android.util.KeyValueListParser;
Adrian Roosc42a1e12014-07-07 23:35:53 +020061import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -080062import android.util.Slog;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -080063import android.util.SparseArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +020064import android.util.SparseBooleanArray;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -070065import android.util.SparseLongArray;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070066import android.util.TimeUtils;
Kweku Adams61e03292017-10-19 14:27:12 -070067import android.util.proto.ProtoOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068
Christopher Tate4cb338d2013-07-26 13:11:31 -070069import java.io.ByteArrayOutputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import java.io.FileDescriptor;
71import java.io.PrintWriter;
Dianne Hackborn043fcd92010-10-06 14:27:34 -070072import java.text.SimpleDateFormat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073import java.util.ArrayList;
Dianne Hackborn81038902012-11-26 17:04:09 -080074import java.util.Arrays;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import java.util.Calendar;
76import java.util.Collections;
77import java.util.Comparator;
Mike Lockwood1f7b4132009-11-20 15:12:51 -050078import java.util.Date;
Christopher Tate1590f1e2014-10-02 17:27:57 -070079import java.util.HashMap;
Christopher Tate18a75f12013-07-01 18:18:59 -070080import java.util.LinkedList;
Adrian Roosc42a1e12014-07-07 23:35:53 +020081import java.util.Locale;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -070082import java.util.Random;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import java.util.TimeZone;
John Spurlock604a5ee2015-06-01 12:27:22 -040084import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085
Christopher Tatee0a22b32013-07-11 14:43:13 -070086import static android.app.AlarmManager.RTC_WAKEUP;
87import static android.app.AlarmManager.RTC;
88import static android.app.AlarmManager.ELAPSED_REALTIME_WAKEUP;
89import static android.app.AlarmManager.ELAPSED_REALTIME;
90
Christopher Tate21e9f192017-08-08 13:49:11 -070091import com.android.internal.annotations.GuardedBy;
Suprabh Shukladb6bf662017-08-30 15:41:53 -070092import com.android.internal.app.IAppOpsCallback;
93import com.android.internal.app.IAppOpsService;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -060094import com.android.internal.util.DumpUtils;
Dianne Hackborn81038902012-11-26 17:04:09 -080095import com.android.internal.util.LocalLog;
96
Adam Lesinski182f73f2013-12-05 16:48:06 -080097class AlarmManagerService extends SystemService {
Christopher Tatee0a22b32013-07-11 14:43:13 -070098 private static final int RTC_WAKEUP_MASK = 1 << RTC_WAKEUP;
99 private static final int RTC_MASK = 1 << RTC;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800100 private static final int ELAPSED_REALTIME_WAKEUP_MASK = 1 << ELAPSED_REALTIME_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700101 private static final int ELAPSED_REALTIME_MASK = 1 << ELAPSED_REALTIME;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800102 static final int TIME_CHANGED_MASK = 1 << 16;
103 static final int IS_WAKEUP_MASK = RTC_WAKEUP_MASK|ELAPSED_REALTIME_WAKEUP_MASK;
Christopher Tateb8849c12011-02-08 13:39:01 -0800104
Christopher Tatee0a22b32013-07-11 14:43:13 -0700105 // Mask for testing whether a given alarm type is wakeup vs non-wakeup
Adam Lesinski182f73f2013-12-05 16:48:06 -0800106 static final int TYPE_NONWAKEUP_MASK = 0x1; // low bit => non-wakeup
Christopher Tateb8849c12011-02-08 13:39:01 -0800107
Adam Lesinski182f73f2013-12-05 16:48:06 -0800108 static final String TAG = "AlarmManager";
Adam Lesinski182f73f2013-12-05 16:48:06 -0800109 static final boolean localLOGV = false;
110 static final boolean DEBUG_BATCH = localLOGV || false;
111 static final boolean DEBUG_VALIDATE = localLOGV || false;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200112 static final boolean DEBUG_ALARM_CLOCK = localLOGV || false;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700113 static final boolean DEBUG_LISTENER_CALLBACK = localLOGV || false;
Makoto Onuki3e7d8452017-03-02 15:33:17 -0800114 static final boolean DEBUG_WAKELOCK = localLOGV || false;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700115 static final boolean DEBUG_BG_LIMIT = localLOGV || false;
Dianne Hackborn1e383822015-04-10 14:02:33 -0700116 static final boolean RECORD_ALARMS_IN_HISTORY = true;
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700117 static final boolean RECORD_DEVICE_IDLE_ALARMS = false;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800118 static final int ALARM_EVENT = 1;
119 static final String TIMEZONE_PROPERTY = "persist.sys.timezone";
Adrian Roosc42a1e12014-07-07 23:35:53 +0200120
Christopher Tate14a7bb02015-10-01 10:24:31 -0700121 private final Intent mBackgroundIntent
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800122 = new Intent().addFlags(Intent.FLAG_FROM_BACKGROUND);
Adam Lesinski182f73f2013-12-05 16:48:06 -0800123 static final IncreasingTimeOrder sIncreasingTimeOrder = new IncreasingTimeOrder();
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700124
Adam Lesinski182f73f2013-12-05 16:48:06 -0800125 static final boolean WAKEUP_STATS = false;
Christopher Tate18a75f12013-07-01 18:18:59 -0700126
Christopher Tate24cd46f2016-02-02 14:28:01 -0800127 private static final Intent NEXT_ALARM_CLOCK_CHANGED_INTENT =
128 new Intent(AlarmManager.ACTION_NEXT_ALARM_CLOCK_CHANGED)
Christopher Tate50191db2017-05-09 16:02:25 -0700129 .addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
130 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
Adrian Roosc42a1e12014-07-07 23:35:53 +0200131
Adam Lesinski182f73f2013-12-05 16:48:06 -0800132 final LocalLog mLog = new LocalLog(TAG);
Dianne Hackborn81038902012-11-26 17:04:09 -0800133
Christopher Tate14a7bb02015-10-01 10:24:31 -0700134 AppOpsManager mAppOps;
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700135 IAppOpsService mAppOpsService;
Dianne Hackborn627dfa12015-11-11 18:10:30 -0800136 DeviceIdleController.LocalService mLocalDeviceIdleController;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700137
Adam Lesinski182f73f2013-12-05 16:48:06 -0800138 final Object mLock = new Object();
Dianne Hackborn81038902012-11-26 17:04:09 -0800139
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700140 ArraySet<String> mForcedAppStandbyPackages = new ArraySet<>();
141 SparseBooleanArray mForegroundUids = new SparseBooleanArray();
142 // List of alarms per uid deferred due to user applied background restrictions on the source app
143 SparseArray<ArrayList<Alarm>> mPendingBackgroundAlarms = new SparseArray<>();
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -0800144 long mNativeData;
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800145 private long mNextWakeup;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700146 private long mNextNonWakeup;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -0700147 private long mLastWakeupSet;
148 private long mLastWakeup;
Adam Lesinski182f73f2013-12-05 16:48:06 -0800149 int mBroadcastRefCount = 0;
150 PowerManager.WakeLock mWakeLock;
Dianne Hackborna1bd7922014-03-21 11:07:11 -0700151 boolean mLastWakeLockUnimportantForLogging;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700152 ArrayList<Alarm> mPendingNonWakeupAlarms = new ArrayList<>();
153 ArrayList<InFlight> mInFlight = new ArrayList<>();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800154 final AlarmHandler mHandler = new AlarmHandler();
155 ClockReceiver mClockReceiver;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700156 InteractiveStateReceiver mInteractiveStateReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157 private UninstallReceiver mUninstallReceiver;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700158 final DeliveryTracker mDeliveryTracker = new DeliveryTracker();
Adam Lesinski182f73f2013-12-05 16:48:06 -0800159 PendingIntent mTimeTickSender;
160 PendingIntent mDateChangeSender;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700161 Random mRandom;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -0700162 boolean mInteractive = true;
163 long mNonInteractiveStartTime;
164 long mNonInteractiveTime;
165 long mLastAlarmDeliveryTime;
166 long mStartCurrentDelayTime;
167 long mNextNonWakeupDeliveryTime;
Dianne Hackbornc3527222015-05-13 14:03:20 -0700168 long mLastTimeChangeClockTime;
169 long mLastTimeChangeRealtime;
Dianne Hackborna750a632015-06-16 17:18:23 -0700170 long mAllowWhileIdleMinTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -0700171 int mNumTimeChanged;
Dianne Hackborn81038902012-11-26 17:04:09 -0800172
Christopher Tatebb9cce52017-04-18 14:19:43 -0700173 // Bookkeeping about the identity of the "System UI" package, determined at runtime.
174
175 /**
176 * This permission must be defined by the canonical System UI package,
177 * with protection level "signature".
178 */
179 private static final String SYSTEM_UI_SELF_PERMISSION =
180 "android.permission.systemui.IDENTITY";
181
182 /**
183 * At boot we use SYSTEM_UI_SELF_PERMISSION to look up the definer's uid.
184 */
185 int mSystemUiUid;
186
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700187 /**
Dianne Hackborn262ae5c2016-02-10 16:28:29 -0800188 * The current set of user whitelisted apps for device idle mode, meaning these are allowed
189 * to freely schedule alarms.
190 */
191 int[] mDeviceIdleUserWhitelist = new int[0];
192
193 /**
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700194 * For each uid, this is the last time we dispatched an "allow while idle" alarm,
Kweku Adams61e03292017-10-19 14:27:12 -0700195 * used to determine the earliest we can dispatch the next such alarm. Times are in the
196 * 'elapsed' timebase.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700197 */
198 final SparseLongArray mLastAllowWhileIdleDispatch = new SparseLongArray();
199
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700200 final static class IdleDispatchEntry {
201 int uid;
202 String pkg;
203 String tag;
204 String op;
205 long elapsedRealtime;
206 long argRealtime;
207 }
208 final ArrayList<IdleDispatchEntry> mAllowWhileIdleDispatches = new ArrayList();
209
Dianne Hackborna750a632015-06-16 17:18:23 -0700210 /**
211 * Broadcast options to use for FLAG_ALLOW_WHILE_IDLE.
212 */
213 Bundle mIdleOptions;
214
Jose Lima235510e2014-08-13 12:50:01 -0700215 private final SparseArray<AlarmManager.AlarmClockInfo> mNextAlarmClockForUser =
216 new SparseArray<>();
217 private final SparseArray<AlarmManager.AlarmClockInfo> mTmpSparseAlarmClockArray =
218 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200219 private final SparseBooleanArray mPendingSendNextAlarmClockChangedForUser =
220 new SparseBooleanArray();
221 private boolean mNextAlarmClockMayChange;
222
223 // May only use on mHandler's thread, locking not required.
Jose Lima235510e2014-08-13 12:50:01 -0700224 private final SparseArray<AlarmManager.AlarmClockInfo> mHandlerSparseAlarmClockArray =
225 new SparseArray<>();
Adrian Roosc42a1e12014-07-07 23:35:53 +0200226
Dianne Hackborna750a632015-06-16 17:18:23 -0700227 /**
228 * All times are in milliseconds. These constants are kept synchronized with the system
229 * global Settings. Any access to this class or its fields should be done while
230 * holding the AlarmManagerService.mLock lock.
231 */
232 private final class Constants extends ContentObserver {
233 // Key names stored in the settings value.
234 private static final String KEY_MIN_FUTURITY = "min_futurity";
235 private static final String KEY_MIN_INTERVAL = "min_interval";
236 private static final String KEY_ALLOW_WHILE_IDLE_SHORT_TIME = "allow_while_idle_short_time";
237 private static final String KEY_ALLOW_WHILE_IDLE_LONG_TIME = "allow_while_idle_long_time";
238 private static final String KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION
239 = "allow_while_idle_whitelist_duration";
Christopher Tate14a7bb02015-10-01 10:24:31 -0700240 private static final String KEY_LISTENER_TIMEOUT = "listener_timeout";
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700241 private static final String KEY_BG_RESTRICTIONS_ENABLED = "limit_bg_alarms_enabled";
Dianne Hackborna750a632015-06-16 17:18:23 -0700242
243 private static final long DEFAULT_MIN_FUTURITY = 5 * 1000;
244 private static final long DEFAULT_MIN_INTERVAL = 60 * 1000;
Christopher Tateaa244da2015-08-27 15:57:57 -0700245 private static final long DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_MIN_FUTURITY;
Dianne Hackborn7682b262015-10-26 17:51:57 -0700246 private static final long DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME = 9*60*1000;
Dianne Hackborna750a632015-06-16 17:18:23 -0700247 private static final long DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION = 10*1000;
248
Christopher Tate14a7bb02015-10-01 10:24:31 -0700249 private static final long DEFAULT_LISTENER_TIMEOUT = 5 * 1000;
250
Dianne Hackborna750a632015-06-16 17:18:23 -0700251 // Minimum futurity of a new alarm
252 public long MIN_FUTURITY = DEFAULT_MIN_FUTURITY;
253
254 // Minimum alarm recurrence interval
255 public long MIN_INTERVAL = DEFAULT_MIN_INTERVAL;
256
257 // Minimum time between ALLOW_WHILE_IDLE alarms when system is not idle.
258 public long ALLOW_WHILE_IDLE_SHORT_TIME = DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME;
259
260 // Minimum time between ALLOW_WHILE_IDLE alarms when system is idling.
261 public long ALLOW_WHILE_IDLE_LONG_TIME = DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME;
262
263 // BroadcastOptions.setTemporaryAppWhitelistDuration() to use for FLAG_ALLOW_WHILE_IDLE.
264 public long ALLOW_WHILE_IDLE_WHITELIST_DURATION
265 = DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION;
266
Christopher Tate14a7bb02015-10-01 10:24:31 -0700267 // Direct alarm listener callback timeout
268 public long LISTENER_TIMEOUT = DEFAULT_LISTENER_TIMEOUT;
269
Dianne Hackborna750a632015-06-16 17:18:23 -0700270 private ContentResolver mResolver;
271 private final KeyValueListParser mParser = new KeyValueListParser(',');
272 private long mLastAllowWhileIdleWhitelistDuration = -1;
273
274 public Constants(Handler handler) {
275 super(handler);
276 updateAllowWhileIdleMinTimeLocked();
277 updateAllowWhileIdleWhitelistDurationLocked();
278 }
279
280 public void start(ContentResolver resolver) {
281 mResolver = resolver;
282 mResolver.registerContentObserver(Settings.Global.getUriFor(
283 Settings.Global.ALARM_MANAGER_CONSTANTS), false, this);
284 updateConstants();
285 }
286
287 public void updateAllowWhileIdleMinTimeLocked() {
288 mAllowWhileIdleMinTime = mPendingIdleUntil != null
289 ? ALLOW_WHILE_IDLE_LONG_TIME : ALLOW_WHILE_IDLE_SHORT_TIME;
290 }
291
292 public void updateAllowWhileIdleWhitelistDurationLocked() {
293 if (mLastAllowWhileIdleWhitelistDuration != ALLOW_WHILE_IDLE_WHITELIST_DURATION) {
294 mLastAllowWhileIdleWhitelistDuration = ALLOW_WHILE_IDLE_WHITELIST_DURATION;
295 BroadcastOptions opts = BroadcastOptions.makeBasic();
296 opts.setTemporaryAppWhitelistDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION);
297 mIdleOptions = opts.toBundle();
298 }
299 }
300
301 @Override
302 public void onChange(boolean selfChange, Uri uri) {
303 updateConstants();
304 }
305
306 private void updateConstants() {
307 synchronized (mLock) {
308 try {
309 mParser.setString(Settings.Global.getString(mResolver,
310 Settings.Global.ALARM_MANAGER_CONSTANTS));
311 } catch (IllegalArgumentException e) {
312 // Failed to parse the settings string, log this and move on
313 // with defaults.
Dianne Hackborn0ef403e2017-01-24 18:22:15 -0800314 Slog.e(TAG, "Bad alarm manager settings", e);
Dianne Hackborna750a632015-06-16 17:18:23 -0700315 }
316
317 MIN_FUTURITY = mParser.getLong(KEY_MIN_FUTURITY, DEFAULT_MIN_FUTURITY);
318 MIN_INTERVAL = mParser.getLong(KEY_MIN_INTERVAL, DEFAULT_MIN_INTERVAL);
319 ALLOW_WHILE_IDLE_SHORT_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_SHORT_TIME,
320 DEFAULT_ALLOW_WHILE_IDLE_SHORT_TIME);
321 ALLOW_WHILE_IDLE_LONG_TIME = mParser.getLong(KEY_ALLOW_WHILE_IDLE_LONG_TIME,
322 DEFAULT_ALLOW_WHILE_IDLE_LONG_TIME);
323 ALLOW_WHILE_IDLE_WHITELIST_DURATION = mParser.getLong(
324 KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION,
325 DEFAULT_ALLOW_WHILE_IDLE_WHITELIST_DURATION);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700326 LISTENER_TIMEOUT = mParser.getLong(KEY_LISTENER_TIMEOUT,
327 DEFAULT_LISTENER_TIMEOUT);
Dianne Hackborna750a632015-06-16 17:18:23 -0700328
329 updateAllowWhileIdleMinTimeLocked();
330 updateAllowWhileIdleWhitelistDurationLocked();
331 }
332 }
333
334 void dump(PrintWriter pw) {
335 pw.println(" Settings:");
336
337 pw.print(" "); pw.print(KEY_MIN_FUTURITY); pw.print("=");
338 TimeUtils.formatDuration(MIN_FUTURITY, pw);
339 pw.println();
340
341 pw.print(" "); pw.print(KEY_MIN_INTERVAL); pw.print("=");
342 TimeUtils.formatDuration(MIN_INTERVAL, pw);
343 pw.println();
344
Christopher Tate14a7bb02015-10-01 10:24:31 -0700345 pw.print(" "); pw.print(KEY_LISTENER_TIMEOUT); pw.print("=");
346 TimeUtils.formatDuration(LISTENER_TIMEOUT, pw);
347 pw.println();
348
Dianne Hackborna750a632015-06-16 17:18:23 -0700349 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_SHORT_TIME); pw.print("=");
350 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_SHORT_TIME, pw);
351 pw.println();
352
353 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_LONG_TIME); pw.print("=");
354 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_LONG_TIME, pw);
355 pw.println();
356
357 pw.print(" "); pw.print(KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION); pw.print("=");
358 TimeUtils.formatDuration(ALLOW_WHILE_IDLE_WHITELIST_DURATION, pw);
359 pw.println();
360 }
Kweku Adams61e03292017-10-19 14:27:12 -0700361
362 void dumpProto(ProtoOutputStream proto, long fieldId) {
363 final long token = proto.start(fieldId);
364
365 proto.write(ConstantsProto.MIN_FUTURITY_DURATION_MS, MIN_FUTURITY);
366 proto.write(ConstantsProto.MIN_INTERVAL_DURATION_MS, MIN_INTERVAL);
367 proto.write(ConstantsProto.LISTENER_TIMEOUT_DURATION_MS, LISTENER_TIMEOUT);
368 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_SHORT_DURATION_MS,
369 ALLOW_WHILE_IDLE_SHORT_TIME);
370 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_LONG_DURATION_MS,
371 ALLOW_WHILE_IDLE_LONG_TIME);
372 proto.write(ConstantsProto.ALLOW_WHILE_IDLE_WHITELIST_DURATION_MS,
373 ALLOW_WHILE_IDLE_WHITELIST_DURATION);
374
375 proto.end(token);
376 }
Dianne Hackborna750a632015-06-16 17:18:23 -0700377 }
378
379 final Constants mConstants;
380
Christopher Tate1590f1e2014-10-02 17:27:57 -0700381 // Alarm delivery ordering bookkeeping
382 static final int PRIO_TICK = 0;
383 static final int PRIO_WAKEUP = 1;
384 static final int PRIO_NORMAL = 2;
385
Dianne Hackborna750a632015-06-16 17:18:23 -0700386 final class PriorityClass {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700387 int seq;
388 int priority;
389
390 PriorityClass() {
391 seq = mCurrentSeq - 1;
392 priority = PRIO_NORMAL;
393 }
394 }
395
Dianne Hackborna750a632015-06-16 17:18:23 -0700396 final HashMap<String, PriorityClass> mPriorities = new HashMap<>();
Christopher Tate1590f1e2014-10-02 17:27:57 -0700397 int mCurrentSeq = 0;
398
Dianne Hackborna750a632015-06-16 17:18:23 -0700399 static final class WakeupEvent {
Christopher Tate18a75f12013-07-01 18:18:59 -0700400 public long when;
401 public int uid;
402 public String action;
403
404 public WakeupEvent(long theTime, int theUid, String theAction) {
405 when = theTime;
406 uid = theUid;
407 action = theAction;
408 }
409 }
410
Adam Lesinski182f73f2013-12-05 16:48:06 -0800411 final LinkedList<WakeupEvent> mRecentWakeups = new LinkedList<WakeupEvent>();
412 final long RECENT_WAKEUP_PERIOD = 1000L * 60 * 60 * 24; // one day
Christopher Tate18a75f12013-07-01 18:18:59 -0700413
Adrian Roosc42a1e12014-07-07 23:35:53 +0200414 final class Batch {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700415 long start; // These endpoints are always in ELAPSED
416 long end;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700417 int flags; // Flags for alarms, such as FLAG_STANDALONE.
Christopher Tatee0a22b32013-07-11 14:43:13 -0700418
419 final ArrayList<Alarm> alarms = new ArrayList<Alarm>();
420
421 Batch() {
422 start = 0;
423 end = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700424 flags = 0;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700425 }
426
427 Batch(Alarm seed) {
428 start = seed.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700429 end = seed.maxWhenElapsed;
430 flags = seed.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700431 alarms.add(seed);
432 }
433
434 int size() {
435 return alarms.size();
436 }
437
438 Alarm get(int index) {
439 return alarms.get(index);
440 }
441
442 boolean canHold(long whenElapsed, long maxWhen) {
443 return (end >= whenElapsed) && (start <= maxWhen);
444 }
445
446 boolean add(Alarm alarm) {
447 boolean newStart = false;
448 // narrows the batch if necessary; presumes that canHold(alarm) is true
449 int index = Collections.binarySearch(alarms, alarm, sIncreasingTimeOrder);
450 if (index < 0) {
451 index = 0 - index - 1;
452 }
453 alarms.add(index, alarm);
454 if (DEBUG_BATCH) {
455 Slog.v(TAG, "Adding " + alarm + " to " + this);
456 }
457 if (alarm.whenElapsed > start) {
458 start = alarm.whenElapsed;
459 newStart = true;
460 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700461 if (alarm.maxWhenElapsed < end) {
462 end = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700463 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700464 flags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700465
466 if (DEBUG_BATCH) {
467 Slog.v(TAG, " => now " + this);
468 }
469 return newStart;
470 }
471
Christopher Tate14a7bb02015-10-01 10:24:31 -0700472 boolean remove(final PendingIntent operation, final IAlarmListener listener) {
473 if (operation == null && listener == null) {
474 if (localLOGV) {
475 Slog.w(TAG, "requested remove() of null operation",
476 new RuntimeException("here"));
477 }
478 return false;
479 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700480 boolean didRemove = false;
481 long newStart = 0; // recalculate endpoints as we go
482 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700483 int newFlags = 0;
Christopher Tateae269d52013-09-26 13:11:55 -0700484 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700485 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700486 if (alarm.matches(operation, listener)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700487 alarms.remove(i);
488 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200489 if (alarm.alarmClock != null) {
490 mNextAlarmClockMayChange = true;
491 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700492 } else {
493 if (alarm.whenElapsed > newStart) {
494 newStart = alarm.whenElapsed;
495 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700496 if (alarm.maxWhenElapsed < newEnd) {
497 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700498 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700499 newFlags |= alarm.flags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700500 i++;
501 }
502 }
503 if (didRemove) {
504 // commit the new batch bounds
505 start = newStart;
506 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700507 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700508 }
509 return didRemove;
510 }
511
512 boolean remove(final String packageName) {
Christopher Tate14a7bb02015-10-01 10:24:31 -0700513 if (packageName == null) {
514 if (localLOGV) {
515 Slog.w(TAG, "requested remove() of null packageName",
516 new RuntimeException("here"));
517 }
518 return false;
519 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700520 boolean didRemove = false;
521 long newStart = 0; // recalculate endpoints as we go
522 long newEnd = Long.MAX_VALUE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700523 int newFlags = 0;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700524 for (int i = alarms.size()-1; i >= 0; i--) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700525 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700526 if (alarm.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700527 alarms.remove(i);
528 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200529 if (alarm.alarmClock != null) {
530 mNextAlarmClockMayChange = true;
531 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700532 } else {
533 if (alarm.whenElapsed > newStart) {
534 newStart = alarm.whenElapsed;
535 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700536 if (alarm.maxWhenElapsed < newEnd) {
537 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700538 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700539 newFlags |= alarm.flags;
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700540 }
541 }
542 if (didRemove) {
543 // commit the new batch bounds
544 start = newStart;
545 end = newEnd;
546 flags = newFlags;
547 }
548 return didRemove;
549 }
550
551 boolean removeForStopped(final int uid) {
552 boolean didRemove = false;
553 long newStart = 0; // recalculate endpoints as we go
554 long newEnd = Long.MAX_VALUE;
555 int newFlags = 0;
556 for (int i = alarms.size()-1; i >= 0; i--) {
557 Alarm alarm = alarms.get(i);
558 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -0800559 if (alarm.uid == uid && ActivityManager.getService().isAppStartModeDisabled(
560 uid, alarm.packageName)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -0700561 alarms.remove(i);
562 didRemove = true;
563 if (alarm.alarmClock != null) {
564 mNextAlarmClockMayChange = true;
565 }
566 } else {
567 if (alarm.whenElapsed > newStart) {
568 newStart = alarm.whenElapsed;
569 }
570 if (alarm.maxWhenElapsed < newEnd) {
571 newEnd = alarm.maxWhenElapsed;
572 }
573 newFlags |= alarm.flags;
574 }
575 } catch (RemoteException e) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700576 }
577 }
578 if (didRemove) {
579 // commit the new batch bounds
580 start = newStart;
581 end = newEnd;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700582 flags = newFlags;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700583 }
584 return didRemove;
585 }
586
587 boolean remove(final int userHandle) {
588 boolean didRemove = false;
589 long newStart = 0; // recalculate endpoints as we go
590 long newEnd = Long.MAX_VALUE;
Christopher Tateae269d52013-09-26 13:11:55 -0700591 for (int i = 0; i < alarms.size(); ) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700592 Alarm alarm = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700593 if (UserHandle.getUserId(alarm.creatorUid) == userHandle) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700594 alarms.remove(i);
595 didRemove = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +0200596 if (alarm.alarmClock != null) {
597 mNextAlarmClockMayChange = true;
598 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700599 } else {
600 if (alarm.whenElapsed > newStart) {
601 newStart = alarm.whenElapsed;
602 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700603 if (alarm.maxWhenElapsed < newEnd) {
604 newEnd = alarm.maxWhenElapsed;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700605 }
606 i++;
607 }
608 }
609 if (didRemove) {
610 // commit the new batch bounds
611 start = newStart;
612 end = newEnd;
613 }
614 return didRemove;
615 }
616
617 boolean hasPackage(final String packageName) {
618 final int N = alarms.size();
619 for (int i = 0; i < N; i++) {
620 Alarm a = alarms.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -0700621 if (a.matches(packageName)) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700622 return true;
623 }
624 }
625 return false;
626 }
627
628 boolean hasWakeups() {
629 final int N = alarms.size();
630 for (int i = 0; i < N; i++) {
631 Alarm a = alarms.get(i);
632 // non-wakeup alarms are types 1 and 3, i.e. have the low bit set
633 if ((a.type & TYPE_NONWAKEUP_MASK) == 0) {
634 return true;
635 }
636 }
637 return false;
638 }
639
640 @Override
641 public String toString() {
642 StringBuilder b = new StringBuilder(40);
643 b.append("Batch{"); b.append(Integer.toHexString(this.hashCode()));
644 b.append(" num="); b.append(size());
645 b.append(" start="); b.append(start);
646 b.append(" end="); b.append(end);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700647 if (flags != 0) {
648 b.append(" flgs=0x");
649 b.append(Integer.toHexString(flags));
Christopher Tatee0a22b32013-07-11 14:43:13 -0700650 }
651 b.append('}');
652 return b.toString();
653 }
Kweku Adams61e03292017-10-19 14:27:12 -0700654
655 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
656 long nowRTC) {
657 final long token = proto.start(fieldId);
658
659 proto.write(BatchProto.START_REALTIME, start);
660 proto.write(BatchProto.END_REALTIME, end);
661 proto.write(BatchProto.FLAGS, flags);
662 for (Alarm a : alarms) {
663 a.writeToProto(proto, BatchProto.ALARMS, nowElapsed, nowRTC);
664 }
665
666 proto.end(token);
667 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700668 }
669
670 static class BatchTimeOrder implements Comparator<Batch> {
671 public int compare(Batch b1, Batch b2) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -0800672 long when1 = b1.start;
673 long when2 = b2.start;
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800674 if (when1 > when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700675 return 1;
676 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +0800677 if (when1 < when2) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700678 return -1;
679 }
680 return 0;
681 }
682 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800683
684 final Comparator<Alarm> mAlarmDispatchComparator = new Comparator<Alarm>() {
685 @Override
686 public int compare(Alarm lhs, Alarm rhs) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700687 // priority class trumps everything. TICK < WAKEUP < NORMAL
688 if (lhs.priorityClass.priority < rhs.priorityClass.priority) {
689 return -1;
690 } else if (lhs.priorityClass.priority > rhs.priorityClass.priority) {
691 return 1;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800692 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700693
694 // within each class, sort by nominal delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800695 if (lhs.whenElapsed < rhs.whenElapsed) {
696 return -1;
697 } else if (lhs.whenElapsed > rhs.whenElapsed) {
698 return 1;
699 }
Christopher Tate1590f1e2014-10-02 17:27:57 -0700700
701 // same priority class + same target delivery time
Dianne Hackborn3d658bf2014-02-05 13:38:56 -0800702 return 0;
703 }
704 };
705
Christopher Tate1590f1e2014-10-02 17:27:57 -0700706 void calculateDeliveryPriorities(ArrayList<Alarm> alarms) {
707 final int N = alarms.size();
708 for (int i = 0; i < N; i++) {
709 Alarm a = alarms.get(i);
710
711 final int alarmPrio;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700712 if (a.operation != null
713 && Intent.ACTION_TIME_TICK.equals(a.operation.getIntent().getAction())) {
Christopher Tate1590f1e2014-10-02 17:27:57 -0700714 alarmPrio = PRIO_TICK;
715 } else if (a.wakeup) {
716 alarmPrio = PRIO_WAKEUP;
717 } else {
718 alarmPrio = PRIO_NORMAL;
719 }
720
721 PriorityClass packagePrio = a.priorityClass;
Christopher Tate14a7bb02015-10-01 10:24:31 -0700722 String alarmPackage = (a.operation != null)
723 ? a.operation.getCreatorPackage()
724 : a.packageName;
725 if (packagePrio == null) packagePrio = mPriorities.get(alarmPackage);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700726 if (packagePrio == null) {
727 packagePrio = a.priorityClass = new PriorityClass(); // lowest prio & stale sequence
Christopher Tate14a7bb02015-10-01 10:24:31 -0700728 mPriorities.put(alarmPackage, packagePrio);
Christopher Tate1590f1e2014-10-02 17:27:57 -0700729 }
730 a.priorityClass = packagePrio;
731
732 if (packagePrio.seq != mCurrentSeq) {
733 // first alarm we've seen in the current delivery generation from this package
734 packagePrio.priority = alarmPrio;
735 packagePrio.seq = mCurrentSeq;
736 } else {
737 // Multiple alarms from this package being delivered in this generation;
738 // bump the package's delivery class if it's warranted.
739 // TICK < WAKEUP < NORMAL
740 if (alarmPrio < packagePrio.priority) {
741 packagePrio.priority = alarmPrio;
742 }
743 }
744 }
745 }
746
Christopher Tatee0a22b32013-07-11 14:43:13 -0700747 // minimum recurrence period or alarm futurity for us to be able to fuzz it
Adam Lesinski182f73f2013-12-05 16:48:06 -0800748 static final long MIN_FUZZABLE_INTERVAL = 10000;
749 static final BatchTimeOrder sBatchOrder = new BatchTimeOrder();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700750 final ArrayList<Batch> mAlarmBatches = new ArrayList<>();
751
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700752 // 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 -0700753 // to run during this time are placed in mPendingWhileIdleAlarms
754 Alarm mPendingIdleUntil = null;
Dianne Hackbornf70faed2015-04-21 14:11:38 -0700755 Alarm mNextWakeFromIdle = null;
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700756 ArrayList<Alarm> mPendingWhileIdleAlarms = new ArrayList<>();
Christopher Tatee0a22b32013-07-11 14:43:13 -0700757
Jeff Brownb880d882014-02-10 19:47:07 -0800758 public AlarmManagerService(Context context) {
759 super(context);
Dianne Hackborna750a632015-06-16 17:18:23 -0700760 mConstants = new Constants(mHandler);
Jeff Brownb880d882014-02-10 19:47:07 -0800761 }
762
Christopher Tatee0a22b32013-07-11 14:43:13 -0700763 static long convertToElapsed(long when, int type) {
764 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
765 if (isRtc) {
766 when -= System.currentTimeMillis() - SystemClock.elapsedRealtime();
767 }
768 return when;
769 }
770
771 // Apply a heuristic to { recurrence interval, futurity of the trigger time } to
772 // calculate the end of our nominal delivery window for the alarm.
773 static long maxTriggerTime(long now, long triggerAtTime, long interval) {
774 // Current heuristic: batchable window is 75% of either the recurrence interval
775 // [for a periodic alarm] or of the time from now to the desired delivery time,
776 // with a minimum delay/interval of 10 seconds, under which we will simply not
777 // defer the alarm.
778 long futurity = (interval == 0)
779 ? (triggerAtTime - now)
780 : interval;
Christopher Tate57ceaaa2013-07-19 16:30:43 -0700781 if (futurity < MIN_FUZZABLE_INTERVAL) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700782 futurity = 0;
783 }
784 return triggerAtTime + (long)(.75 * futurity);
785 }
786
787 // returns true if the batch was added at the head
788 static boolean addBatchLocked(ArrayList<Batch> list, Batch newBatch) {
789 int index = Collections.binarySearch(list, newBatch, sBatchOrder);
790 if (index < 0) {
791 index = 0 - index - 1;
792 }
793 list.add(index, newBatch);
794 return (index == 0);
795 }
796
Christopher Tate385e4982013-07-23 18:22:29 -0700797 // Return the index of the matching batch, or -1 if none found.
798 int attemptCoalesceLocked(long whenElapsed, long maxWhen) {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700799 final int N = mAlarmBatches.size();
800 for (int i = 0; i < N; i++) {
801 Batch b = mAlarmBatches.get(i);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700802 if ((b.flags&AlarmManager.FLAG_STANDALONE) == 0 && b.canHold(whenElapsed, maxWhen)) {
Christopher Tate385e4982013-07-23 18:22:29 -0700803 return i;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700804 }
805 }
Christopher Tate385e4982013-07-23 18:22:29 -0700806 return -1;
Christopher Tatee0a22b32013-07-11 14:43:13 -0700807 }
808
809 // The RTC clock has moved arbitrarily, so we need to recalculate all the batching
810 void rebatchAllAlarms() {
Christopher Tatee0a22b32013-07-11 14:43:13 -0700811 synchronized (mLock) {
Christopher Tate4cb338d2013-07-26 13:11:31 -0700812 rebatchAllAlarmsLocked(true);
813 }
814 }
815
816 void rebatchAllAlarmsLocked(boolean doValidate) {
817 ArrayList<Batch> oldSet = (ArrayList<Batch>) mAlarmBatches.clone();
818 mAlarmBatches.clear();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700819 Alarm oldPendingIdleUntil = mPendingIdleUntil;
Christopher Tate4cb338d2013-07-26 13:11:31 -0700820 final long nowElapsed = SystemClock.elapsedRealtime();
821 final int oldBatches = oldSet.size();
822 for (int batchNum = 0; batchNum < oldBatches; batchNum++) {
823 Batch batch = oldSet.get(batchNum);
824 final int N = batch.size();
825 for (int i = 0; i < N; i++) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700826 reAddAlarmLocked(batch.get(i), nowElapsed, doValidate);
Christopher Tatee0a22b32013-07-11 14:43:13 -0700827 }
828 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700829 if (oldPendingIdleUntil != null && oldPendingIdleUntil != mPendingIdleUntil) {
830 Slog.wtf(TAG, "Rebatching: idle until changed from " + oldPendingIdleUntil
831 + " to " + mPendingIdleUntil);
832 if (mPendingIdleUntil == null) {
833 // Somehow we lost this... we need to restore all of the pending alarms.
834 restorePendingWhileIdleAlarmsLocked();
835 }
836 }
837 rescheduleKernelAlarmsLocked();
838 updateNextAlarmClockLocked();
839 }
840
841 void reAddAlarmLocked(Alarm a, long nowElapsed, boolean doValidate) {
842 a.when = a.origWhen;
843 long whenElapsed = convertToElapsed(a.when, a.type);
844 final long maxElapsed;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700845 if (a.windowLength == AlarmManager.WINDOW_EXACT) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700846 // Exact
847 maxElapsed = whenElapsed;
848 } else {
849 // Not exact. Preserve any explicit window, otherwise recalculate
850 // the window based on the alarm's new futurity. Note that this
851 // reflects a policy of preferring timely to deferred delivery.
852 maxElapsed = (a.windowLength > 0)
853 ? (whenElapsed + a.windowLength)
854 : maxTriggerTime(nowElapsed, whenElapsed, a.repeatInterval);
855 }
856 a.whenElapsed = whenElapsed;
857 a.maxWhenElapsed = maxElapsed;
858 setImplLocked(a, true, doValidate);
859 }
860
Suprabh Shukladb6bf662017-08-30 15:41:53 -0700861 /**
862 * Sends alarms that were blocked due to user applied background restrictions - either because
863 * the user lifted those or the uid came to foreground.
864 *
865 * @param uid uid to filter on
866 * @param packageName package to filter on, or null for all packages in uid
867 */
868 void sendPendingBackgroundAlarmsLocked(int uid, String packageName) {
869 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(uid);
870 if (alarmsForUid == null || alarmsForUid.size() == 0) {
871 return;
872 }
873 final ArrayList<Alarm> alarmsToDeliver;
874 if (packageName != null) {
875 if (DEBUG_BG_LIMIT) {
876 Slog.d(TAG, "Sending blocked alarms for uid " + uid + ", package " + packageName);
877 }
878 alarmsToDeliver = new ArrayList<>();
879 for (int i = alarmsForUid.size() - 1; i >= 0; i--) {
880 final Alarm a = alarmsForUid.get(i);
881 if (a.matches(packageName)) {
882 alarmsToDeliver.add(alarmsForUid.remove(i));
883 }
884 }
885 if (alarmsForUid.size() == 0) {
886 mPendingBackgroundAlarms.remove(uid);
887 }
888 } else {
889 if (DEBUG_BG_LIMIT) {
890 Slog.d(TAG, "Sending blocked alarms for uid " + uid);
891 }
892 alarmsToDeliver = alarmsForUid;
893 mPendingBackgroundAlarms.remove(uid);
894 }
895 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
896 }
897
898 void sendPendingBackgroundAlarmsForAppIdLocked(int appId) {
899 final ArrayList<Alarm> alarmsToDeliver = new ArrayList<>();
900 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
901 final int uid = mPendingBackgroundAlarms.keyAt(i);
902 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
903 if (UserHandle.getAppId(uid) == appId) {
904 alarmsToDeliver.addAll(alarmsForUid);
905 mPendingBackgroundAlarms.removeAt(i);
906 }
907 }
908 deliverPendingBackgroundAlarmsLocked(alarmsToDeliver, SystemClock.elapsedRealtime());
909 }
910
911 private void deliverPendingBackgroundAlarmsLocked(ArrayList<Alarm> alarms, long nowELAPSED) {
912 final int N = alarms.size();
913 boolean hasWakeup = false;
914 for (int i = 0; i < N; i++) {
915 final Alarm alarm = alarms.get(i);
916 if (alarm.wakeup) {
917 hasWakeup = true;
918 }
919 alarm.count = 1;
920 // Recurring alarms may have passed several alarm intervals while the
921 // alarm was kept pending. Send the appropriate trigger count.
922 if (alarm.repeatInterval > 0) {
923 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
924 // Also schedule its next recurrence
925 final long delta = alarm.count * alarm.repeatInterval;
926 final long nextElapsed = alarm.whenElapsed + delta;
927 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
928 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
929 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
930 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
931 // Kernel alarms will be rescheduled as needed in setImplLocked
932 }
933 }
934 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
935 // No need to wakeup for non wakeup alarms
936 if (mPendingNonWakeupAlarms.size() == 0) {
937 mStartCurrentDelayTime = nowELAPSED;
938 mNextNonWakeupDeliveryTime = nowELAPSED
939 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
940 }
941 mPendingNonWakeupAlarms.addAll(alarms);
942 mNumDelayedAlarms += alarms.size();
943 } else {
944 if (DEBUG_BG_LIMIT) {
945 Slog.d(TAG, "Waking up to deliver pending blocked alarms");
946 }
947 // Since we are waking up, also deliver any pending non wakeup alarms we have.
948 if (mPendingNonWakeupAlarms.size() > 0) {
949 alarms.addAll(mPendingNonWakeupAlarms);
950 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
951 mTotalDelayTime += thisDelayTime;
952 if (mMaxDelayTime < thisDelayTime) {
953 mMaxDelayTime = thisDelayTime;
954 }
955 mPendingNonWakeupAlarms.clear();
956 }
957 calculateDeliveryPriorities(alarms);
958 Collections.sort(alarms, mAlarmDispatchComparator);
959 deliverAlarmsLocked(alarms, nowELAPSED);
960 }
961 }
962
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700963 void restorePendingWhileIdleAlarmsLocked() {
Dianne Hackbornae78bf82015-10-26 13:33:20 -0700964 if (RECORD_DEVICE_IDLE_ALARMS) {
965 IdleDispatchEntry ent = new IdleDispatchEntry();
966 ent.uid = 0;
967 ent.pkg = "FINISH IDLE";
968 ent.elapsedRealtime = SystemClock.elapsedRealtime();
969 mAllowWhileIdleDispatches.add(ent);
970 }
971
Dianne Hackborn35d54032015-04-23 10:30:43 -0700972 // Bring pending alarms back into the main list.
Dianne Hackborn0b4daca2015-04-27 09:47:32 -0700973 if (mPendingWhileIdleAlarms.size() > 0) {
974 ArrayList<Alarm> alarms = mPendingWhileIdleAlarms;
975 mPendingWhileIdleAlarms = new ArrayList<>();
976 final long nowElapsed = SystemClock.elapsedRealtime();
977 for (int i=alarms.size() - 1; i >= 0; i--) {
978 Alarm a = alarms.get(i);
979 reAddAlarmLocked(a, nowElapsed, false);
980 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700981 }
Dianne Hackborn35d54032015-04-23 10:30:43 -0700982
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700983 // Make sure we are using the correct ALLOW_WHILE_IDLE min time.
Dianne Hackborna750a632015-06-16 17:18:23 -0700984 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -0700985
Dianne Hackborn35d54032015-04-23 10:30:43 -0700986 // Reschedule everything.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -0700987 rescheduleKernelAlarmsLocked();
988 updateNextAlarmClockLocked();
Dianne Hackborn35d54032015-04-23 10:30:43 -0700989
990 // And send a TIME_TICK right now, since it is important to get the UI updated.
991 try {
992 mTimeTickSender.send();
993 } catch (PendingIntent.CanceledException e) {
994 }
Christopher Tatee0a22b32013-07-11 14:43:13 -0700995 }
996
Christopher Tate14a7bb02015-10-01 10:24:31 -0700997 static final class InFlight {
Dianne Hackborn81038902012-11-26 17:04:09 -0800998 final PendingIntent mPendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -0700999 final long mWhenElapsed;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001000 final IBinder mListener;
David Christieebe51fc2013-07-26 13:23:29 -07001001 final WorkSource mWorkSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001002 final int mUid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001003 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001004 final BroadcastStats mBroadcastStats;
1005 final FilterStats mFilterStats;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001006 final int mAlarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001007
Christopher Tate14a7bb02015-10-01 10:24:31 -07001008 InFlight(AlarmManagerService service, PendingIntent pendingIntent, IAlarmListener listener,
1009 WorkSource workSource, int uid, String alarmPkg, int alarmType, String tag,
1010 long nowELAPSED) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001011 mPendingIntent = pendingIntent;
Christopher Tateeabba732017-08-17 17:12:52 -07001012 mWhenElapsed = nowELAPSED;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001013 mListener = listener != null ? listener.asBinder() : null;
David Christieebe51fc2013-07-26 13:23:29 -07001014 mWorkSource = workSource;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001015 mUid = uid;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001016 mTag = tag;
Christopher Tate14a7bb02015-10-01 10:24:31 -07001017 mBroadcastStats = (pendingIntent != null)
1018 ? service.getStatsLocked(pendingIntent)
1019 : service.getStatsLocked(uid, alarmPkg);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001020 FilterStats fs = mBroadcastStats.filterStats.get(mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001021 if (fs == null) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001022 fs = new FilterStats(mBroadcastStats, mTag);
1023 mBroadcastStats.filterStats.put(mTag, fs);
Dianne Hackborn81038902012-11-26 17:04:09 -08001024 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001025 fs.lastTime = nowELAPSED;
Dianne Hackborn81038902012-11-26 17:04:09 -08001026 mFilterStats = fs;
Dianne Hackborne5167ca2014-03-08 14:39:10 -08001027 mAlarmType = alarmType;
Dianne Hackborn81038902012-11-26 17:04:09 -08001028 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001029
1030 @Override
1031 public String toString() {
1032 return "InFlight{"
1033 + "pendingIntent=" + mPendingIntent
Christopher Tateeabba732017-08-17 17:12:52 -07001034 + ", when=" + mWhenElapsed
Makoto Onuki33955e12017-03-01 18:11:00 -08001035 + ", workSource=" + mWorkSource
1036 + ", uid=" + mUid
1037 + ", tag=" + mTag
1038 + ", broadcastStats=" + mBroadcastStats
1039 + ", filterStats=" + mFilterStats
1040 + ", alarmType=" + mAlarmType
1041 + "}";
1042 }
Kweku Adams61e03292017-10-19 14:27:12 -07001043
1044 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1045 final long token = proto.start(fieldId);
1046
1047 proto.write(InFlightProto.UID, mUid);
1048 proto.write(InFlightProto.TAG, mTag);
1049 proto.write(InFlightProto.WHEN_ELAPSED_MS, mWhenElapsed);
1050 proto.write(InFlightProto.ALARM_TYPE, mAlarmType);
1051 if (mPendingIntent != null) {
1052 mPendingIntent.writeToProto(proto, InFlightProto.PENDING_INTENT);
1053 }
1054 if (mBroadcastStats != null) {
1055 mBroadcastStats.writeToProto(proto, InFlightProto.BROADCAST_STATS);
1056 }
1057 if (mFilterStats != null) {
1058 mFilterStats.writeToProto(proto, InFlightProto.FILTER_STATS);
1059 }
1060 if (mWorkSource != null) {
1061 mWorkSource.writeToProto(proto, InFlightProto.WORK_SOURCE);
1062 }
1063
1064 proto.end(token);
1065 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001067
Adam Lesinski182f73f2013-12-05 16:48:06 -08001068 static final class FilterStats {
Dianne Hackborn81038902012-11-26 17:04:09 -08001069 final BroadcastStats mBroadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001070 final String mTag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001071
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001072 long lastTime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 long aggregateTime;
Dianne Hackborn81038902012-11-26 17:04:09 -08001074 int count;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 int numWakeup;
1076 long startTime;
1077 int nesting;
Dianne Hackborn81038902012-11-26 17:04:09 -08001078
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001079 FilterStats(BroadcastStats broadcastStats, String tag) {
Dianne Hackborn81038902012-11-26 17:04:09 -08001080 mBroadcastStats = broadcastStats;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001081 mTag = tag;
Dianne Hackborn81038902012-11-26 17:04:09 -08001082 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001083
1084 @Override
1085 public String toString() {
1086 return "FilterStats{"
1087 + "tag=" + mTag
1088 + ", lastTime=" + lastTime
1089 + ", aggregateTime=" + aggregateTime
1090 + ", count=" + count
1091 + ", numWakeup=" + numWakeup
1092 + ", startTime=" + startTime
1093 + ", nesting=" + nesting
1094 + "}";
1095 }
Kweku Adams61e03292017-10-19 14:27:12 -07001096
1097 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1098 final long token = proto.start(fieldId);
1099
1100 proto.write(FilterStatsProto.TAG, mTag);
1101 proto.write(FilterStatsProto.LAST_FLIGHT_TIME_REALTIME, lastTime);
1102 proto.write(FilterStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1103 proto.write(FilterStatsProto.COUNT, count);
1104 proto.write(FilterStatsProto.WAKEUP_COUNT, numWakeup);
1105 proto.write(FilterStatsProto.START_TIME_REALTIME, startTime);
1106 proto.write(FilterStatsProto.NESTING, nesting);
1107
1108 proto.end(token);
1109 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001110 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001111
Adam Lesinski182f73f2013-12-05 16:48:06 -08001112 static final class BroadcastStats {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001113 final int mUid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001114 final String mPackageName;
1115
1116 long aggregateTime;
1117 int count;
1118 int numWakeup;
1119 long startTime;
1120 int nesting;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001121 final ArrayMap<String, FilterStats> filterStats = new ArrayMap<String, FilterStats>();
Dianne Hackborn81038902012-11-26 17:04:09 -08001122
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001123 BroadcastStats(int uid, String packageName) {
1124 mUid = uid;
Dianne Hackborn81038902012-11-26 17:04:09 -08001125 mPackageName = packageName;
1126 }
Makoto Onuki33955e12017-03-01 18:11:00 -08001127
1128 @Override
1129 public String toString() {
1130 return "BroadcastStats{"
1131 + "uid=" + mUid
1132 + ", packageName=" + mPackageName
1133 + ", aggregateTime=" + aggregateTime
1134 + ", count=" + count
1135 + ", numWakeup=" + numWakeup
1136 + ", startTime=" + startTime
1137 + ", nesting=" + nesting
1138 + "}";
1139 }
Kweku Adams61e03292017-10-19 14:27:12 -07001140
1141 public void writeToProto(ProtoOutputStream proto, long fieldId) {
1142 final long token = proto.start(fieldId);
1143
1144 proto.write(BroadcastStatsProto.UID, mUid);
1145 proto.write(BroadcastStatsProto.PACKAGE_NAME, mPackageName);
1146 proto.write(BroadcastStatsProto.TOTAL_FLIGHT_DURATION_MS, aggregateTime);
1147 proto.write(BroadcastStatsProto.COUNT, count);
1148 proto.write(BroadcastStatsProto.WAKEUP_COUNT, numWakeup);
1149 proto.write(BroadcastStatsProto.START_TIME_REALTIME, startTime);
1150 proto.write(BroadcastStatsProto.NESTING, nesting);
1151
1152 proto.end(token);
1153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001155
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001156 final SparseArray<ArrayMap<String, BroadcastStats>> mBroadcastStats
1157 = new SparseArray<ArrayMap<String, BroadcastStats>>();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001158
1159 int mNumDelayedAlarms = 0;
1160 long mTotalDelayTime = 0;
1161 long mMaxDelayTime = 0;
1162
Adam Lesinski182f73f2013-12-05 16:48:06 -08001163 @Override
1164 public void onStart() {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001165 mNativeData = init();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08001166 mNextWakeup = mNextNonWakeup = 0;
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001167
1168 // We have to set current TimeZone info to kernel
1169 // because kernel doesn't keep this after reboot
Adam Lesinski182f73f2013-12-05 16:48:06 -08001170 setTimeZoneImpl(SystemProperties.get(TIMEZONE_PROPERTY));
Robert CH Chou64ba8e42009-11-04 21:38:49 +08001171
Christopher Tate247571462017-04-10 11:45:05 -07001172 // Also sure that we're booting with a halfway sensible current time
1173 if (mNativeData != 0) {
1174 final long systemBuildTime = Environment.getRootDirectory().lastModified();
1175 if (System.currentTimeMillis() < systemBuildTime) {
1176 Slog.i(TAG, "Current time only " + System.currentTimeMillis()
1177 + ", advancing to build time " + systemBuildTime);
1178 setKernelTime(mNativeData, systemBuildTime);
1179 }
1180 }
1181
Christopher Tatebb9cce52017-04-18 14:19:43 -07001182 // Determine SysUI's uid
1183 final PackageManager packMan = getContext().getPackageManager();
1184 try {
1185 PermissionInfo sysUiPerm = packMan.getPermissionInfo(SYSTEM_UI_SELF_PERMISSION, 0);
1186 ApplicationInfo sysUi = packMan.getApplicationInfo(sysUiPerm.packageName, 0);
1187 if ((sysUi.privateFlags&ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) {
1188 mSystemUiUid = sysUi.uid;
1189 } else {
1190 Slog.e(TAG, "SysUI permission " + SYSTEM_UI_SELF_PERMISSION
1191 + " defined by non-privileged app " + sysUi.packageName
1192 + " - ignoring");
1193 }
1194 } catch (NameNotFoundException e) {
1195 }
1196
1197 if (mSystemUiUid <= 0) {
1198 Slog.wtf(TAG, "SysUI package not found!");
1199 }
1200
Adam Lesinski182f73f2013-12-05 16:48:06 -08001201 PowerManager pm = (PowerManager) getContext().getSystemService(Context.POWER_SERVICE);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001202 mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "*alarm*");
Dianne Hackborna1f1a3c2014-02-24 18:12:28 -08001203
Adam Lesinski182f73f2013-12-05 16:48:06 -08001204 mTimeTickSender = PendingIntent.getBroadcastAsUser(getContext(), 0,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001205 new Intent(Intent.ACTION_TIME_TICK).addFlags(
Dianne Hackborn3bc8f78d2013-09-19 13:34:35 -07001206 Intent.FLAG_RECEIVER_REGISTERED_ONLY
Chad Brubaker291df4f2017-03-14 10:23:02 -07001207 | Intent.FLAG_RECEIVER_FOREGROUND
1208 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS), 0,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001209 UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001210 Intent intent = new Intent(Intent.ACTION_DATE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001211 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
1212 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001213 mDateChangeSender = PendingIntent.getBroadcastAsUser(getContext(), 0, intent,
Dianne Hackborndb5aca92012-10-26 13:39:41 -07001214 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT, UserHandle.ALL);
Kweku Adams61e03292017-10-19 14:27:12 -07001215
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001216 // now that we have initied the driver schedule the alarm
Adam Lesinski182f73f2013-12-05 16:48:06 -08001217 mClockReceiver = new ClockReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001218 mClockReceiver.scheduleTimeTickEvent();
1219 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001220 mInteractiveStateReceiver = new InteractiveStateReceiver();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001221 mUninstallReceiver = new UninstallReceiver();
Kweku Adams61e03292017-10-19 14:27:12 -07001222
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001223 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001224 AlarmThread waitThread = new AlarmThread();
1225 waitThread.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 } else {
Joe Onorato8a9b2202010-02-26 18:56:32 -08001227 Slog.w(TAG, "Failed to open alarm driver. Falling back to a handler.");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001229
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001230 try {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08001231 ActivityManager.getService().registerUidObserver(new UidObserver(),
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001232 ActivityManager.UID_OBSERVER_GONE | ActivityManager.UID_OBSERVER_IDLE
1233 | ActivityManager.UID_OBSERVER_ACTIVE,
1234 ActivityManager.PROCESS_STATE_UNKNOWN, null);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001235 } catch (RemoteException e) {
1236 // ignored; both services live in system_server
1237 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001238 mAppOpsService = IAppOpsService.Stub.asInterface(
1239 ServiceManager.getService(Context.APP_OPS_SERVICE));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001240 publishBinderService(Context.ALARM_SERVICE, mService);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001241 publishLocalService(LocalService.class, new LocalService());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001243
1244 @Override
Dianne Hackborna750a632015-06-16 17:18:23 -07001245 public void onBootPhase(int phase) {
1246 if (phase == PHASE_SYSTEM_SERVICES_READY) {
1247 mConstants.start(getContext().getContentResolver());
Christopher Tate14a7bb02015-10-01 10:24:31 -07001248 mAppOps = (AppOpsManager) getContext().getSystemService(Context.APP_OPS_SERVICE);
Dianne Hackborn627dfa12015-11-11 18:10:30 -08001249 mLocalDeviceIdleController
1250 = LocalServices.getService(DeviceIdleController.LocalService.class);
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001251 try {
1252 mAppOpsService.startWatchingMode(AppOpsManager.OP_RUN_ANY_IN_BACKGROUND, null,
1253 new AppOpsWatcher());
1254 } catch (RemoteException rexc) {
1255 // Shouldn't happen as they are in the same process.
1256 Slog.e(TAG, "AppOps service not reachable", rexc);
1257 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001258 }
1259 }
1260
1261 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 protected void finalize() throws Throwable {
1263 try {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08001264 close(mNativeData);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 } finally {
1266 super.finalize();
1267 }
1268 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001269
Adam Lesinski182f73f2013-12-05 16:48:06 -08001270 void setTimeZoneImpl(String tz) {
1271 if (TextUtils.isEmpty(tz)) {
1272 return;
David Christieebe51fc2013-07-26 13:23:29 -07001273 }
1274
Adam Lesinski182f73f2013-12-05 16:48:06 -08001275 TimeZone zone = TimeZone.getTimeZone(tz);
1276 // Prevent reentrant calls from stepping on each other when writing
1277 // the time zone property
1278 boolean timeZoneWasChanged = false;
1279 synchronized (this) {
1280 String current = SystemProperties.get(TIMEZONE_PROPERTY);
1281 if (current == null || !current.equals(zone.getID())) {
1282 if (localLOGV) {
1283 Slog.v(TAG, "timezone changed: " + current + ", new=" + zone.getID());
1284 }
1285 timeZoneWasChanged = true;
1286 SystemProperties.set(TIMEZONE_PROPERTY, zone.getID());
1287 }
1288
1289 // Update the kernel timezone information
1290 // Kernel tracks time offsets as 'minutes west of GMT'
1291 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08001292 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Adam Lesinski182f73f2013-12-05 16:48:06 -08001293 }
1294
1295 TimeZone.setDefault(null);
1296
1297 if (timeZoneWasChanged) {
1298 Intent intent = new Intent(Intent.ACTION_TIMEZONE_CHANGED);
Chad Brubaker291df4f2017-03-14 10:23:02 -07001299 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate5cdf9f82017-05-03 18:10:39 -07001300 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
Chad Brubaker291df4f2017-03-14 10:23:02 -07001301 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001302 intent.putExtra("time-zone", zone.getID());
1303 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
1304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001306
Adam Lesinski182f73f2013-12-05 16:48:06 -08001307 void removeImpl(PendingIntent operation) {
1308 if (operation == null) {
1309 return;
1310 }
1311 synchronized (mLock) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07001312 removeLocked(operation, null);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001313 }
1314 }
1315
1316 void setImpl(int type, long triggerAtTime, long windowLength, long interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001317 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1318 int flags, WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock,
1319 int callingUid, String callingPackage) {
1320 // must be *either* PendingIntent or AlarmReceiver, but not both
1321 if ((operation == null && directReceiver == null)
1322 || (operation != null && directReceiver != null)) {
1323 Slog.w(TAG, "Alarms must either supply a PendingIntent or an AlarmReceiver");
1324 // NB: previous releases failed silently here, so we are continuing to do the same
1325 // rather than throw an IllegalArgumentException.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001326 return;
1327 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001328
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001329 // Sanity check the window length. This will catch people mistakenly
1330 // trying to pass an end-of-window timestamp rather than a duration.
1331 if (windowLength > AlarmManager.INTERVAL_HALF_DAY) {
1332 Slog.w(TAG, "Window length " + windowLength
1333 + "ms suspiciously long; limiting to 1 hour");
1334 windowLength = AlarmManager.INTERVAL_HOUR;
1335 }
1336
Christopher Tate498c6cb2014-11-17 16:09:27 -08001337 // Sanity check the recurrence interval. This will catch people who supply
1338 // seconds when the API expects milliseconds.
Dianne Hackborna750a632015-06-16 17:18:23 -07001339 final long minInterval = mConstants.MIN_INTERVAL;
1340 if (interval > 0 && interval < minInterval) {
Christopher Tate498c6cb2014-11-17 16:09:27 -08001341 Slog.w(TAG, "Suspiciously short interval " + interval
Dianne Hackborna750a632015-06-16 17:18:23 -07001342 + " millis; expanding to " + (minInterval/1000)
Christopher Tate498c6cb2014-11-17 16:09:27 -08001343 + " seconds");
Dianne Hackborna750a632015-06-16 17:18:23 -07001344 interval = minInterval;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001345 }
1346
Christopher Tatee0a22b32013-07-11 14:43:13 -07001347 if (type < RTC_WAKEUP || type > ELAPSED_REALTIME) {
1348 throw new IllegalArgumentException("Invalid alarm type " + type);
1349 }
1350
Christopher Tate5f221e82013-07-30 17:13:15 -07001351 if (triggerAtTime < 0) {
Christopher Tate5f221e82013-07-30 17:13:15 -07001352 final long what = Binder.getCallingPid();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001353 Slog.w(TAG, "Invalid alarm trigger time! " + triggerAtTime + " from uid=" + callingUid
Christopher Tate5f221e82013-07-30 17:13:15 -07001354 + " pid=" + what);
1355 triggerAtTime = 0;
1356 }
1357
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001358 final long nowElapsed = SystemClock.elapsedRealtime();
Christopher Tate498c6cb2014-11-17 16:09:27 -08001359 final long nominalTrigger = convertToElapsed(triggerAtTime, type);
1360 // Try to prevent spamming by making sure we aren't firing alarms in the immediate future
Dianne Hackborna750a632015-06-16 17:18:23 -07001361 final long minTrigger = nowElapsed + mConstants.MIN_FUTURITY;
Christopher Tate498c6cb2014-11-17 16:09:27 -08001362 final long triggerElapsed = (nominalTrigger > minTrigger) ? nominalTrigger : minTrigger;
1363
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001364 final long maxElapsed;
1365 if (windowLength == AlarmManager.WINDOW_EXACT) {
1366 maxElapsed = triggerElapsed;
1367 } else if (windowLength < 0) {
1368 maxElapsed = maxTriggerTime(nowElapsed, triggerElapsed, interval);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001369 // Fix this window in place, so that as time approaches we don't collapse it.
1370 windowLength = maxElapsed - triggerElapsed;
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001371 } else {
1372 maxElapsed = triggerElapsed + windowLength;
1373 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001374
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 synchronized (mLock) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07001376 if (DEBUG_BATCH) {
1377 Slog.v(TAG, "set(" + operation + ") : type=" + type
Christopher Tate57ceaaa2013-07-19 16:30:43 -07001378 + " triggerAtTime=" + triggerAtTime + " win=" + windowLength
Christopher Tatee0a22b32013-07-11 14:43:13 -07001379 + " tElapsed=" + triggerElapsed + " maxElapsed=" + maxElapsed
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001380 + " interval=" + interval + " flags=0x" + Integer.toHexString(flags));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001381 }
Christopher Tate3e04b472013-10-21 17:51:31 -07001382 setImplLocked(type, triggerAtTime, triggerElapsed, windowLength, maxElapsed,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001383 interval, operation, directReceiver, listenerTag, flags, true, workSource,
1384 alarmClock, callingUid, callingPackage);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001385 }
1386 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387
Christopher Tate3e04b472013-10-21 17:51:31 -07001388 private void setImplLocked(int type, long when, long whenElapsed, long windowLength,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001389 long maxWhen, long interval, PendingIntent operation, IAlarmListener directReceiver,
1390 String listenerTag, int flags, boolean doValidate, WorkSource workSource,
1391 AlarmManager.AlarmClockInfo alarmClock, int callingUid, String callingPackage) {
Christopher Tate3e04b472013-10-21 17:51:31 -07001392 Alarm a = new Alarm(type, when, whenElapsed, windowLength, maxWhen, interval,
Christopher Tate14a7bb02015-10-01 10:24:31 -07001393 operation, directReceiver, listenerTag, workSource, flags, alarmClock,
1394 callingUid, callingPackage);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001395 try {
Dianne Hackbornc3af19a2017-01-20 17:00:44 -08001396 if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07001397 Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a
1398 + " -- package not allowed to start");
1399 return;
1400 }
1401 } catch (RemoteException e) {
1402 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07001403 removeLocked(operation, directReceiver);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001404 setImplLocked(a, false, doValidate);
1405 }
Christopher Tateb8849c12011-02-08 13:39:01 -08001406
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001407 private void setImplLocked(Alarm a, boolean rebatching, boolean doValidate) {
1408 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001409 // This is a special alarm that will put the system into idle until it goes off.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001410 // The caller has given the time they want this to happen at, however we need
1411 // to pull that earlier if there are existing alarms that have requested to
Dianne Hackbornf3831292015-10-15 14:51:06 -07001412 // bring us out of idle at an earlier time.
1413 if (mNextWakeFromIdle != null && a.whenElapsed > mNextWakeFromIdle.whenElapsed) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001414 a.when = a.whenElapsed = a.maxWhenElapsed = mNextWakeFromIdle.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001415 }
1416 // Add fuzz to make the alarm go off some time before the actual desired time.
1417 final long nowElapsed = SystemClock.elapsedRealtime();
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001418 final int fuzz = fuzzForDuration(a.whenElapsed-nowElapsed);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001419 if (fuzz > 0) {
1420 if (mRandom == null) {
1421 mRandom = new Random();
1422 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001423 final int delta = mRandom.nextInt(fuzz);
1424 a.whenElapsed -= delta;
1425 if (false) {
1426 Slog.d(TAG, "Alarm when: " + a.whenElapsed);
1427 Slog.d(TAG, "Delta until alarm: " + (a.whenElapsed-nowElapsed));
1428 Slog.d(TAG, "Applied fuzz: " + fuzz);
1429 Slog.d(TAG, "Final delta: " + delta);
1430 Slog.d(TAG, "Final when: " + a.whenElapsed);
1431 }
1432 a.when = a.maxWhenElapsed = a.whenElapsed;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001433 }
1434
1435 } else if (mPendingIdleUntil != null) {
1436 // We currently have an idle until alarm scheduled; if the new alarm has
1437 // not explicitly stated it wants to run while idle, then put it on hold.
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001438 if ((a.flags&(AlarmManager.FLAG_ALLOW_WHILE_IDLE
1439 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED
1440 | AlarmManager.FLAG_WAKE_FROM_IDLE))
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001441 == 0) {
1442 mPendingWhileIdleAlarms.add(a);
1443 return;
1444 }
1445 }
1446
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001447 if (RECORD_DEVICE_IDLE_ALARMS) {
1448 if ((a.flags & AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
1449 IdleDispatchEntry ent = new IdleDispatchEntry();
1450 ent.uid = a.uid;
1451 ent.pkg = a.operation.getCreatorPackage();
1452 ent.tag = a.operation.getTag("");
1453 ent.op = "SET";
1454 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1455 ent.argRealtime = a.whenElapsed;
1456 mAllowWhileIdleDispatches.add(ent);
1457 }
1458 }
1459
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001460 int whichBatch = ((a.flags&AlarmManager.FLAG_STANDALONE) != 0)
1461 ? -1 : attemptCoalesceLocked(a.whenElapsed, a.maxWhenElapsed);
Christopher Tate385e4982013-07-23 18:22:29 -07001462 if (whichBatch < 0) {
1463 Batch batch = new Batch(a);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001464 addBatchLocked(mAlarmBatches, batch);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 } else {
Christopher Tate385e4982013-07-23 18:22:29 -07001466 Batch batch = mAlarmBatches.get(whichBatch);
Christopher Tate7d57ed82013-10-25 20:18:03 -07001467 if (batch.add(a)) {
Christopher Tate385e4982013-07-23 18:22:29 -07001468 // The start time of this batch advanced, so batch ordering may
1469 // have just been broken. Move it to where it now belongs.
1470 mAlarmBatches.remove(whichBatch);
1471 addBatchLocked(mAlarmBatches, batch);
1472 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
1474
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001475 if (a.alarmClock != null) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001476 mNextAlarmClockMayChange = true;
Adrian Roosc42a1e12014-07-07 23:35:53 +02001477 }
1478
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001479 boolean needRebatch = false;
1480
1481 if ((a.flags&AlarmManager.FLAG_IDLE_UNTIL) != 0) {
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001482 if (RECORD_DEVICE_IDLE_ALARMS) {
1483 if (mPendingIdleUntil == null) {
1484 IdleDispatchEntry ent = new IdleDispatchEntry();
1485 ent.uid = 0;
1486 ent.pkg = "START IDLE";
1487 ent.elapsedRealtime = SystemClock.elapsedRealtime();
1488 mAllowWhileIdleDispatches.add(ent);
1489 }
1490 }
Makoto Onuki4274a6d2017-04-21 12:21:25 -07001491 if ((mPendingIdleUntil != a) && (mPendingIdleUntil != null)) {
1492 Slog.wtfStack(TAG, "setImplLocked: idle until changed from " + mPendingIdleUntil
1493 + " to " + a);
1494 }
1495
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001496 mPendingIdleUntil = a;
Dianne Hackborna750a632015-06-16 17:18:23 -07001497 mConstants.updateAllowWhileIdleMinTimeLocked();
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001498 needRebatch = true;
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001499 } else if ((a.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
1500 if (mNextWakeFromIdle == null || mNextWakeFromIdle.whenElapsed > a.whenElapsed) {
1501 mNextWakeFromIdle = a;
1502 // If this wake from idle is earlier than whatever was previously scheduled,
1503 // and we are currently idling, then we need to rebatch alarms in case the idle
1504 // until time needs to be updated.
1505 if (mPendingIdleUntil != null) {
1506 needRebatch = true;
1507 }
1508 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001509 }
1510
1511 if (!rebatching) {
1512 if (DEBUG_VALIDATE) {
1513 if (doValidate && !validateConsistencyLocked()) {
1514 Slog.v(TAG, "Tipping-point operation: type=" + a.type + " when=" + a.when
1515 + " when(hex)=" + Long.toHexString(a.when)
1516 + " whenElapsed=" + a.whenElapsed
1517 + " maxWhenElapsed=" + a.maxWhenElapsed
1518 + " interval=" + a.repeatInterval + " op=" + a.operation
1519 + " flags=0x" + Integer.toHexString(a.flags));
1520 rebatchAllAlarmsLocked(false);
1521 needRebatch = false;
1522 }
1523 }
1524
1525 if (needRebatch) {
Christopher Tate4cb338d2013-07-26 13:11:31 -07001526 rebatchAllAlarmsLocked(false);
Christopher Tate4cb338d2013-07-26 13:11:31 -07001527 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001528
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001529 rescheduleKernelAlarmsLocked();
1530 updateNextAlarmClockLocked();
1531 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001532 }
1533
Adam Lesinski182f73f2013-12-05 16:48:06 -08001534 private final IBinder mService = new IAlarmManager.Stub() {
1535 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001536 public void set(String callingPackage,
1537 int type, long triggerAtTime, long windowLength, long interval, int flags,
1538 PendingIntent operation, IAlarmListener directReceiver, String listenerTag,
1539 WorkSource workSource, AlarmManager.AlarmClockInfo alarmClock) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001540 final int callingUid = Binder.getCallingUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07001541
1542 // make sure the caller is not lying about which package should be blamed for
1543 // wakelock time spent in alarm delivery
1544 mAppOps.checkPackage(callingUid, callingPackage);
1545
1546 // Repeating alarms must use PendingIntent, not direct listener
1547 if (interval != 0) {
1548 if (directReceiver != null) {
1549 throw new IllegalArgumentException("Repeating alarms cannot use AlarmReceivers");
1550 }
1551 }
1552
Adam Lesinski182f73f2013-12-05 16:48:06 -08001553 if (workSource != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001554 getContext().enforcePermission(
Adam Lesinski182f73f2013-12-05 16:48:06 -08001555 android.Manifest.permission.UPDATE_DEVICE_STATS,
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001556 Binder.getCallingPid(), callingUid, "AlarmManager.set");
Christopher Tate89779822012-08-31 14:40:03 -07001557 }
1558
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001559 // No incoming callers can request either WAKE_FROM_IDLE or
1560 // ALLOW_WHILE_IDLE_UNRESTRICTED -- we will apply those later as appropriate.
1561 flags &= ~(AlarmManager.FLAG_WAKE_FROM_IDLE
1562 | AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED);
1563
1564 // Only the system can use FLAG_IDLE_UNTIL -- this is used to tell the alarm
1565 // manager when to come out of idle mode, which is only for DeviceIdleController.
1566 if (callingUid != Process.SYSTEM_UID) {
1567 flags &= ~AlarmManager.FLAG_IDLE_UNTIL;
1568 }
1569
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001570 // If this is an exact time alarm, then it can't be batched with other alarms.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001571 if (windowLength == AlarmManager.WINDOW_EXACT) {
1572 flags |= AlarmManager.FLAG_STANDALONE;
1573 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001574
1575 // If this alarm is for an alarm clock, then it must be standalone and we will
1576 // use it to wake early from idle if needed.
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001577 if (alarmClock != null) {
1578 flags |= AlarmManager.FLAG_WAKE_FROM_IDLE | AlarmManager.FLAG_STANDALONE;
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001579
1580 // If the caller is a core system component or on the user's whitelist, and not calling
1581 // to do work on behalf of someone else, then always set ALLOW_WHILE_IDLE_UNRESTRICTED.
1582 // This means we will allow these alarms to go off as normal even while idle, with no
1583 // timing restrictions.
1584 } else if (workSource == null && (callingUid < Process.FIRST_APPLICATION_UID
Christopher Tatebb9cce52017-04-18 14:19:43 -07001585 || callingUid == mSystemUiUid
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001586 || Arrays.binarySearch(mDeviceIdleUserWhitelist,
1587 UserHandle.getAppId(callingUid)) >= 0)) {
1588 flags |= AlarmManager.FLAG_ALLOW_WHILE_IDLE_UNRESTRICTED;
1589 flags &= ~AlarmManager.FLAG_ALLOW_WHILE_IDLE;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001590 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001591
Christopher Tate14a7bb02015-10-01 10:24:31 -07001592 setImpl(type, triggerAtTime, windowLength, interval, operation, directReceiver,
1593 listenerTag, flags, workSource, alarmClock, callingUid, callingPackage);
Adam Lesinski182f73f2013-12-05 16:48:06 -08001594 }
Christopher Tate89779822012-08-31 14:40:03 -07001595
Adam Lesinski182f73f2013-12-05 16:48:06 -08001596 @Override
Greg Hackmann0cab8962014-02-21 16:35:52 -08001597 public boolean setTime(long millis) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08001598 getContext().enforceCallingOrSelfPermission(
1599 "android.permission.SET_TIME",
1600 "setTime");
1601
Greg Hackmann0cab8962014-02-21 16:35:52 -08001602 if (mNativeData == 0) {
1603 Slog.w(TAG, "Not setting time since no alarm driver is available.");
1604 return false;
Christopher Tate89779822012-08-31 14:40:03 -07001605 }
Greg Hackmann0cab8962014-02-21 16:35:52 -08001606
1607 synchronized (mLock) {
1608 return setKernelTime(mNativeData, millis) == 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001610 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001611
1612 @Override
1613 public void setTimeZone(String tz) {
1614 getContext().enforceCallingOrSelfPermission(
1615 "android.permission.SET_TIME_ZONE",
1616 "setTimeZone");
1617
1618 final long oldId = Binder.clearCallingIdentity();
1619 try {
1620 setTimeZoneImpl(tz);
1621 } finally {
1622 Binder.restoreCallingIdentity(oldId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001623 }
1624 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001625
Adam Lesinski182f73f2013-12-05 16:48:06 -08001626 @Override
Christopher Tate14a7bb02015-10-01 10:24:31 -07001627 public void remove(PendingIntent operation, IAlarmListener listener) {
1628 if (operation == null && listener == null) {
1629 Slog.w(TAG, "remove() with no intent or listener");
1630 return;
1631 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001632
Christopher Tate14a7bb02015-10-01 10:24:31 -07001633 synchronized (mLock) {
1634 removeLocked(operation, listener);
1635 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 }
Christopher Tate4cb338d2013-07-26 13:11:31 -07001637
Adam Lesinski182f73f2013-12-05 16:48:06 -08001638 @Override
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001639 public long getNextWakeFromIdleTime() {
1640 return getNextWakeFromIdleTimeImpl();
1641 }
1642
1643 @Override
Jose Lima235510e2014-08-13 12:50:01 -07001644 public AlarmManager.AlarmClockInfo getNextAlarmClock(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02001645 userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(),
1646 Binder.getCallingUid(), userId, false /* allowAll */, false /* requireFull */,
1647 "getNextAlarmClock", null);
1648
1649 return getNextAlarmClockImpl(userId);
1650 }
1651
1652 @Override
Adam Lesinski182f73f2013-12-05 16:48:06 -08001653 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
Jeff Sharkey6df866a2017-03-31 14:08:23 -06001654 if (!DumpUtils.checkDumpAndUsageStatsPermission(getContext(), TAG, pw)) return;
Kweku Adams61e03292017-10-19 14:27:12 -07001655
1656 if (args.length > 0 && "--proto".equals(args[0])) {
1657 dumpProto(fd);
1658 } else {
1659 dumpImpl(pw);
1660 }
Dianne Hackborn80a4af22012-08-27 19:18:31 -07001661 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08001662 };
Christopher Tate4cb338d2013-07-26 13:11:31 -07001663
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001664 public final class LocalService {
1665 public void setDeviceIdleUserWhitelist(int[] appids) {
1666 setDeviceIdleUserWhitelistImpl(appids);
1667 }
1668 }
1669
Adam Lesinski182f73f2013-12-05 16:48:06 -08001670 void dumpImpl(PrintWriter pw) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001671 synchronized (mLock) {
1672 pw.println("Current Alarm Manager state:");
Dianne Hackborna750a632015-06-16 17:18:23 -07001673 mConstants.dump(pw);
1674 pw.println();
1675
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001676 pw.print(" Foreground uids: [");
1677 for (int i = 0; i < mForegroundUids.size(); i++) {
1678 if (mForegroundUids.valueAt(i)) pw.print(mForegroundUids.keyAt(i) + " ");
1679 }
1680 pw.println("]");
1681 pw.println(" Forced app standby packages: " + mForcedAppStandbyPackages);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001682 final long nowRTC = System.currentTimeMillis();
1683 final long nowELAPSED = SystemClock.elapsedRealtime();
1684 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
1685
Dianne Hackborna750a632015-06-16 17:18:23 -07001686 pw.print(" nowRTC="); pw.print(nowRTC);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001687 pw.print("="); pw.print(sdf.format(new Date(nowRTC)));
Christopher Tate7f2a0352015-12-08 10:24:33 -08001688 pw.print(" nowELAPSED="); pw.print(nowELAPSED);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001689 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001690 pw.print(" mLastTimeChangeClockTime="); pw.print(mLastTimeChangeClockTime);
Dianne Hackbornc3527222015-05-13 14:03:20 -07001691 pw.print("="); pw.println(sdf.format(new Date(mLastTimeChangeClockTime)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001692 pw.print(" mLastTimeChangeRealtime=");
Dianne Hackbornc3527222015-05-13 14:03:20 -07001693 TimeUtils.formatDuration(mLastTimeChangeRealtime, pw);
1694 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001695 if (!mInteractive) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001696 pw.print(" Time since non-interactive: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001697 TimeUtils.formatDuration(nowELAPSED - mNonInteractiveStartTime, pw);
1698 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001699 pw.print(" Max wakeup delay: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001700 TimeUtils.formatDuration(currentNonWakeupFuzzLocked(nowELAPSED), pw);
1701 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001702 pw.print(" Time since last dispatch: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001703 TimeUtils.formatDuration(nowELAPSED - mLastAlarmDeliveryTime, pw);
1704 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001705 pw.print(" Next non-wakeup delivery time: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001706 TimeUtils.formatDuration(nowELAPSED - mNextNonWakeupDeliveryTime, pw);
1707 pw.println();
1708 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001709
1710 long nextWakeupRTC = mNextWakeup + (nowRTC - nowELAPSED);
1711 long nextNonWakeupRTC = mNextNonWakeup + (nowRTC - nowELAPSED);
Dianne Hackborna750a632015-06-16 17:18:23 -07001712 pw.print(" Next non-wakeup alarm: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001713 TimeUtils.formatDuration(mNextNonWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001714 pw.print(" = "); pw.println(sdf.format(new Date(nextNonWakeupRTC)));
Dianne Hackborna750a632015-06-16 17:18:23 -07001715 pw.print(" Next wakeup: "); TimeUtils.formatDuration(mNextWakeup, nowELAPSED, pw);
Christopher Tatee0a22b32013-07-11 14:43:13 -07001716 pw.print(" = "); pw.println(sdf.format(new Date(nextWakeupRTC)));
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07001717 pw.print(" Last wakeup: "); TimeUtils.formatDuration(mLastWakeup, nowELAPSED, pw);
1718 pw.print(" set at "); TimeUtils.formatDuration(mLastWakeupSet, nowELAPSED, pw);
1719 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001720 pw.print(" Num time change events: "); pw.println(mNumTimeChanged);
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08001721 pw.println(" mDeviceIdleUserWhitelist=" + Arrays.toString(mDeviceIdleUserWhitelist));
Christopher Tatee0a22b32013-07-11 14:43:13 -07001722
John Spurlock604a5ee2015-06-01 12:27:22 -04001723 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001724 pw.println(" Next alarm clock information: ");
John Spurlock604a5ee2015-06-01 12:27:22 -04001725 final TreeSet<Integer> users = new TreeSet<>();
1726 for (int i = 0; i < mNextAlarmClockForUser.size(); i++) {
1727 users.add(mNextAlarmClockForUser.keyAt(i));
1728 }
1729 for (int i = 0; i < mPendingSendNextAlarmClockChangedForUser.size(); i++) {
1730 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
1731 }
1732 for (int user : users) {
1733 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
1734 final long time = next != null ? next.getTriggerTime() : 0;
1735 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
Dianne Hackborna750a632015-06-16 17:18:23 -07001736 pw.print(" user:"); pw.print(user);
John Spurlock604a5ee2015-06-01 12:27:22 -04001737 pw.print(" pendingSend:"); pw.print(pendingSend);
1738 pw.print(" time:"); pw.print(time);
1739 if (time > 0) {
1740 pw.print(" = "); pw.print(sdf.format(new Date(time)));
1741 pw.print(" = "); TimeUtils.formatDuration(time, nowRTC, pw);
1742 }
1743 pw.println();
1744 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07001745 if (mAlarmBatches.size() > 0) {
1746 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001747 pw.print(" Pending alarm batches: ");
Christopher Tatee0a22b32013-07-11 14:43:13 -07001748 pw.println(mAlarmBatches.size());
1749 for (Batch b : mAlarmBatches) {
1750 pw.print(b); pw.println(':');
Dianne Hackborna750a632015-06-16 17:18:23 -07001751 dumpAlarmList(pw, b.alarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001753 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07001754 pw.println();
1755 pw.println(" Pending user blocked background alarms: ");
1756 boolean blocked = false;
1757 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
1758 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
1759 if (blockedAlarms != null && blockedAlarms.size() > 0) {
1760 blocked = true;
1761 dumpAlarmList(pw, blockedAlarms, " ", nowELAPSED, nowRTC, sdf);
1762 }
1763 }
1764 if (!blocked) {
1765 pw.println(" none");
1766 }
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001767 if (mPendingIdleUntil != null || mPendingWhileIdleAlarms.size() > 0) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001768 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001769 pw.println(" Idle mode state:");
1770 pw.print(" Idling until: ");
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001771 if (mPendingIdleUntil != null) {
1772 pw.println(mPendingIdleUntil);
Kweku Adams61e03292017-10-19 14:27:12 -07001773 mPendingIdleUntil.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn0b4daca2015-04-27 09:47:32 -07001774 } else {
1775 pw.println("null");
1776 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001777 pw.println(" Pending alarms:");
1778 dumpAlarmList(pw, mPendingWhileIdleAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07001779 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001780 if (mNextWakeFromIdle != null) {
1781 pw.println();
1782 pw.print(" Next wake from idle: "); pw.println(mNextWakeFromIdle);
Kweku Adams61e03292017-10-19 14:27:12 -07001783 mNextWakeFromIdle.dump(pw, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001784 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001785
1786 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001787 pw.print(" Past-due non-wakeup alarms: ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001788 if (mPendingNonWakeupAlarms.size() > 0) {
1789 pw.println(mPendingNonWakeupAlarms.size());
Dianne Hackborna750a632015-06-16 17:18:23 -07001790 dumpAlarmList(pw, mPendingNonWakeupAlarms, " ", nowELAPSED, nowRTC, sdf);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001791 } else {
1792 pw.println("(none)");
1793 }
Dianne Hackborna750a632015-06-16 17:18:23 -07001794 pw.print(" Number of delayed alarms: "); pw.print(mNumDelayedAlarms);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001795 pw.print(", total delay time: "); TimeUtils.formatDuration(mTotalDelayTime, pw);
1796 pw.println();
Dianne Hackborna750a632015-06-16 17:18:23 -07001797 pw.print(" Max delay time: "); TimeUtils.formatDuration(mMaxDelayTime, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001798 pw.print(", max non-interactive time: ");
1799 TimeUtils.formatDuration(mNonInteractiveTime, pw);
1800 pw.println();
1801
1802 pw.println();
Dianne Hackborn1d442e02009-04-20 18:14:05 -07001803 pw.print(" Broadcast ref count: "); pw.println(mBroadcastRefCount);
Christopher Tateeabba732017-08-17 17:12:52 -07001804 pw.print(" PendingIntent send count: "); pw.println(mSendCount);
1805 pw.print(" PendingIntent finish count: "); pw.println(mSendFinishCount);
1806 pw.print(" Listener send count: "); pw.println(mListenerCount);
1807 pw.print(" Listener finish count: "); pw.println(mListenerFinishCount);
Dianne Hackborn81038902012-11-26 17:04:09 -08001808 pw.println();
1809
Christopher Tate7f2a0352015-12-08 10:24:33 -08001810 if (mInFlight.size() > 0) {
1811 pw.println("Outstanding deliveries:");
1812 for (int i = 0; i < mInFlight.size(); i++) {
1813 pw.print(" #"); pw.print(i); pw.print(": ");
1814 pw.println(mInFlight.get(i));
1815 }
1816 pw.println();
1817 }
1818
Dianne Hackborna750a632015-06-16 17:18:23 -07001819 pw.print(" mAllowWhileIdleMinTime=");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001820 TimeUtils.formatDuration(mAllowWhileIdleMinTime, pw);
1821 pw.println();
1822 if (mLastAllowWhileIdleDispatch.size() > 0) {
Dianne Hackborna750a632015-06-16 17:18:23 -07001823 pw.println(" Last allow while idle dispatch times:");
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07001824 for (int i=0; i<mLastAllowWhileIdleDispatch.size(); i++) {
1825 pw.print(" UID ");
1826 UserHandle.formatUid(pw, mLastAllowWhileIdleDispatch.keyAt(i));
1827 pw.print(": ");
1828 TimeUtils.formatDuration(mLastAllowWhileIdleDispatch.valueAt(i),
1829 nowELAPSED, pw);
1830 pw.println();
1831 }
1832 }
1833 pw.println();
1834
Dianne Hackborn81038902012-11-26 17:04:09 -08001835 if (mLog.dump(pw, " Recent problems", " ")) {
1836 pw.println();
1837 }
1838
1839 final FilterStats[] topFilters = new FilterStats[10];
1840 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
1841 @Override
1842 public int compare(FilterStats lhs, FilterStats rhs) {
1843 if (lhs.aggregateTime < rhs.aggregateTime) {
1844 return 1;
1845 } else if (lhs.aggregateTime > rhs.aggregateTime) {
1846 return -1;
1847 }
1848 return 0;
1849 }
1850 };
1851 int len = 0;
Kweku Adams61e03292017-10-19 14:27:12 -07001852 // Get the top 10 FilterStats, ordered by aggregateTime.
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001853 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1854 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1855 for (int ip=0; ip<uidStats.size(); ip++) {
1856 BroadcastStats bs = uidStats.valueAt(ip);
1857 for (int is=0; is<bs.filterStats.size(); is++) {
1858 FilterStats fs = bs.filterStats.valueAt(is);
1859 int pos = len > 0
1860 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
1861 if (pos < 0) {
1862 pos = -pos - 1;
Dianne Hackborn81038902012-11-26 17:04:09 -08001863 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001864 if (pos < topFilters.length) {
1865 int copylen = topFilters.length - pos - 1;
1866 if (copylen > 0) {
1867 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
1868 }
1869 topFilters[pos] = fs;
1870 if (len < topFilters.length) {
1871 len++;
1872 }
Dianne Hackborn81038902012-11-26 17:04:09 -08001873 }
1874 }
1875 }
1876 }
1877 if (len > 0) {
1878 pw.println(" Top Alarms:");
1879 for (int i=0; i<len; i++) {
1880 FilterStats fs = topFilters[i];
1881 pw.print(" ");
1882 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1883 TimeUtils.formatDuration(fs.aggregateTime, pw);
1884 pw.print(" running, "); pw.print(fs.numWakeup);
1885 pw.print(" wakeups, "); pw.print(fs.count);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001886 pw.print(" alarms: "); UserHandle.formatUid(pw, fs.mBroadcastStats.mUid);
1887 pw.print(":"); pw.print(fs.mBroadcastStats.mPackageName);
Dianne Hackborn81038902012-11-26 17:04:09 -08001888 pw.println();
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001889 pw.print(" "); pw.print(fs.mTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08001890 pw.println();
1891 }
1892 }
1893
1894 pw.println(" ");
1895 pw.println(" Alarm Stats:");
1896 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001897 for (int iu=0; iu<mBroadcastStats.size(); iu++) {
1898 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
1899 for (int ip=0; ip<uidStats.size(); ip++) {
1900 BroadcastStats bs = uidStats.valueAt(ip);
1901 pw.print(" ");
1902 if (bs.nesting > 0) pw.print("*ACTIVE* ");
1903 UserHandle.formatUid(pw, bs.mUid);
1904 pw.print(":");
1905 pw.print(bs.mPackageName);
1906 pw.print(" "); TimeUtils.formatDuration(bs.aggregateTime, pw);
1907 pw.print(" running, "); pw.print(bs.numWakeup);
1908 pw.println(" wakeups:");
1909 tmpFilters.clear();
1910 for (int is=0; is<bs.filterStats.size(); is++) {
1911 tmpFilters.add(bs.filterStats.valueAt(is));
1912 }
1913 Collections.sort(tmpFilters, comparator);
1914 for (int i=0; i<tmpFilters.size(); i++) {
1915 FilterStats fs = tmpFilters.get(i);
1916 pw.print(" ");
1917 if (fs.nesting > 0) pw.print("*ACTIVE* ");
1918 TimeUtils.formatDuration(fs.aggregateTime, pw);
1919 pw.print(" "); pw.print(fs.numWakeup);
1920 pw.print(" wakes " ); pw.print(fs.count);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07001921 pw.print(" alarms, last ");
1922 TimeUtils.formatDuration(fs.lastTime, nowELAPSED, pw);
1923 pw.println(":");
1924 pw.print(" ");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07001925 pw.print(fs.mTag);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08001926 pw.println();
1927 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001928 }
1929 }
Christopher Tate18a75f12013-07-01 18:18:59 -07001930
Dianne Hackbornae78bf82015-10-26 13:33:20 -07001931 if (RECORD_DEVICE_IDLE_ALARMS) {
1932 pw.println();
1933 pw.println(" Allow while idle dispatches:");
1934 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
1935 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
1936 pw.print(" ");
1937 TimeUtils.formatDuration(ent.elapsedRealtime, nowELAPSED, pw);
1938 pw.print(": ");
1939 UserHandle.formatUid(pw, ent.uid);
1940 pw.print(":");
1941 pw.println(ent.pkg);
1942 if (ent.op != null) {
1943 pw.print(" ");
1944 pw.print(ent.op);
1945 pw.print(" / ");
1946 pw.print(ent.tag);
1947 if (ent.argRealtime != 0) {
1948 pw.print(" (");
1949 TimeUtils.formatDuration(ent.argRealtime, nowELAPSED, pw);
1950 pw.print(")");
1951 }
1952 pw.println();
1953 }
1954 }
1955 }
1956
Christopher Tate18a75f12013-07-01 18:18:59 -07001957 if (WAKEUP_STATS) {
1958 pw.println();
1959 pw.println(" Recent Wakeup History:");
Christopher Tate18a75f12013-07-01 18:18:59 -07001960 long last = -1;
1961 for (WakeupEvent event : mRecentWakeups) {
1962 pw.print(" "); pw.print(sdf.format(new Date(event.when)));
1963 pw.print('|');
1964 if (last < 0) {
1965 pw.print('0');
1966 } else {
1967 pw.print(event.when - last);
1968 }
1969 last = event.when;
1970 pw.print('|'); pw.print(event.uid);
1971 pw.print('|'); pw.print(event.action);
1972 pw.println();
1973 }
1974 pw.println();
1975 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001976 }
1977 }
1978
Kweku Adams61e03292017-10-19 14:27:12 -07001979 void dumpProto(FileDescriptor fd) {
1980 final ProtoOutputStream proto = new ProtoOutputStream(fd);
1981
1982 synchronized (mLock) {
1983 final long nowRTC = System.currentTimeMillis();
1984 final long nowElapsed = SystemClock.elapsedRealtime();
1985 proto.write(AlarmManagerServiceProto.CURRENT_TIME, nowRTC);
1986 proto.write(AlarmManagerServiceProto.ELAPSED_REALTIME, nowElapsed);
1987 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_CLOCK_TIME,
1988 mLastTimeChangeClockTime);
1989 proto.write(AlarmManagerServiceProto.LAST_TIME_CHANGE_REALTIME,
1990 mLastTimeChangeRealtime);
1991
1992 mConstants.dumpProto(proto, AlarmManagerServiceProto.SETTINGS);
1993
1994 final int foregroundUidsSize = mForegroundUids.size();
1995 for (int i = 0; i < foregroundUidsSize; i++) {
1996 if (mForegroundUids.valueAt(i)) {
1997 proto.write(AlarmManagerServiceProto.FOREGROUND_UIDS, mForegroundUids.keyAt(i));
1998 }
1999 }
2000 for (String pkg : mForcedAppStandbyPackages) {
2001 proto.write(AlarmManagerServiceProto.FORCED_APP_STANDBY_PACKAGES, pkg);
2002 }
2003
2004 proto.write(AlarmManagerServiceProto.IS_INTERACTIVE, mInteractive);
2005 if (!mInteractive) {
2006 // Durations
2007 proto.write(AlarmManagerServiceProto.TIME_SINCE_NON_INTERACTIVE_MS,
2008 nowElapsed - mNonInteractiveStartTime);
2009 proto.write(AlarmManagerServiceProto.MAX_WAKEUP_DELAY_MS,
2010 currentNonWakeupFuzzLocked(nowElapsed));
2011 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_DISPATCH_MS,
2012 nowElapsed - mLastAlarmDeliveryTime);
2013 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_DELIVERY_MS,
2014 nowElapsed - mNextNonWakeupDeliveryTime);
2015 }
2016
2017 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_NON_WAKEUP_ALARM_MS,
2018 mNextNonWakeup - nowElapsed);
2019 proto.write(AlarmManagerServiceProto.TIME_UNTIL_NEXT_WAKEUP_MS,
2020 mNextWakeup - nowElapsed);
2021 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_MS,
2022 nowElapsed - mLastWakeup);
2023 proto.write(AlarmManagerServiceProto.TIME_SINCE_LAST_WAKEUP_SET_MS,
2024 nowElapsed - mLastWakeupSet);
2025 proto.write(AlarmManagerServiceProto.TIME_CHANGE_EVENT_COUNT, mNumTimeChanged);
2026 for (int i : mDeviceIdleUserWhitelist) {
2027 proto.write(AlarmManagerServiceProto.DEVICE_IDLE_USER_WHITELIST_APP_IDS, i);
2028 }
2029
2030 final TreeSet<Integer> users = new TreeSet<>();
2031 final int nextAlarmClockForUserSize = mNextAlarmClockForUser.size();
2032 for (int i = 0; i < nextAlarmClockForUserSize; i++) {
2033 users.add(mNextAlarmClockForUser.keyAt(i));
2034 }
2035 final int pendingSendNextAlarmClockChangedForUserSize =
2036 mPendingSendNextAlarmClockChangedForUser.size();
2037 for (int i = 0; i < pendingSendNextAlarmClockChangedForUserSize; i++) {
2038 users.add(mPendingSendNextAlarmClockChangedForUser.keyAt(i));
2039 }
2040 for (int user : users) {
2041 final AlarmManager.AlarmClockInfo next = mNextAlarmClockForUser.get(user);
2042 final long time = next != null ? next.getTriggerTime() : 0;
2043 final boolean pendingSend = mPendingSendNextAlarmClockChangedForUser.get(user);
2044 final long aToken = proto.start(AlarmManagerServiceProto.NEXT_ALARM_CLOCK_METADATA);
2045 proto.write(AlarmClockMetadataProto.USER, user);
2046 proto.write(AlarmClockMetadataProto.IS_PENDING_SEND, pendingSend);
2047 proto.write(AlarmClockMetadataProto.TRIGGER_TIME_MS, time);
2048 proto.end(aToken);
2049 }
2050 for (Batch b : mAlarmBatches) {
2051 b.writeToProto(proto, AlarmManagerServiceProto.PENDING_ALARM_BATCHES,
2052 nowElapsed, nowRTC);
2053 }
2054 for (int i = 0; i < mPendingBackgroundAlarms.size(); i++) {
2055 final ArrayList<Alarm> blockedAlarms = mPendingBackgroundAlarms.valueAt(i);
2056 if (blockedAlarms != null) {
2057 for (Alarm a : blockedAlarms) {
2058 a.writeToProto(proto,
2059 AlarmManagerServiceProto.PENDING_USER_BLOCKED_BACKGROUND_ALARMS,
2060 nowElapsed, nowRTC);
2061 }
2062 }
2063 }
2064 if (mPendingIdleUntil != null) {
2065 mPendingIdleUntil.writeToProto(
2066 proto, AlarmManagerServiceProto.PENDING_IDLE_UNTIL, nowElapsed, nowRTC);
2067 }
2068 for (Alarm a : mPendingWhileIdleAlarms) {
2069 a.writeToProto(proto, AlarmManagerServiceProto.PENDING_WHILE_IDLE_ALARMS,
2070 nowElapsed, nowRTC);
2071 }
2072 if (mNextWakeFromIdle != null) {
2073 mNextWakeFromIdle.writeToProto(proto, AlarmManagerServiceProto.NEXT_WAKE_FROM_IDLE,
2074 nowElapsed, nowRTC);
2075 }
2076
2077 for (Alarm a : mPendingNonWakeupAlarms) {
2078 a.writeToProto(proto, AlarmManagerServiceProto.PAST_DUE_NON_WAKEUP_ALARMS,
2079 nowElapsed, nowRTC);
2080 }
2081
2082 proto.write(AlarmManagerServiceProto.DELAYED_ALARM_COUNT, mNumDelayedAlarms);
2083 proto.write(AlarmManagerServiceProto.TOTAL_DELAY_TIME_MS, mTotalDelayTime);
2084 proto.write(AlarmManagerServiceProto.MAX_DELAY_DURATION_MS, mMaxDelayTime);
2085 proto.write(AlarmManagerServiceProto.MAX_NON_INTERACTIVE_DURATION_MS,
2086 mNonInteractiveTime);
2087
2088 proto.write(AlarmManagerServiceProto.BROADCAST_REF_COUNT, mBroadcastRefCount);
2089 proto.write(AlarmManagerServiceProto.PENDING_INTENT_SEND_COUNT, mSendCount);
2090 proto.write(AlarmManagerServiceProto.PENDING_INTENT_FINISH_COUNT, mSendFinishCount);
2091 proto.write(AlarmManagerServiceProto.LISTENER_SEND_COUNT, mListenerCount);
2092 proto.write(AlarmManagerServiceProto.LISTENER_FINISH_COUNT, mListenerFinishCount);
2093
2094 for (InFlight f : mInFlight) {
2095 f.writeToProto(proto, AlarmManagerServiceProto.OUTSTANDING_DELIVERIES);
2096 }
2097
2098 proto.write(AlarmManagerServiceProto.ALLOW_WHILE_IDLE_MIN_DURATION_MS,
2099 mAllowWhileIdleMinTime);
2100 for (int i = 0; i < mLastAllowWhileIdleDispatch.size(); ++i) {
2101 final long token = proto.start(
2102 AlarmManagerServiceProto.LAST_ALLOW_WHILE_IDLE_DISPATCH_TIMES);
2103 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.UID,
2104 mLastAllowWhileIdleDispatch.keyAt(i));
2105 proto.write(AlarmManagerServiceProto.LastAllowWhileIdleDispatch.TIME_MS,
2106 mLastAllowWhileIdleDispatch.valueAt(i));
2107 proto.end(token);
2108 }
2109
2110 mLog.writeToProto(proto, AlarmManagerServiceProto.RECENT_PROBLEMS);
2111
2112 final FilterStats[] topFilters = new FilterStats[10];
2113 final Comparator<FilterStats> comparator = new Comparator<FilterStats>() {
2114 @Override
2115 public int compare(FilterStats lhs, FilterStats rhs) {
2116 if (lhs.aggregateTime < rhs.aggregateTime) {
2117 return 1;
2118 } else if (lhs.aggregateTime > rhs.aggregateTime) {
2119 return -1;
2120 }
2121 return 0;
2122 }
2123 };
2124 int len = 0;
2125 // Get the top 10 FilterStats, ordered by aggregateTime.
2126 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2127 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2128 for (int ip = 0; ip < uidStats.size(); ++ip) {
2129 BroadcastStats bs = uidStats.valueAt(ip);
2130 for (int is = 0; is < bs.filterStats.size(); ++is) {
2131 FilterStats fs = bs.filterStats.valueAt(is);
2132 int pos = len > 0
2133 ? Arrays.binarySearch(topFilters, 0, len, fs, comparator) : 0;
2134 if (pos < 0) {
2135 pos = -pos - 1;
2136 }
2137 if (pos < topFilters.length) {
2138 int copylen = topFilters.length - pos - 1;
2139 if (copylen > 0) {
2140 System.arraycopy(topFilters, pos, topFilters, pos+1, copylen);
2141 }
2142 topFilters[pos] = fs;
2143 if (len < topFilters.length) {
2144 len++;
2145 }
2146 }
2147 }
2148 }
2149 }
2150 for (int i = 0; i < len; ++i) {
2151 final long token = proto.start(AlarmManagerServiceProto.TOP_ALARMS);
2152 FilterStats fs = topFilters[i];
2153
2154 proto.write(AlarmManagerServiceProto.TopAlarm.UID, fs.mBroadcastStats.mUid);
2155 proto.write(AlarmManagerServiceProto.TopAlarm.PACKAGE_NAME,
2156 fs.mBroadcastStats.mPackageName);
2157 fs.writeToProto(proto, AlarmManagerServiceProto.TopAlarm.FILTER);
2158
2159 proto.end(token);
2160 }
2161
2162 final ArrayList<FilterStats> tmpFilters = new ArrayList<FilterStats>();
2163 for (int iu = 0; iu < mBroadcastStats.size(); ++iu) {
2164 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(iu);
2165 for (int ip = 0; ip < uidStats.size(); ++ip) {
2166 final long token = proto.start(AlarmManagerServiceProto.ALARM_STATS);
2167
2168 BroadcastStats bs = uidStats.valueAt(ip);
2169 bs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.BROADCAST);
2170
2171 // uidStats is an ArrayMap, which we can't sort.
2172 tmpFilters.clear();
2173 for (int is = 0; is < bs.filterStats.size(); ++is) {
2174 tmpFilters.add(bs.filterStats.valueAt(is));
2175 }
2176 Collections.sort(tmpFilters, comparator);
2177 for (FilterStats fs : tmpFilters) {
2178 fs.writeToProto(proto, AlarmManagerServiceProto.AlarmStat.FILTERS);
2179 }
2180
2181 proto.end(token);
2182 }
2183 }
2184
2185 if (RECORD_DEVICE_IDLE_ALARMS) {
2186 for (int i = 0; i < mAllowWhileIdleDispatches.size(); i++) {
2187 IdleDispatchEntry ent = mAllowWhileIdleDispatches.get(i);
2188 final long token = proto.start(
2189 AlarmManagerServiceProto.ALLOW_WHILE_IDLE_DISPATCHES);
2190
2191 proto.write(IdleDispatchEntryProto.UID, ent.uid);
2192 proto.write(IdleDispatchEntryProto.PKG, ent.pkg);
2193 proto.write(IdleDispatchEntryProto.TAG, ent.tag);
2194 proto.write(IdleDispatchEntryProto.OP, ent.op);
2195 proto.write(IdleDispatchEntryProto.ENTRY_CREATION_REALTIME,
2196 ent.elapsedRealtime);
2197 proto.write(IdleDispatchEntryProto.ARG_REALTIME, ent.argRealtime);
2198
2199 proto.end(token);
2200 }
2201 }
2202
2203 if (WAKEUP_STATS) {
2204 for (WakeupEvent event : mRecentWakeups) {
2205 final long token = proto.start(AlarmManagerServiceProto.RECENT_WAKEUP_HISTORY);
2206 proto.write(WakeupEventProto.UID, event.uid);
2207 proto.write(WakeupEventProto.ACTION, event.action);
2208 proto.write(WakeupEventProto.WHEN, event.when);
2209 proto.end(token);
2210 }
2211 }
2212 }
2213
2214 proto.flush();
2215 }
2216
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002217 private void logBatchesLocked(SimpleDateFormat sdf) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002218 ByteArrayOutputStream bs = new ByteArrayOutputStream(2048);
2219 PrintWriter pw = new PrintWriter(bs);
2220 final long nowRTC = System.currentTimeMillis();
2221 final long nowELAPSED = SystemClock.elapsedRealtime();
2222 final int NZ = mAlarmBatches.size();
2223 for (int iz = 0; iz < NZ; iz++) {
2224 Batch bz = mAlarmBatches.get(iz);
2225 pw.append("Batch "); pw.print(iz); pw.append(": "); pw.println(bz);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002226 dumpAlarmList(pw, bz.alarms, " ", nowELAPSED, nowRTC, sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002227 pw.flush();
2228 Slog.v(TAG, bs.toString());
2229 bs.reset();
2230 }
2231 }
2232
2233 private boolean validateConsistencyLocked() {
2234 if (DEBUG_VALIDATE) {
2235 long lastTime = Long.MIN_VALUE;
2236 final int N = mAlarmBatches.size();
2237 for (int i = 0; i < N; i++) {
2238 Batch b = mAlarmBatches.get(i);
2239 if (b.start >= lastTime) {
2240 // duplicate start times are okay because of standalone batches
2241 lastTime = b.start;
2242 } else {
2243 Slog.e(TAG, "CONSISTENCY FAILURE: Batch " + i + " is out of order");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002244 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
2245 logBatchesLocked(sdf);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002246 return false;
2247 }
2248 }
2249 }
2250 return true;
2251 }
2252
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002253 private Batch findFirstWakeupBatchLocked() {
2254 final int N = mAlarmBatches.size();
2255 for (int i = 0; i < N; i++) {
2256 Batch b = mAlarmBatches.get(i);
2257 if (b.hasWakeups()) {
2258 return b;
2259 }
2260 }
2261 return null;
2262 }
2263
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002264 long getNextWakeFromIdleTimeImpl() {
2265 synchronized (mLock) {
2266 return mNextWakeFromIdle != null ? mNextWakeFromIdle.whenElapsed : Long.MAX_VALUE;
2267 }
2268 }
2269
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002270 void setDeviceIdleUserWhitelistImpl(int[] appids) {
2271 synchronized (mLock) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002272 // appids are sorted, just send pending alarms for any new appids added to the whitelist
2273 int i = 0, j = 0;
2274 while (i < appids.length) {
2275 while (j < mDeviceIdleUserWhitelist.length
2276 && mDeviceIdleUserWhitelist[j] < appids[i]) {
2277 j++;
2278 }
2279 if (j < mDeviceIdleUserWhitelist.length
2280 && appids[i] != mDeviceIdleUserWhitelist[j]) {
2281 if (DEBUG_BG_LIMIT) {
2282 Slog.d(TAG, "Sending blocked alarms for whitelisted appid " + appids[j]);
2283 }
2284 sendPendingBackgroundAlarmsForAppIdLocked(appids[j]);
2285 }
2286 i++;
2287 }
Dianne Hackborn262ae5c2016-02-10 16:28:29 -08002288 mDeviceIdleUserWhitelist = appids;
2289 }
2290 }
2291
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002292 AlarmManager.AlarmClockInfo getNextAlarmClockImpl(int userId) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002293 synchronized (mLock) {
2294 return mNextAlarmClockForUser.get(userId);
2295 }
2296 }
2297
2298 /**
2299 * Recomputes the next alarm clock for all users.
2300 */
2301 private void updateNextAlarmClockLocked() {
2302 if (!mNextAlarmClockMayChange) {
2303 return;
2304 }
2305 mNextAlarmClockMayChange = false;
2306
Jose Lima235510e2014-08-13 12:50:01 -07002307 SparseArray<AlarmManager.AlarmClockInfo> nextForUser = mTmpSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002308 nextForUser.clear();
2309
2310 final int N = mAlarmBatches.size();
2311 for (int i = 0; i < N; i++) {
2312 ArrayList<Alarm> alarms = mAlarmBatches.get(i).alarms;
2313 final int M = alarms.size();
2314
2315 for (int j = 0; j < M; j++) {
2316 Alarm a = alarms.get(j);
2317 if (a.alarmClock != null) {
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002318 final int userId = UserHandle.getUserId(a.uid);
Christopher Tate76389c02016-08-03 14:57:47 -07002319 AlarmManager.AlarmClockInfo current = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002320
2321 if (DEBUG_ALARM_CLOCK) {
Christopher Tate76389c02016-08-03 14:57:47 -07002322 Log.v(TAG, "Found AlarmClockInfo " + a.alarmClock + " at " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002323 formatNextAlarm(getContext(), a.alarmClock, userId) +
Adrian Roosc42a1e12014-07-07 23:35:53 +02002324 " for user " + userId);
2325 }
2326
2327 // Alarms and batches are sorted by time, no need to compare times here.
2328 if (nextForUser.get(userId) == null) {
2329 nextForUser.put(userId, a.alarmClock);
Christopher Tate76389c02016-08-03 14:57:47 -07002330 } else if (a.alarmClock.equals(current)
2331 && current.getTriggerTime() <= nextForUser.get(userId).getTriggerTime()) {
2332 // same/earlier time and it's the one we cited before, so stick with it
2333 nextForUser.put(userId, current);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002334 }
2335 }
2336 }
2337 }
2338
2339 // Update mNextAlarmForUser with new values.
2340 final int NN = nextForUser.size();
2341 for (int i = 0; i < NN; i++) {
Jose Lima235510e2014-08-13 12:50:01 -07002342 AlarmManager.AlarmClockInfo newAlarm = nextForUser.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002343 int userId = nextForUser.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002344 AlarmManager.AlarmClockInfo currentAlarm = mNextAlarmClockForUser.get(userId);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002345 if (!newAlarm.equals(currentAlarm)) {
2346 updateNextAlarmInfoForUserLocked(userId, newAlarm);
2347 }
2348 }
2349
2350 // Remove users without any alarm clocks scheduled.
2351 final int NNN = mNextAlarmClockForUser.size();
2352 for (int i = NNN - 1; i >= 0; i--) {
2353 int userId = mNextAlarmClockForUser.keyAt(i);
2354 if (nextForUser.get(userId) == null) {
2355 updateNextAlarmInfoForUserLocked(userId, null);
2356 }
2357 }
2358 }
2359
Jose Lima235510e2014-08-13 12:50:01 -07002360 private void updateNextAlarmInfoForUserLocked(int userId,
2361 AlarmManager.AlarmClockInfo alarmClock) {
Adrian Roosc42a1e12014-07-07 23:35:53 +02002362 if (alarmClock != null) {
2363 if (DEBUG_ALARM_CLOCK) {
2364 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): " +
Selim Cinek9c4a7072014-11-21 17:44:34 +01002365 formatNextAlarm(getContext(), alarmClock, userId));
Adrian Roosc42a1e12014-07-07 23:35:53 +02002366 }
2367 mNextAlarmClockForUser.put(userId, alarmClock);
2368 } else {
2369 if (DEBUG_ALARM_CLOCK) {
2370 Log.v(TAG, "Next AlarmClockInfoForUser(" + userId + "): None");
2371 }
2372 mNextAlarmClockForUser.remove(userId);
2373 }
2374
2375 mPendingSendNextAlarmClockChangedForUser.put(userId, true);
2376 mHandler.removeMessages(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2377 mHandler.sendEmptyMessage(AlarmHandler.SEND_NEXT_ALARM_CLOCK_CHANGED);
2378 }
2379
2380 /**
2381 * Updates NEXT_ALARM_FORMATTED and sends NEXT_ALARM_CLOCK_CHANGED_INTENT for all users
2382 * for which alarm clocks have changed since the last call to this.
2383 *
2384 * Do not call with a lock held. Only call from mHandler's thread.
2385 *
2386 * @see AlarmHandler#SEND_NEXT_ALARM_CLOCK_CHANGED
2387 */
2388 private void sendNextAlarmClockChanged() {
Jose Lima235510e2014-08-13 12:50:01 -07002389 SparseArray<AlarmManager.AlarmClockInfo> pendingUsers = mHandlerSparseAlarmClockArray;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002390 pendingUsers.clear();
2391
2392 synchronized (mLock) {
2393 final int N = mPendingSendNextAlarmClockChangedForUser.size();
2394 for (int i = 0; i < N; i++) {
2395 int userId = mPendingSendNextAlarmClockChangedForUser.keyAt(i);
2396 pendingUsers.append(userId, mNextAlarmClockForUser.get(userId));
2397 }
2398 mPendingSendNextAlarmClockChangedForUser.clear();
2399 }
2400
2401 final int N = pendingUsers.size();
2402 for (int i = 0; i < N; i++) {
2403 int userId = pendingUsers.keyAt(i);
Jose Lima235510e2014-08-13 12:50:01 -07002404 AlarmManager.AlarmClockInfo alarmClock = pendingUsers.valueAt(i);
Adrian Roosc42a1e12014-07-07 23:35:53 +02002405 Settings.System.putStringForUser(getContext().getContentResolver(),
2406 Settings.System.NEXT_ALARM_FORMATTED,
Selim Cinek9c4a7072014-11-21 17:44:34 +01002407 formatNextAlarm(getContext(), alarmClock, userId),
Adrian Roosc42a1e12014-07-07 23:35:53 +02002408 userId);
2409
2410 getContext().sendBroadcastAsUser(NEXT_ALARM_CLOCK_CHANGED_INTENT,
2411 new UserHandle(userId));
2412 }
2413 }
2414
2415 /**
2416 * Formats an alarm like platform/packages/apps/DeskClock used to.
2417 */
Selim Cinek9c4a7072014-11-21 17:44:34 +01002418 private static String formatNextAlarm(final Context context, AlarmManager.AlarmClockInfo info,
2419 int userId) {
2420 String skeleton = DateFormat.is24HourFormat(context, userId) ? "EHm" : "Ehma";
Adrian Roosc42a1e12014-07-07 23:35:53 +02002421 String pattern = DateFormat.getBestDateTimePattern(Locale.getDefault(), skeleton);
2422 return (info == null) ? "" :
2423 DateFormat.format(pattern, info.getTriggerTime()).toString();
2424 }
2425
Adam Lesinski182f73f2013-12-05 16:48:06 -08002426 void rescheduleKernelAlarmsLocked() {
2427 // Schedule the next upcoming wakeup alarm. If there is a deliverable batch
2428 // prior to that which contains no wakeups, we schedule that as well.
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002429 long nextNonWakeup = 0;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002430 if (mAlarmBatches.size() > 0) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002431 final Batch firstWakeup = findFirstWakeupBatchLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002432 final Batch firstBatch = mAlarmBatches.get(0);
Prashant Malani753e9e02015-06-10 17:43:49 -07002433 if (firstWakeup != null && mNextWakeup != firstWakeup.start) {
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002434 mNextWakeup = firstWakeup.start;
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07002435 mLastWakeupSet = SystemClock.elapsedRealtime();
Christopher Tate0dab4dc2014-12-16 12:14:06 -08002436 setLocked(ELAPSED_REALTIME_WAKEUP, firstWakeup.start);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002437 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002438 if (firstBatch != firstWakeup) {
2439 nextNonWakeup = firstBatch.start;
Adam Lesinski182f73f2013-12-05 16:48:06 -08002440 }
2441 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002442 if (mPendingNonWakeupAlarms.size() > 0) {
2443 if (nextNonWakeup == 0 || mNextNonWakeupDeliveryTime < nextNonWakeup) {
2444 nextNonWakeup = mNextNonWakeupDeliveryTime;
2445 }
2446 }
Prashant Malani753e9e02015-06-10 17:43:49 -07002447 if (nextNonWakeup != 0 && mNextNonWakeup != nextNonWakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002448 mNextNonWakeup = nextNonWakeup;
2449 setLocked(ELAPSED_REALTIME, nextNonWakeup);
2450 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002451 }
2452
Christopher Tate14a7bb02015-10-01 10:24:31 -07002453 private void removeLocked(PendingIntent operation, IAlarmListener directReceiver) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002454 boolean didRemove = false;
2455 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2456 Batch b = mAlarmBatches.get(i);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002457 didRemove |= b.remove(operation, directReceiver);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002458 if (b.size() == 0) {
2459 mAlarmBatches.remove(i);
2460 }
2461 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002462 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002463 if (mPendingWhileIdleAlarms.get(i).matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002464 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2465 mPendingWhileIdleAlarms.remove(i);
2466 }
2467 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002468 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2469 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2470 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2471 if (alarmsForUid.get(j).matches(operation, directReceiver)) {
2472 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2473 alarmsForUid.remove(j);
2474 }
2475 }
2476 if (alarmsForUid.size() == 0) {
2477 mPendingBackgroundAlarms.removeAt(i);
2478 }
2479 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002480 if (didRemove) {
2481 if (DEBUG_BATCH) {
2482 Slog.v(TAG, "remove(operation) changed bounds; rebatching");
2483 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002484 boolean restorePending = false;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002485 if (mPendingIdleUntil != null && mPendingIdleUntil.matches(operation, directReceiver)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002486 mPendingIdleUntil = null;
2487 restorePending = true;
2488 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07002489 if (mNextWakeFromIdle != null && mNextWakeFromIdle.matches(operation, directReceiver)) {
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002490 mNextWakeFromIdle = null;
2491 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002492 rebatchAllAlarmsLocked(true);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002493 if (restorePending) {
2494 restorePendingWhileIdleAlarmsLocked();
2495 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002496 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002497 }
2498 }
2499
2500 void removeLocked(String packageName) {
2501 boolean didRemove = false;
2502 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2503 Batch b = mAlarmBatches.get(i);
2504 didRemove |= b.remove(packageName);
2505 if (b.size() == 0) {
2506 mAlarmBatches.remove(i);
2507 }
2508 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002509 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002510 final Alarm a = mPendingWhileIdleAlarms.get(i);
2511 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002512 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2513 mPendingWhileIdleAlarms.remove(i);
2514 }
2515 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002516 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i --) {
2517 final ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.valueAt(i);
2518 for (int j = alarmsForUid.size() - 1; j >= 0; j--) {
2519 if (alarmsForUid.get(j).matches(packageName)) {
2520 alarmsForUid.remove(j);
2521 }
2522 }
2523 if (alarmsForUid.size() == 0) {
2524 mPendingBackgroundAlarms.removeAt(i);
2525 }
2526 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002527 if (didRemove) {
2528 if (DEBUG_BATCH) {
2529 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2530 }
2531 rebatchAllAlarmsLocked(true);
2532 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002533 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002534 }
2535 }
2536
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002537 void removeForStoppedLocked(int uid) {
2538 boolean didRemove = false;
2539 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2540 Batch b = mAlarmBatches.get(i);
2541 didRemove |= b.removeForStopped(uid);
2542 if (b.size() == 0) {
2543 mAlarmBatches.remove(i);
2544 }
2545 }
2546 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
2547 final Alarm a = mPendingWhileIdleAlarms.get(i);
Dianne Hackborne07641d2016-11-09 15:07:23 -08002548 if (a.uid == uid) {
2549 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2550 mPendingWhileIdleAlarms.remove(i);
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002551 }
2552 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002553 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2554 if (mPendingBackgroundAlarms.keyAt(i) == uid) {
2555 mPendingBackgroundAlarms.removeAt(i);
2556 }
2557 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07002558 if (didRemove) {
2559 if (DEBUG_BATCH) {
2560 Slog.v(TAG, "remove(package) changed bounds; rebatching");
2561 }
2562 rebatchAllAlarmsLocked(true);
2563 rescheduleKernelAlarmsLocked();
2564 updateNextAlarmClockLocked();
2565 }
2566 }
2567
Adam Lesinski182f73f2013-12-05 16:48:06 -08002568 void removeUserLocked(int userHandle) {
2569 boolean didRemove = false;
2570 for (int i = mAlarmBatches.size() - 1; i >= 0; i--) {
2571 Batch b = mAlarmBatches.get(i);
2572 didRemove |= b.remove(userHandle);
2573 if (b.size() == 0) {
2574 mAlarmBatches.remove(i);
2575 }
2576 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002577 for (int i = mPendingWhileIdleAlarms.size() - 1; i >= 0; i--) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002578 if (UserHandle.getUserId(mPendingWhileIdleAlarms.get(i).creatorUid)
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002579 == userHandle) {
2580 // Don't set didRemove, since this doesn't impact the scheduled alarms.
2581 mPendingWhileIdleAlarms.remove(i);
2582 }
2583 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002584 for (int i = mPendingBackgroundAlarms.size() - 1; i >= 0; i--) {
2585 if (UserHandle.getUserId(mPendingBackgroundAlarms.keyAt(i)) == userHandle) {
2586 mPendingBackgroundAlarms.removeAt(i);
2587 }
2588 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002589 for (int i = mLastAllowWhileIdleDispatch.size() - 1; i >= 0; i--) {
2590 if (UserHandle.getUserId(mLastAllowWhileIdleDispatch.keyAt(i)) == userHandle) {
2591 mLastAllowWhileIdleDispatch.removeAt(i);
2592 }
2593 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002594
2595 if (didRemove) {
2596 if (DEBUG_BATCH) {
2597 Slog.v(TAG, "remove(user) changed bounds; rebatching");
2598 }
2599 rebatchAllAlarmsLocked(true);
2600 rescheduleKernelAlarmsLocked();
Adrian Roosc42a1e12014-07-07 23:35:53 +02002601 updateNextAlarmClockLocked();
Adam Lesinski182f73f2013-12-05 16:48:06 -08002602 }
2603 }
2604
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002605 void interactiveStateChangedLocked(boolean interactive) {
2606 if (mInteractive != interactive) {
2607 mInteractive = interactive;
2608 final long nowELAPSED = SystemClock.elapsedRealtime();
2609 if (interactive) {
2610 if (mPendingNonWakeupAlarms.size() > 0) {
2611 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
2612 mTotalDelayTime += thisDelayTime;
2613 if (mMaxDelayTime < thisDelayTime) {
2614 mMaxDelayTime = thisDelayTime;
2615 }
2616 deliverAlarmsLocked(mPendingNonWakeupAlarms, nowELAPSED);
2617 mPendingNonWakeupAlarms.clear();
2618 }
2619 if (mNonInteractiveStartTime > 0) {
2620 long dur = nowELAPSED - mNonInteractiveStartTime;
2621 if (dur > mNonInteractiveTime) {
2622 mNonInteractiveTime = dur;
2623 }
2624 }
2625 } else {
2626 mNonInteractiveStartTime = nowELAPSED;
2627 }
2628 }
2629 }
2630
Adam Lesinski182f73f2013-12-05 16:48:06 -08002631 boolean lookForPackageLocked(String packageName) {
2632 for (int i = 0; i < mAlarmBatches.size(); i++) {
2633 Batch b = mAlarmBatches.get(i);
2634 if (b.hasPackage(packageName)) {
2635 return true;
2636 }
2637 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002638 for (int i = 0; i < mPendingWhileIdleAlarms.size(); i++) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002639 final Alarm a = mPendingWhileIdleAlarms.get(i);
2640 if (a.matches(packageName)) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002641 return true;
2642 }
2643 }
Adam Lesinski182f73f2013-12-05 16:48:06 -08002644 return false;
2645 }
2646
2647 private void setLocked(int type, long when) {
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002648 if (mNativeData != 0) {
Adam Lesinski182f73f2013-12-05 16:48:06 -08002649 // The kernel never triggers alarms with negative wakeup times
2650 // so we ensure they are positive.
2651 long alarmSeconds, alarmNanoseconds;
2652 if (when < 0) {
2653 alarmSeconds = 0;
2654 alarmNanoseconds = 0;
2655 } else {
2656 alarmSeconds = when / 1000;
2657 alarmNanoseconds = (when % 1000) * 1000 * 1000;
2658 }
Kweku Adams61e03292017-10-19 14:27:12 -07002659
Greg Hackmannf1bdbdd2013-12-17 11:56:22 -08002660 set(mNativeData, type, alarmSeconds, alarmNanoseconds);
Adam Lesinski182f73f2013-12-05 16:48:06 -08002661 } else {
2662 Message msg = Message.obtain();
2663 msg.what = ALARM_EVENT;
Kweku Adams61e03292017-10-19 14:27:12 -07002664
Adam Lesinski182f73f2013-12-05 16:48:06 -08002665 mHandler.removeMessages(ALARM_EVENT);
2666 mHandler.sendMessageAtTime(msg, when);
2667 }
2668 }
2669
Dianne Hackborn043fcd92010-10-06 14:27:34 -07002670 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Kweku Adams61e03292017-10-19 14:27:12 -07002671 String prefix, String label, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002672 for (int i=list.size()-1; i>=0; i--) {
2673 Alarm a = list.get(i);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002674 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2675 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002676 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002677 }
2678 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002679
2680 private static final String labelForType(int type) {
2681 switch (type) {
2682 case RTC: return "RTC";
2683 case RTC_WAKEUP : return "RTC_WAKEUP";
2684 case ELAPSED_REALTIME : return "ELAPSED";
2685 case ELAPSED_REALTIME_WAKEUP: return "ELAPSED_WAKEUP";
Christopher Tatee0a22b32013-07-11 14:43:13 -07002686 }
2687 return "--unknown--";
2688 }
2689
2690 private static final void dumpAlarmList(PrintWriter pw, ArrayList<Alarm> list,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002691 String prefix, long nowELAPSED, long nowRTC, SimpleDateFormat sdf) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002692 for (int i=list.size()-1; i>=0; i--) {
2693 Alarm a = list.get(i);
2694 final String label = labelForType(a.type);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002695 pw.print(prefix); pw.print(label); pw.print(" #"); pw.print(i);
2696 pw.print(": "); pw.println(a);
Kweku Adams61e03292017-10-19 14:27:12 -07002697 a.dump(pw, prefix + " ", nowELAPSED, nowRTC, sdf);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002698 }
2699 }
2700
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002701 private boolean isBackgroundRestricted(Alarm alarm) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002702 if (alarm.alarmClock != null) {
2703 // Don't block alarm clocks
2704 return false;
2705 }
2706 if (alarm.operation != null
2707 && (alarm.operation.isActivity() || alarm.operation.isForegroundService())) {
2708 // Don't block starting foreground components
2709 return false;
2710 }
2711 final String sourcePackage =
2712 (alarm.operation != null) ? alarm.operation.getCreatorPackage() : alarm.packageName;
2713 final int sourceUid = alarm.creatorUid;
2714 return mForcedAppStandbyPackages.contains(sourcePackage) && !mForegroundUids.get(sourceUid)
2715 && Arrays.binarySearch(mDeviceIdleUserWhitelist, UserHandle.getAppId(sourceUid))
2716 < 0;
2717 }
2718
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002719 private native long init();
2720 private native void close(long nativeData);
2721 private native void set(long nativeData, int type, long seconds, long nanoseconds);
2722 private native int waitForAlarm(long nativeData);
Greg Hackmann38bf5142014-02-19 16:39:36 -08002723 private native int setKernelTime(long nativeData, long millis);
Greg Hackmanna1d6f922013-12-09 16:56:53 -08002724 private native int setKernelTimezone(long nativeData, int minuteswest);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002725
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002726 boolean triggerAlarmsLocked(ArrayList<Alarm> triggerList, final long nowELAPSED,
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002727 final long nowRTC) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002728 boolean hasWakeup = false;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002729 // batches are temporally sorted, so we need only pull from the
2730 // start of the list until we either empty it or hit a batch
2731 // that is not yet deliverable
Christopher Tate6578ad12013-09-24 17:12:46 -07002732 while (mAlarmBatches.size() > 0) {
2733 Batch batch = mAlarmBatches.get(0);
Christopher Tatee0a22b32013-07-11 14:43:13 -07002734 if (batch.start > nowELAPSED) {
2735 // Everything else is scheduled for the future
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002736 break;
2737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002738
Christopher Tatee0a22b32013-07-11 14:43:13 -07002739 // We will (re)schedule some alarms now; don't let that interfere
2740 // with delivery of this current batch
2741 mAlarmBatches.remove(0);
Dianne Hackborn390517b2013-05-30 15:03:32 -07002742
Christopher Tatee0a22b32013-07-11 14:43:13 -07002743 final int N = batch.size();
2744 for (int i = 0; i < N; i++) {
2745 Alarm alarm = batch.get(i);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002746
2747 if ((alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0) {
2748 // If this is an ALLOW_WHILE_IDLE alarm, we constrain how frequently the app can
2749 // schedule such alarms.
2750 long lastTime = mLastAllowWhileIdleDispatch.get(alarm.uid, 0);
2751 long minTime = lastTime + mAllowWhileIdleMinTime;
2752 if (nowELAPSED < minTime) {
2753 // Whoops, it hasn't been long enough since the last ALLOW_WHILE_IDLE
2754 // alarm went off for this app. Reschedule the alarm to be in the
2755 // correct time period.
2756 alarm.whenElapsed = minTime;
2757 if (alarm.maxWhenElapsed < minTime) {
2758 alarm.maxWhenElapsed = minTime;
2759 }
Dianne Hackbornae78bf82015-10-26 13:33:20 -07002760 if (RECORD_DEVICE_IDLE_ALARMS) {
2761 IdleDispatchEntry ent = new IdleDispatchEntry();
2762 ent.uid = alarm.uid;
2763 ent.pkg = alarm.operation.getCreatorPackage();
2764 ent.tag = alarm.operation.getTag("");
2765 ent.op = "RESCHEDULE";
2766 ent.elapsedRealtime = nowELAPSED;
2767 ent.argRealtime = lastTime;
2768 mAllowWhileIdleDispatches.add(ent);
2769 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002770 setImplLocked(alarm, true, false);
2771 continue;
2772 }
2773 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07002774 if (isBackgroundRestricted(alarm)) {
2775 // Alarms with FLAG_WAKE_FROM_IDLE or mPendingIdleUntil alarm are not deferred
2776 if (DEBUG_BG_LIMIT) {
2777 Slog.d(TAG, "Deferring alarm " + alarm + " due to user forced app standby");
2778 }
2779 ArrayList<Alarm> alarmsForUid = mPendingBackgroundAlarms.get(alarm.creatorUid);
2780 if (alarmsForUid == null) {
2781 alarmsForUid = new ArrayList<>();
2782 mPendingBackgroundAlarms.put(alarm.creatorUid, alarmsForUid);
2783 }
2784 alarmsForUid.add(alarm);
2785 continue;
2786 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002787
Christopher Tatee0a22b32013-07-11 14:43:13 -07002788 alarm.count = 1;
2789 triggerList.add(alarm);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002790 if ((alarm.flags&AlarmManager.FLAG_WAKE_FROM_IDLE) != 0) {
2791 EventLogTags.writeDeviceIdleWakeFromIdle(mPendingIdleUntil != null ? 1 : 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002792 alarm.statsTag);
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002793 }
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002794 if (mPendingIdleUntil == alarm) {
2795 mPendingIdleUntil = null;
2796 rebatchAllAlarmsLocked(false);
2797 restorePendingWhileIdleAlarmsLocked();
2798 }
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002799 if (mNextWakeFromIdle == alarm) {
2800 mNextWakeFromIdle = null;
2801 rebatchAllAlarmsLocked(false);
2802 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002803
2804 // Recurring alarms may have passed several alarm intervals while the
2805 // phone was asleep or off, so pass a trigger count when sending them.
2806 if (alarm.repeatInterval > 0) {
2807 // this adjustment will be zero if we're late by
2808 // less than one full repeat interval
2809 alarm.count += (nowELAPSED - alarm.whenElapsed) / alarm.repeatInterval;
2810
2811 // Also schedule its next recurrence
2812 final long delta = alarm.count * alarm.repeatInterval;
2813 final long nextElapsed = alarm.whenElapsed + delta;
Christopher Tate3e04b472013-10-21 17:51:31 -07002814 setImplLocked(alarm.type, alarm.when + delta, nextElapsed, alarm.windowLength,
Christopher Tatee0a22b32013-07-11 14:43:13 -07002815 maxTriggerTime(nowELAPSED, nextElapsed, alarm.repeatInterval),
Christopher Tate14a7bb02015-10-01 10:24:31 -07002816 alarm.repeatInterval, alarm.operation, null, null, alarm.flags, true,
2817 alarm.workSource, alarm.alarmClock, alarm.uid, alarm.packageName);
Christopher Tate864d42e2014-12-02 11:48:53 -08002818 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002819
Christopher Tate864d42e2014-12-02 11:48:53 -08002820 if (alarm.wakeup) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002821 hasWakeup = true;
2822 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02002823
2824 // We removed an alarm clock. Let the caller recompute the next alarm clock.
2825 if (alarm.alarmClock != null) {
2826 mNextAlarmClockMayChange = true;
2827 }
Dianne Hackborn390517b2013-05-30 15:03:32 -07002828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002829 }
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002830
Christopher Tate1590f1e2014-10-02 17:27:57 -07002831 // This is a new alarm delivery set; bump the sequence number to indicate that
2832 // all apps' alarm delivery classes should be recalculated.
2833 mCurrentSeq++;
2834 calculateDeliveryPriorities(triggerList);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002835 Collections.sort(triggerList, mAlarmDispatchComparator);
2836
2837 if (localLOGV) {
2838 for (int i=0; i<triggerList.size(); i++) {
2839 Slog.v(TAG, "Triggering alarm #" + i + ": " + triggerList.get(i));
2840 }
2841 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002842
2843 return hasWakeup;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002844 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002846 /**
2847 * This Comparator sorts Alarms into increasing time order.
2848 */
2849 public static class IncreasingTimeOrder implements Comparator<Alarm> {
2850 public int compare(Alarm a1, Alarm a2) {
jinho.park1acd32a2015-05-27 14:44:18 +09002851 long when1 = a1.whenElapsed;
2852 long when2 = a2.whenElapsed;
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002853 if (when1 > when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 return 1;
2855 }
Charles Tsaicdaaeee2015-05-20 18:16:48 +08002856 if (when1 < when2) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 return -1;
2858 }
2859 return 0;
2860 }
2861 }
Kweku Adams61e03292017-10-19 14:27:12 -07002862
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002863 private static class Alarm {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002864 public final int type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002865 public final long origWhen;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002866 public final boolean wakeup;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002867 public final PendingIntent operation;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002868 public final IAlarmListener listener;
2869 public final String listenerTag;
2870 public final String statsTag;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002871 public final WorkSource workSource;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002872 public final int flags;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002873 public final AlarmManager.AlarmClockInfo alarmClock;
2874 public final int uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002875 public final int creatorUid;
2876 public final String packageName;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002877 public int count;
2878 public long when;
Christopher Tate3e04b472013-10-21 17:51:31 -07002879 public long windowLength;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002880 public long whenElapsed; // 'when' in the elapsed time base
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002881 public long maxWhenElapsed; // also in the elapsed time base
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002882 public long repeatInterval;
Christopher Tate1590f1e2014-10-02 17:27:57 -07002883 public PriorityClass priorityClass;
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002884
Christopher Tate3e04b472013-10-21 17:51:31 -07002885 public Alarm(int _type, long _when, long _whenElapsed, long _windowLength, long _maxWhen,
Christopher Tate14a7bb02015-10-01 10:24:31 -07002886 long _interval, PendingIntent _op, IAlarmListener _rec, String _listenerTag,
2887 WorkSource _ws, int _flags, AlarmManager.AlarmClockInfo _info,
2888 int _uid, String _pkgName) {
Christopher Tatee0a22b32013-07-11 14:43:13 -07002889 type = _type;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002890 origWhen = _when;
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002891 wakeup = _type == AlarmManager.ELAPSED_REALTIME_WAKEUP
2892 || _type == AlarmManager.RTC_WAKEUP;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002893 when = _when;
2894 whenElapsed = _whenElapsed;
Christopher Tate3e04b472013-10-21 17:51:31 -07002895 windowLength = _windowLength;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002896 maxWhenElapsed = _maxWhen;
Christopher Tatee0a22b32013-07-11 14:43:13 -07002897 repeatInterval = _interval;
2898 operation = _op;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002899 listener = _rec;
2900 listenerTag = _listenerTag;
2901 statsTag = makeTag(_op, _listenerTag, _type);
David Christieebe51fc2013-07-26 13:23:29 -07002902 workSource = _ws;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002903 flags = _flags;
Adrian Roosc42a1e12014-07-07 23:35:53 +02002904 alarmClock = _info;
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002905 uid = _uid;
Christopher Tate14a7bb02015-10-01 10:24:31 -07002906 packageName = _pkgName;
2907
2908 creatorUid = (operation != null) ? operation.getCreatorUid() : uid;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002909 }
Christopher Tatee0a22b32013-07-11 14:43:13 -07002910
Christopher Tate14a7bb02015-10-01 10:24:31 -07002911 public static String makeTag(PendingIntent pi, String tag, int type) {
2912 final String alarmString = type == ELAPSED_REALTIME_WAKEUP || type == RTC_WAKEUP
2913 ? "*walarm*:" : "*alarm*:";
2914 return (pi != null) ? pi.getTag(alarmString) : (alarmString + tag);
2915 }
2916
2917 public WakeupEvent makeWakeupEvent(long nowRTC) {
2918 return new WakeupEvent(nowRTC, creatorUid,
2919 (operation != null)
2920 ? operation.getIntent().getAction()
2921 : ("<listener>:" + listenerTag));
2922 }
2923
2924 // Returns true if either matches
2925 public boolean matches(PendingIntent pi, IAlarmListener rec) {
2926 return (operation != null)
2927 ? operation.equals(pi)
Lorenzo Colitti9b43ce02015-11-22 22:00:08 +09002928 : rec != null && listener.asBinder().equals(rec.asBinder());
Christopher Tate14a7bb02015-10-01 10:24:31 -07002929 }
2930
2931 public boolean matches(String packageName) {
2932 return (operation != null)
2933 ? packageName.equals(operation.getTargetPackage())
2934 : packageName.equals(this.packageName);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002935 }
2936
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002937 @Override
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002938 public String toString() {
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002939 StringBuilder sb = new StringBuilder(128);
2940 sb.append("Alarm{");
2941 sb.append(Integer.toHexString(System.identityHashCode(this)));
2942 sb.append(" type ");
2943 sb.append(type);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08002944 sb.append(" when ");
2945 sb.append(when);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002946 sb.append(" ");
Christopher Tate14a7bb02015-10-01 10:24:31 -07002947 if (operation != null) {
2948 sb.append(operation.getTargetPackage());
2949 } else {
Dianne Hackborn2fefbcf2016-03-18 15:34:54 -07002950 sb.append(packageName);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002951 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002952 sb.append('}');
2953 return sb.toString();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 }
2955
Kweku Adams61e03292017-10-19 14:27:12 -07002956 public void dump(PrintWriter pw, String prefix, long nowELAPSED, long nowRTC,
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002957 SimpleDateFormat sdf) {
2958 final boolean isRtc = (type == RTC || type == RTC_WAKEUP);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002959 pw.print(prefix); pw.print("tag="); pw.println(statsTag);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002960 pw.print(prefix); pw.print("type="); pw.print(type);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002961 pw.print(" whenElapsed="); TimeUtils.formatDuration(whenElapsed,
2962 nowELAPSED, pw);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002963 pw.print(" when=");
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002964 if (isRtc) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002965 pw.print(sdf.format(new Date(when)));
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002966 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07002967 TimeUtils.formatDuration(when, nowELAPSED, pw);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07002968 }
2969 pw.println();
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07002970 pw.print(prefix); pw.print("window="); TimeUtils.formatDuration(windowLength, pw);
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002971 pw.print(" repeatInterval="); pw.print(repeatInterval);
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07002972 pw.print(" count="); pw.print(count);
2973 pw.print(" flags=0x"); pw.println(Integer.toHexString(flags));
Dianne Hackbornf70faed2015-04-21 14:11:38 -07002974 if (alarmClock != null) {
2975 pw.print(prefix); pw.println("Alarm clock:");
2976 pw.print(prefix); pw.print(" triggerTime=");
2977 pw.println(sdf.format(new Date(alarmClock.getTriggerTime())));
2978 pw.print(prefix); pw.print(" showIntent="); pw.println(alarmClock.getShowIntent());
2979 }
Dianne Hackborn1d442e02009-04-20 18:14:05 -07002980 pw.print(prefix); pw.print("operation="); pw.println(operation);
Christopher Tate14a7bb02015-10-01 10:24:31 -07002981 if (listener != null) {
2982 pw.print(prefix); pw.print("listener="); pw.println(listener.asBinder());
2983 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002984 }
Kweku Adams61e03292017-10-19 14:27:12 -07002985
2986 public void writeToProto(ProtoOutputStream proto, long fieldId, long nowElapsed,
2987 long nowRTC) {
2988 final long token = proto.start(fieldId);
2989
2990 proto.write(AlarmProto.TAG, statsTag);
2991 proto.write(AlarmProto.TYPE, type);
2992 proto.write(AlarmProto.WHEN_ELAPSED_MS, whenElapsed - nowElapsed);
2993 proto.write(AlarmProto.WINDOW_LENGTH_MS, windowLength);
2994 proto.write(AlarmProto.REPEAT_INTERVAL_MS, repeatInterval);
2995 proto.write(AlarmProto.COUNT, count);
2996 proto.write(AlarmProto.FLAGS, flags);
2997 if (alarmClock != null) {
2998 alarmClock.writeToProto(proto, AlarmProto.ALARM_CLOCK);
2999 }
3000 if (operation != null) {
3001 operation.writeToProto(proto, AlarmProto.OPERATION);
3002 }
3003 if (listener != null) {
3004 proto.write(AlarmProto.LISTENER, listener.asBinder().toString());
3005 }
3006
3007 proto.end(token);
3008 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003009 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003010
Christopher Tatee0a22b32013-07-11 14:43:13 -07003011 void recordWakeupAlarms(ArrayList<Batch> batches, long nowELAPSED, long nowRTC) {
3012 final int numBatches = batches.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003013 for (int nextBatch = 0; nextBatch < numBatches; nextBatch++) {
3014 Batch b = batches.get(nextBatch);
Christopher Tatee0a22b32013-07-11 14:43:13 -07003015 if (b.start > nowELAPSED) {
Christopher Tate18a75f12013-07-01 18:18:59 -07003016 break;
3017 }
3018
Christopher Tatee0a22b32013-07-11 14:43:13 -07003019 final int numAlarms = b.alarms.size();
Christopher Tatee982faf2013-07-19 14:51:44 -07003020 for (int nextAlarm = 0; nextAlarm < numAlarms; nextAlarm++) {
3021 Alarm a = b.alarms.get(nextAlarm);
Christopher Tate14a7bb02015-10-01 10:24:31 -07003022 mRecentWakeups.add(a.makeWakeupEvent(nowRTC));
Christopher Tatee0a22b32013-07-11 14:43:13 -07003023 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003024 }
3025 }
3026
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003027 long currentNonWakeupFuzzLocked(long nowELAPSED) {
3028 long timeSinceOn = nowELAPSED - mNonInteractiveStartTime;
3029 if (timeSinceOn < 5*60*1000) {
3030 // If the screen has been off for 5 minutes, only delay by at most two minutes.
3031 return 2*60*1000;
3032 } else if (timeSinceOn < 30*60*1000) {
3033 // If the screen has been off for 30 minutes, only delay by at most 15 minutes.
3034 return 15*60*1000;
3035 } else {
3036 // Otherwise, we will delay by at most an hour.
3037 return 60*60*1000;
3038 }
3039 }
3040
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003041 static int fuzzForDuration(long duration) {
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003042 if (duration < 15*60*1000) {
3043 // If the duration until the time is less than 15 minutes, the maximum fuzz
3044 // is the duration.
Dianne Hackbornf70faed2015-04-21 14:11:38 -07003045 return (int)duration;
Dianne Hackborn4870e9d2015-04-08 16:55:47 -07003046 } else if (duration < 90*60*1000) {
3047 // If duration is less than 1 1/2 hours, the maximum fuzz is 15 minutes,
3048 return 15*60*1000;
3049 } else {
3050 // Otherwise, we will fuzz by at most half an hour.
3051 return 30*60*1000;
3052 }
3053 }
3054
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003055 boolean checkAllowNonWakeupDelayLocked(long nowELAPSED) {
3056 if (mInteractive) {
3057 return false;
3058 }
3059 if (mLastAlarmDeliveryTime <= 0) {
3060 return false;
3061 }
minho.choo649acab2014-12-12 16:13:55 +09003062 if (mPendingNonWakeupAlarms.size() > 0 && mNextNonWakeupDeliveryTime < nowELAPSED) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003063 // This is just a little paranoia, if somehow we have pending non-wakeup alarms
3064 // and the next delivery time is in the past, then just deliver them all. This
3065 // avoids bugs where we get stuck in a loop trying to poll for alarms.
3066 return false;
3067 }
3068 long timeSinceLast = nowELAPSED - mLastAlarmDeliveryTime;
3069 return timeSinceLast <= currentNonWakeupFuzzLocked(nowELAPSED);
3070 }
3071
3072 void deliverAlarmsLocked(ArrayList<Alarm> triggerList, long nowELAPSED) {
3073 mLastAlarmDeliveryTime = nowELAPSED;
3074 for (int i=0; i<triggerList.size(); i++) {
3075 Alarm alarm = triggerList.get(i);
Dianne Hackborna750a632015-06-16 17:18:23 -07003076 final boolean allowWhileIdle = (alarm.flags&AlarmManager.FLAG_ALLOW_WHILE_IDLE) != 0;
Tim Murray175c0f92017-11-28 15:01:04 -08003077 if (alarm.wakeup) {
3078 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch wakeup alarm to " + alarm.packageName);
3079 } else {
3080 Trace.traceBegin(Trace.TRACE_TAG_POWER, "Dispatch non-wakeup alarm to " + alarm.packageName);
3081 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003082 try {
Christopher Tate2ff5a732014-09-18 13:47:57 -07003083 if (localLOGV) {
3084 Slog.v(TAG, "sending alarm " + alarm);
3085 }
Dianne Hackborn1e383822015-04-10 14:02:33 -07003086 if (RECORD_ALARMS_IN_HISTORY) {
3087 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3088 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003089 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003090 alarm.operation, alarm.workSource.get(wi), alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003091 }
3092 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003093 ActivityManager.noteAlarmStart(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003094 alarm.operation, alarm.uid, alarm.statsTag);
Dianne Hackborn1e383822015-04-10 14:02:33 -07003095 }
3096 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003097 mDeliveryTracker.deliverLocked(alarm, nowELAPSED, allowWhileIdle);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003098 } catch (RuntimeException e) {
3099 Slog.w(TAG, "Failure sending alarm.", e);
3100 }
Tim Murray175c0f92017-11-28 15:01:04 -08003101 Trace.traceEnd(Trace.TRACE_TAG_POWER);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003102 }
3103 }
3104
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003105 private class AlarmThread extends Thread
3106 {
3107 public AlarmThread()
3108 {
3109 super("AlarmManager");
3110 }
Kweku Adams61e03292017-10-19 14:27:12 -07003111
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003112 public void run()
3113 {
Dianne Hackborn390517b2013-05-30 15:03:32 -07003114 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3115
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003116 while (true)
3117 {
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003118 int result = waitForAlarm(mNativeData);
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003119 mLastWakeup = SystemClock.elapsedRealtime();
Dianne Hackborn390517b2013-05-30 15:03:32 -07003120
3121 triggerList.clear();
3122
Dianne Hackbornc3527222015-05-13 14:03:20 -07003123 final long nowRTC = System.currentTimeMillis();
3124 final long nowELAPSED = SystemClock.elapsedRealtime();
3125
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003126 if ((result & TIME_CHANGED_MASK) != 0) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003127 // The kernel can give us spurious time change notifications due to
3128 // small adjustments it makes internally; we want to filter those out.
3129 final long lastTimeChangeClockTime;
3130 final long expectedClockTime;
Dianne Hackborn998e6082014-09-11 19:13:23 -07003131 synchronized (mLock) {
Dianne Hackbornc3527222015-05-13 14:03:20 -07003132 lastTimeChangeClockTime = mLastTimeChangeClockTime;
3133 expectedClockTime = lastTimeChangeClockTime
3134 + (nowELAPSED - mLastTimeChangeRealtime);
Dianne Hackborn998e6082014-09-11 19:13:23 -07003135 }
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003136 if (lastTimeChangeClockTime == 0 || nowRTC < (expectedClockTime-1000)
3137 || nowRTC > (expectedClockTime+1000)) {
3138 // The change is by at least +/- 1000 ms (or this is the first change),
Dianne Hackbornc3527222015-05-13 14:03:20 -07003139 // let's do it!
3140 if (DEBUG_BATCH) {
3141 Slog.v(TAG, "Time changed notification from kernel; rebatching");
3142 }
3143 removeImpl(mTimeTickSender);
Christopher Tatecf024712016-08-05 13:21:45 -07003144 removeImpl(mDateChangeSender);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003145 rebatchAllAlarms();
3146 mClockReceiver.scheduleTimeTickEvent();
Christopher Tatecf024712016-08-05 13:21:45 -07003147 mClockReceiver.scheduleDateChangedEvent();
Dianne Hackbornc3527222015-05-13 14:03:20 -07003148 synchronized (mLock) {
3149 mNumTimeChanged++;
3150 mLastTimeChangeClockTime = nowRTC;
3151 mLastTimeChangeRealtime = nowELAPSED;
3152 }
3153 Intent intent = new Intent(Intent.ACTION_TIME_CHANGED);
3154 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING
Christopher Tate2b6e459e2017-02-17 14:33:52 -08003155 | Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT
Chad Brubaker291df4f2017-03-14 10:23:02 -07003156 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
3157 | Intent.FLAG_RECEIVER_VISIBLE_TO_INSTANT_APPS);
Dianne Hackbornc3527222015-05-13 14:03:20 -07003158 getContext().sendBroadcastAsUser(intent, UserHandle.ALL);
3159
3160 // The world has changed on us, so we need to re-evaluate alarms
3161 // regardless of whether the kernel has told us one went off.
3162 result |= IS_WAKEUP_MASK;
3163 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003164 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003165
Dianne Hackbornc3527222015-05-13 14:03:20 -07003166 if (result != TIME_CHANGED_MASK) {
3167 // If this was anything besides just a time change, then figure what if
3168 // anything to do about alarms.
3169 synchronized (mLock) {
3170 if (localLOGV) Slog.v(
3171 TAG, "Checking for alarms... rtc=" + nowRTC
3172 + ", elapsed=" + nowELAPSED);
Christopher Tate18a75f12013-07-01 18:18:59 -07003173
Dianne Hackbornc3527222015-05-13 14:03:20 -07003174 if (WAKEUP_STATS) {
3175 if ((result & IS_WAKEUP_MASK) != 0) {
3176 long newEarliest = nowRTC - RECENT_WAKEUP_PERIOD;
3177 int n = 0;
3178 for (WakeupEvent event : mRecentWakeups) {
3179 if (event.when > newEarliest) break;
3180 n++; // number of now-stale entries at the list head
3181 }
3182 for (int i = 0; i < n; i++) {
3183 mRecentWakeups.remove();
3184 }
Christopher Tate18a75f12013-07-01 18:18:59 -07003185
Dianne Hackbornc3527222015-05-13 14:03:20 -07003186 recordWakeupAlarms(mAlarmBatches, nowELAPSED, nowRTC);
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003187 }
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003188 }
Dianne Hackbornc3527222015-05-13 14:03:20 -07003189
3190 boolean hasWakeup = triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3191 if (!hasWakeup && checkAllowNonWakeupDelayLocked(nowELAPSED)) {
3192 // if there are no wakeup alarms and the screen is off, we can
3193 // delay what we have so far until the future.
3194 if (mPendingNonWakeupAlarms.size() == 0) {
3195 mStartCurrentDelayTime = nowELAPSED;
3196 mNextNonWakeupDeliveryTime = nowELAPSED
3197 + ((currentNonWakeupFuzzLocked(nowELAPSED)*3)/2);
3198 }
3199 mPendingNonWakeupAlarms.addAll(triggerList);
3200 mNumDelayedAlarms += triggerList.size();
3201 rescheduleKernelAlarmsLocked();
3202 updateNextAlarmClockLocked();
3203 } else {
3204 // now deliver the alarm intents; if there are pending non-wakeup
3205 // alarms, we need to merge them in to the list. note we don't
3206 // just deliver them first because we generally want non-wakeup
3207 // alarms delivered after wakeup alarms.
3208 rescheduleKernelAlarmsLocked();
3209 updateNextAlarmClockLocked();
3210 if (mPendingNonWakeupAlarms.size() > 0) {
3211 calculateDeliveryPriorities(mPendingNonWakeupAlarms);
3212 triggerList.addAll(mPendingNonWakeupAlarms);
3213 Collections.sort(triggerList, mAlarmDispatchComparator);
3214 final long thisDelayTime = nowELAPSED - mStartCurrentDelayTime;
3215 mTotalDelayTime += thisDelayTime;
3216 if (mMaxDelayTime < thisDelayTime) {
3217 mMaxDelayTime = thisDelayTime;
3218 }
3219 mPendingNonWakeupAlarms.clear();
3220 }
3221 deliverAlarmsLocked(triggerList, nowELAPSED);
3222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003223 }
Dianne Hackbornaa9a59d2016-05-23 15:59:18 -07003224
3225 } else {
3226 // Just in case -- even though no wakeup flag was set, make sure
3227 // we have updated the kernel to the next alarm time.
Christopher Tate7b5b7cb2016-07-07 14:41:36 -07003228 synchronized (mLock) {
3229 rescheduleKernelAlarmsLocked();
3230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003231 }
3232 }
3233 }
3234 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003235
David Christieebe51fc2013-07-26 13:23:29 -07003236 /**
3237 * Attribute blame for a WakeLock.
3238 * @param pi PendingIntent to attribute blame to if ws is null.
3239 * @param ws WorkSource to attribute blame.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003240 * @param knownUid attribution uid; < 0 if we need to derive it from the PendingIntent sender
David Christieebe51fc2013-07-26 13:23:29 -07003241 */
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003242 void setWakelockWorkSource(PendingIntent pi, WorkSource ws, int type, String tag,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003243 int knownUid, boolean first) {
Christopher Tatec4a07d12012-04-06 14:19:13 -07003244 try {
Dianne Hackborna1bd7922014-03-21 11:07:11 -07003245 final boolean unimportant = pi == mTimeTickSender;
3246 mWakeLock.setUnimportantForLogging(unimportant);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003247 if (first || mLastWakeLockUnimportantForLogging) {
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003248 mWakeLock.setHistoryTag(tag);
Dianne Hackborn4590e522014-03-24 13:36:46 -07003249 } else {
3250 mWakeLock.setHistoryTag(null);
3251 }
3252 mLastWakeLockUnimportantForLogging = unimportant;
David Christieebe51fc2013-07-26 13:23:29 -07003253 if (ws != null) {
3254 mWakeLock.setWorkSource(ws);
3255 return;
3256 }
3257
Christopher Tate14a7bb02015-10-01 10:24:31 -07003258 final int uid = (knownUid >= 0)
3259 ? knownUid
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003260 : ActivityManager.getService().getUidForIntentSender(pi.getTarget());
Christopher Tatec4a07d12012-04-06 14:19:13 -07003261 if (uid >= 0) {
3262 mWakeLock.setWorkSource(new WorkSource(uid));
3263 return;
3264 }
3265 } catch (Exception e) {
3266 }
3267
3268 // Something went wrong; fall back to attributing the lock to the OS
3269 mWakeLock.setWorkSource(null);
3270 }
3271
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003272 private class AlarmHandler extends Handler {
3273 public static final int ALARM_EVENT = 1;
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003274 public static final int SEND_NEXT_ALARM_CLOCK_CHANGED = 2;
3275 public static final int LISTENER_TIMEOUT = 3;
3276 public static final int REPORT_ALARMS_ACTIVE = 4;
Kweku Adams61e03292017-10-19 14:27:12 -07003277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003278 public AlarmHandler() {
3279 }
Kweku Adams61e03292017-10-19 14:27:12 -07003280
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003281 public void handleMessage(Message msg) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003282 switch (msg.what) {
3283 case ALARM_EVENT: {
3284 ArrayList<Alarm> triggerList = new ArrayList<Alarm>();
3285 synchronized (mLock) {
3286 final long nowRTC = System.currentTimeMillis();
3287 final long nowELAPSED = SystemClock.elapsedRealtime();
3288 triggerAlarmsLocked(triggerList, nowELAPSED, nowRTC);
3289 updateNextAlarmClockLocked();
3290 }
Adrian Roosc42a1e12014-07-07 23:35:53 +02003291
Christopher Tate14a7bb02015-10-01 10:24:31 -07003292 // now trigger the alarms without the lock held
3293 for (int i=0; i<triggerList.size(); i++) {
3294 Alarm alarm = triggerList.get(i);
3295 try {
3296 alarm.operation.send();
3297 } catch (PendingIntent.CanceledException e) {
3298 if (alarm.repeatInterval > 0) {
3299 // This IntentSender is no longer valid, but this
3300 // is a repeating alarm, so toss the hoser.
3301 removeImpl(alarm.operation);
3302 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003303 }
3304 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003305 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003306 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003307
3308 case SEND_NEXT_ALARM_CLOCK_CHANGED:
3309 sendNextAlarmClockChanged();
3310 break;
3311
3312 case LISTENER_TIMEOUT:
3313 mDeliveryTracker.alarmTimedOut((IBinder) msg.obj);
3314 break;
3315
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003316 case REPORT_ALARMS_ACTIVE:
3317 if (mLocalDeviceIdleController != null) {
3318 mLocalDeviceIdleController.setAlarmsActive(msg.arg1 != 0);
3319 }
3320 break;
3321
Christopher Tate14a7bb02015-10-01 10:24:31 -07003322 default:
3323 // nope, just ignore it
3324 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003325 }
3326 }
3327 }
Kweku Adams61e03292017-10-19 14:27:12 -07003328
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003329 class ClockReceiver extends BroadcastReceiver {
3330 public ClockReceiver() {
3331 IntentFilter filter = new IntentFilter();
3332 filter.addAction(Intent.ACTION_TIME_TICK);
3333 filter.addAction(Intent.ACTION_DATE_CHANGED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003334 getContext().registerReceiver(this, filter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003335 }
Kweku Adams61e03292017-10-19 14:27:12 -07003336
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003337 @Override
3338 public void onReceive(Context context, Intent intent) {
3339 if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
Christopher Tate385e4982013-07-23 18:22:29 -07003340 if (DEBUG_BATCH) {
3341 Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
3342 }
3343 scheduleTimeTickEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003344 } else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
3345 // Since the kernel does not keep track of DST, we need to
3346 // reset the TZ information at the beginning of each day
3347 // based off of the current Zone gmt offset + userspace tracked
3348 // daylight savings information.
3349 TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
Lavettacn Xiaoc84cc4f2010-08-30 12:47:23 +02003350 int gmtOffset = zone.getOffset(System.currentTimeMillis());
Greg Hackmanna1d6f922013-12-09 16:56:53 -08003351 setKernelTimezone(mNativeData, -(gmtOffset / 60000));
Christopher Tate385e4982013-07-23 18:22:29 -07003352 scheduleDateChangedEvent();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003353 }
3354 }
Kweku Adams61e03292017-10-19 14:27:12 -07003355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003356 public void scheduleTimeTickEvent() {
Paul Westbrook51608a52011-08-25 13:18:54 -07003357 final long currentTime = System.currentTimeMillis();
Sungmin Choi563914a2013-01-10 17:28:40 +09003358 final long nextTime = 60000 * ((currentTime / 60000) + 1);
Paul Westbrook51608a52011-08-25 13:18:54 -07003359
3360 // Schedule this event for the amount of time that it would take to get to
3361 // the top of the next minute.
Sungmin Choi563914a2013-01-10 17:28:40 +09003362 final long tickEventDelay = nextTime - currentTime;
Paul Westbrook51608a52011-08-25 13:18:54 -07003363
David Christieebe51fc2013-07-26 13:23:29 -07003364 final WorkSource workSource = null; // Let system take blame for time tick events.
Adam Lesinski182f73f2013-12-05 16:48:06 -08003365 setImpl(ELAPSED_REALTIME, SystemClock.elapsedRealtime() + tickEventDelay, 0,
Christopher Tate14a7bb02015-10-01 10:24:31 -07003366 0, mTimeTickSender, null, null, AlarmManager.FLAG_STANDALONE, workSource,
3367 null, Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003368 }
Christopher Tate385e4982013-07-23 18:22:29 -07003369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003370 public void scheduleDateChangedEvent() {
3371 Calendar calendar = Calendar.getInstance();
3372 calendar.setTimeInMillis(System.currentTimeMillis());
Christopher Tateafa8b982016-08-10 16:15:48 -07003373 calendar.set(Calendar.HOUR_OF_DAY, 0);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003374 calendar.set(Calendar.MINUTE, 0);
3375 calendar.set(Calendar.SECOND, 0);
3376 calendar.set(Calendar.MILLISECOND, 0);
3377 calendar.add(Calendar.DAY_OF_MONTH, 1);
David Christieebe51fc2013-07-26 13:23:29 -07003378
3379 final WorkSource workSource = null; // Let system take blame for date change events.
Christopher Tate14a7bb02015-10-01 10:24:31 -07003380 setImpl(RTC, calendar.getTimeInMillis(), 0, 0, mDateChangeSender, null, null,
3381 AlarmManager.FLAG_STANDALONE, workSource, null,
3382 Process.myUid(), "android");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003383 }
3384 }
Kweku Adams61e03292017-10-19 14:27:12 -07003385
Dianne Hackbornd4e6d462014-05-16 16:32:37 -07003386 class InteractiveStateReceiver extends BroadcastReceiver {
3387 public InteractiveStateReceiver() {
3388 IntentFilter filter = new IntentFilter();
3389 filter.addAction(Intent.ACTION_SCREEN_OFF);
3390 filter.addAction(Intent.ACTION_SCREEN_ON);
3391 filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
3392 getContext().registerReceiver(this, filter);
3393 }
3394
3395 @Override
3396 public void onReceive(Context context, Intent intent) {
3397 synchronized (mLock) {
3398 interactiveStateChangedLocked(Intent.ACTION_SCREEN_ON.equals(intent.getAction()));
3399 }
3400 }
3401 }
3402
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003403 class UninstallReceiver extends BroadcastReceiver {
3404 public UninstallReceiver() {
3405 IntentFilter filter = new IntentFilter();
3406 filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
3407 filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003408 filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003409 filter.addDataScheme("package");
Adam Lesinski182f73f2013-12-05 16:48:06 -08003410 getContext().registerReceiver(this, filter);
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003411 // Register for events related to sdcard installation.
3412 IntentFilter sdFilter = new IntentFilter();
Suchi Amalapurapub56ae202010-02-04 22:51:07 -08003413 sdFilter.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003414 sdFilter.addAction(Intent.ACTION_USER_STOPPED);
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003415 sdFilter.addAction(Intent.ACTION_UID_REMOVED);
Adam Lesinski182f73f2013-12-05 16:48:06 -08003416 getContext().registerReceiver(this, sdFilter);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003417 }
Kweku Adams61e03292017-10-19 14:27:12 -07003418
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003419 @Override
3420 public void onReceive(Context context, Intent intent) {
3421 synchronized (mLock) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003422 String action = intent.getAction();
3423 String pkgList[] = null;
Dianne Hackborn21f1bd12010-02-19 17:02:21 -08003424 if (Intent.ACTION_QUERY_PACKAGE_RESTART.equals(action)) {
3425 pkgList = intent.getStringArrayExtra(Intent.EXTRA_PACKAGES);
3426 for (String packageName : pkgList) {
3427 if (lookForPackageLocked(packageName)) {
3428 setResultCode(Activity.RESULT_OK);
3429 return;
3430 }
3431 }
3432 return;
3433 } else if (Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE.equals(action)) {
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003434 pkgList = intent.getStringArrayExtra(Intent.EXTRA_CHANGED_PACKAGE_LIST);
Dianne Hackborn80a4af22012-08-27 19:18:31 -07003435 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
3436 int userHandle = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, -1);
3437 if (userHandle >= 0) {
3438 removeUserLocked(userHandle);
3439 }
Dianne Hackborn3d1933c42015-06-10 16:25:57 -07003440 } else if (Intent.ACTION_UID_REMOVED.equals(action)) {
3441 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
3442 if (uid >= 0) {
3443 mLastAllowWhileIdleDispatch.delete(uid);
3444 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003445 } else {
Dianne Hackborn409578f2010-03-10 17:23:43 -08003446 if (Intent.ACTION_PACKAGE_REMOVED.equals(action)
3447 && intent.getBooleanExtra(Intent.EXTRA_REPLACING, false)) {
3448 // This package is being updated; don't kill its alarms.
3449 return;
3450 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003451 Uri data = intent.getData();
3452 if (data != null) {
3453 String pkg = data.getSchemeSpecificPart();
3454 if (pkg != null) {
3455 pkgList = new String[]{pkg};
3456 }
3457 }
3458 }
3459 if (pkgList != null && (pkgList.length > 0)) {
3460 for (String pkg : pkgList) {
3461 removeLocked(pkg);
Christopher Tate1590f1e2014-10-02 17:27:57 -07003462 mPriorities.remove(pkg);
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003463 for (int i=mBroadcastStats.size()-1; i>=0; i--) {
3464 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.valueAt(i);
3465 if (uidStats.remove(pkg) != null) {
3466 if (uidStats.size() <= 0) {
3467 mBroadcastStats.removeAt(i);
3468 }
3469 }
3470 }
Suchi Amalapurapu08675a32010-01-28 09:57:30 -08003471 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003472 }
3473 }
3474 }
3475 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003476
3477 final class UidObserver extends IUidObserver.Stub {
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003478 @Override public void onUidStateChanged(int uid, int procState, long procStateSeq) {
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003479 }
3480
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003481 @Override public void onUidGone(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003482 synchronized (mLock) {
3483 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003484 removeForStoppedLocked(uid);
3485 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003486 mForegroundUids.delete(uid);
Dianne Hackborne07641d2016-11-09 15:07:23 -08003487 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003488 }
3489
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003490 @Override public void onUidActive(int uid) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003491 synchronized (mLock) {
3492 if (!mForegroundUids.get(uid)) {
3493 mForegroundUids.put(uid, true);
3494 sendPendingBackgroundAlarmsLocked(uid, null);
3495 }
3496 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003497 }
3498
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003499 @Override public void onUidIdle(int uid, boolean disabled) {
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003500 synchronized (mLock) {
3501 if (disabled) {
Dianne Hackborne07641d2016-11-09 15:07:23 -08003502 removeForStoppedLocked(uid);
3503 }
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003504 mForegroundUids.delete(uid);
Dianne Hackbornde9c48b2015-11-20 14:49:59 -08003505 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003506 }
Dianne Hackborn3e99f652017-07-05 16:33:56 -07003507
3508 @Override public void onUidCachedChanged(int uid, boolean cached) {
3509 }
Dianne Hackbornbef28fe2015-10-29 17:57:11 -07003510 };
3511
Suprabh Shukladb6bf662017-08-30 15:41:53 -07003512 private final class AppOpsWatcher extends IAppOpsCallback.Stub {
3513 @Override
3514 public void opChanged(int op, int uid, String packageName) throws RemoteException {
3515 synchronized (mLock) {
3516 final int mode = mAppOpsService.checkOperation(op, uid, packageName);
3517 if (DEBUG_BG_LIMIT) {
3518 Slog.d(TAG,
3519 "Appop changed for " + uid + ", " + packageName + " to " + mode);
3520 }
3521 final boolean changed;
3522 if (mode != AppOpsManager.MODE_ALLOWED) {
3523 changed = mForcedAppStandbyPackages.add(packageName);
3524 } else {
3525 changed = mForcedAppStandbyPackages.remove(packageName);
3526 }
3527 if (changed && mode == AppOpsManager.MODE_ALLOWED) {
3528 sendPendingBackgroundAlarmsLocked(uid, packageName);
3529 }
3530 }
3531 }
3532 }
3533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003534 private final BroadcastStats getStatsLocked(PendingIntent pi) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003535 String pkg = pi.getCreatorPackage();
3536 int uid = pi.getCreatorUid();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003537 return getStatsLocked(uid, pkg);
3538 }
3539
3540 private final BroadcastStats getStatsLocked(int uid, String pkgName) {
Dianne Hackborn3d658bf2014-02-05 13:38:56 -08003541 ArrayMap<String, BroadcastStats> uidStats = mBroadcastStats.get(uid);
3542 if (uidStats == null) {
3543 uidStats = new ArrayMap<String, BroadcastStats>();
3544 mBroadcastStats.put(uid, uidStats);
3545 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003546 BroadcastStats bs = uidStats.get(pkgName);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003547 if (bs == null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003548 bs = new BroadcastStats(uid, pkgName);
3549 uidStats.put(pkgName, bs);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003550 }
3551 return bs;
3552 }
Dianne Hackborn81038902012-11-26 17:04:09 -08003553
Christopher Tate21e9f192017-08-08 13:49:11 -07003554 /**
3555 * Canonical count of (operation.send() - onSendFinished()) and
3556 * listener send/complete/timeout invocations.
3557 * Guarded by the usual lock.
3558 */
3559 @GuardedBy("mLock")
3560 private int mSendCount = 0;
3561 @GuardedBy("mLock")
Christopher Tateeabba732017-08-17 17:12:52 -07003562 private int mSendFinishCount = 0;
3563 @GuardedBy("mLock")
Christopher Tate21e9f192017-08-08 13:49:11 -07003564 private int mListenerCount = 0;
Christopher Tateeabba732017-08-17 17:12:52 -07003565 @GuardedBy("mLock")
3566 private int mListenerFinishCount = 0;
Christopher Tate21e9f192017-08-08 13:49:11 -07003567
Christopher Tate14a7bb02015-10-01 10:24:31 -07003568 class DeliveryTracker extends IAlarmCompleteListener.Stub implements PendingIntent.OnFinished {
Christopher Tate21e9f192017-08-08 13:49:11 -07003569
Christopher Tate14a7bb02015-10-01 10:24:31 -07003570 private InFlight removeLocked(PendingIntent pi, Intent intent) {
3571 for (int i = 0; i < mInFlight.size(); i++) {
Christopher Tatedb9ae422017-08-21 11:24:30 -07003572 if (mInFlight.get(i).mPendingIntent == pi) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003573 return mInFlight.remove(i);
3574 }
3575 }
3576 mLog.w("No in-flight alarm for " + pi + " " + intent);
3577 return null;
3578 }
3579
3580 private InFlight removeLocked(IBinder listener) {
3581 for (int i = 0; i < mInFlight.size(); i++) {
3582 if (mInFlight.get(i).mListener == listener) {
3583 return mInFlight.remove(i);
3584 }
3585 }
3586 mLog.w("No in-flight alarm for listener " + listener);
3587 return null;
3588 }
3589
3590 private void updateStatsLocked(InFlight inflight) {
3591 final long nowELAPSED = SystemClock.elapsedRealtime();
3592 BroadcastStats bs = inflight.mBroadcastStats;
3593 bs.nesting--;
3594 if (bs.nesting <= 0) {
3595 bs.nesting = 0;
3596 bs.aggregateTime += nowELAPSED - bs.startTime;
3597 }
3598 FilterStats fs = inflight.mFilterStats;
3599 fs.nesting--;
3600 if (fs.nesting <= 0) {
3601 fs.nesting = 0;
3602 fs.aggregateTime += nowELAPSED - fs.startTime;
3603 }
3604 if (RECORD_ALARMS_IN_HISTORY) {
3605 if (inflight.mWorkSource != null && inflight.mWorkSource.size() > 0) {
3606 for (int wi=0; wi<inflight.mWorkSource.size(); wi++) {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003607 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003608 inflight.mPendingIntent, inflight.mWorkSource.get(wi), inflight.mTag);
3609 }
3610 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003611 ActivityManager.noteAlarmFinish(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003612 inflight.mPendingIntent, inflight.mUid, inflight.mTag);
3613 }
3614 }
3615 }
3616
3617 private void updateTrackingLocked(InFlight inflight) {
3618 if (inflight != null) {
3619 updateStatsLocked(inflight);
3620 }
3621 mBroadcastRefCount--;
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003622 if (DEBUG_WAKELOCK) {
3623 Slog.d(TAG, "mBroadcastRefCount -> " + mBroadcastRefCount);
3624 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003625 if (mBroadcastRefCount == 0) {
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003626 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 0).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003627 mWakeLock.release();
3628 if (mInFlight.size() > 0) {
3629 mLog.w("Finished all dispatches with " + mInFlight.size()
3630 + " remaining inflights");
3631 for (int i=0; i<mInFlight.size(); i++) {
3632 mLog.w(" Remaining #" + i + ": " + mInFlight.get(i));
3633 }
3634 mInFlight.clear();
3635 }
3636 } else {
3637 // the next of our alarms is now in flight. reattribute the wakelock.
3638 if (mInFlight.size() > 0) {
3639 InFlight inFlight = mInFlight.get(0);
3640 setWakelockWorkSource(inFlight.mPendingIntent, inFlight.mWorkSource,
3641 inFlight.mAlarmType, inFlight.mTag, -1, false);
3642 } else {
3643 // should never happen
3644 mLog.w("Alarm wakelock still held but sent queue empty");
3645 mWakeLock.setWorkSource(null);
3646 }
3647 }
3648 }
3649
3650 /**
3651 * Callback that arrives when a direct-call alarm reports that delivery has finished
3652 */
3653 @Override
3654 public void alarmComplete(IBinder who) {
3655 if (who == null) {
Christopher Tate21e9f192017-08-08 13:49:11 -07003656 mLog.w("Invalid alarmComplete: uid=" + Binder.getCallingUid()
Christopher Tate14a7bb02015-10-01 10:24:31 -07003657 + " pid=" + Binder.getCallingPid());
3658 return;
3659 }
3660
3661 final long ident = Binder.clearCallingIdentity();
3662 try {
3663 synchronized (mLock) {
3664 mHandler.removeMessages(AlarmHandler.LISTENER_TIMEOUT, who);
3665 InFlight inflight = removeLocked(who);
3666 if (inflight != null) {
3667 if (DEBUG_LISTENER_CALLBACK) {
3668 Slog.i(TAG, "alarmComplete() from " + who);
3669 }
3670 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003671 mListenerFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003672 } else {
3673 // Delivery timed out, and the timeout handling already took care of
3674 // updating our tracking here, so we needn't do anything further.
3675 if (DEBUG_LISTENER_CALLBACK) {
3676 Slog.i(TAG, "Late alarmComplete() from " + who);
3677 }
3678 }
3679 }
3680 } finally {
3681 Binder.restoreCallingIdentity(ident);
3682 }
3683 }
3684
3685 /**
3686 * Callback that arrives when a PendingIntent alarm has finished delivery
3687 */
3688 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003689 public void onSendFinished(PendingIntent pi, Intent intent, int resultCode,
3690 String resultData, Bundle resultExtras) {
3691 synchronized (mLock) {
Christopher Tateeabba732017-08-17 17:12:52 -07003692 mSendFinishCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003693 updateTrackingLocked(removeLocked(pi, intent));
3694 }
3695 }
3696
3697 /**
3698 * Timeout of a direct-call alarm delivery
3699 */
3700 public void alarmTimedOut(IBinder who) {
3701 synchronized (mLock) {
3702 InFlight inflight = removeLocked(who);
Dianne Hackborn81038902012-11-26 17:04:09 -08003703 if (inflight != null) {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003704 // TODO: implement ANR policy for the target
3705 if (DEBUG_LISTENER_CALLBACK) {
3706 Slog.i(TAG, "Alarm listener " + who + " timed out in delivery");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003707 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003708 updateTrackingLocked(inflight);
Christopher Tateeabba732017-08-17 17:12:52 -07003709 mListenerFinishCount++;
Dianne Hackborn81038902012-11-26 17:04:09 -08003710 } else {
Christopher Tate14a7bb02015-10-01 10:24:31 -07003711 if (DEBUG_LISTENER_CALLBACK) {
3712 Slog.i(TAG, "Spurious timeout of listener " + who);
3713 }
Christopher Tate21e9f192017-08-08 13:49:11 -07003714 mLog.w("Spurious timeout of listener " + who);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003715 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003716 }
3717 }
3718
3719 /**
3720 * Deliver an alarm and set up the post-delivery handling appropriately
3721 */
3722 public void deliverLocked(Alarm alarm, long nowELAPSED, boolean allowWhileIdle) {
3723 if (alarm.operation != null) {
3724 // PendingIntent alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003725 mSendCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003726 try {
3727 alarm.operation.send(getContext(), 0,
3728 mBackgroundIntent.putExtra(
3729 Intent.EXTRA_ALARM_COUNT, alarm.count),
3730 mDeliveryTracker, mHandler, null,
3731 allowWhileIdle ? mIdleOptions : null);
3732 } catch (PendingIntent.CanceledException e) {
3733 if (alarm.repeatInterval > 0) {
3734 // This IntentSender is no longer valid, but this
3735 // is a repeating alarm, so toss it
3736 removeImpl(alarm.operation);
3737 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003738 // No actual delivery was possible, so the delivery tracker's
3739 // 'finished' callback won't be invoked. We also don't need
3740 // to do any wakelock or stats tracking, so we have nothing
3741 // left to do here but go on to the next thing.
Christopher Tateeabba732017-08-17 17:12:52 -07003742 mSendFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003743 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003744 }
3745 } else {
3746 // Direct listener callback alarm
Christopher Tate21e9f192017-08-08 13:49:11 -07003747 mListenerCount++;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003748 try {
3749 if (DEBUG_LISTENER_CALLBACK) {
3750 Slog.v(TAG, "Alarm to uid=" + alarm.uid
3751 + " listener=" + alarm.listener.asBinder());
3752 }
3753 alarm.listener.doAlarm(this);
3754 mHandler.sendMessageDelayed(
3755 mHandler.obtainMessage(AlarmHandler.LISTENER_TIMEOUT,
3756 alarm.listener.asBinder()),
3757 mConstants.LISTENER_TIMEOUT);
3758 } catch (Exception e) {
3759 if (DEBUG_LISTENER_CALLBACK) {
3760 Slog.i(TAG, "Alarm undeliverable to listener "
3761 + alarm.listener.asBinder(), e);
3762 }
Christopher Tate7f2a0352015-12-08 10:24:33 -08003763 // As in the PendingIntent.CanceledException case, delivery of the
3764 // alarm was not possible, so we have no wakelock or timeout or
3765 // stats management to do. It threw before we posted the delayed
3766 // timeout message, so we're done here.
Christopher Tateeabba732017-08-17 17:12:52 -07003767 mListenerFinishCount++;
Christopher Tate7f2a0352015-12-08 10:24:33 -08003768 return;
Christopher Tate14a7bb02015-10-01 10:24:31 -07003769 }
3770 }
3771
3772 // The alarm is now in flight; now arrange wakelock and stats tracking
Makoto Onuki3e7d8452017-03-02 15:33:17 -08003773 if (DEBUG_WAKELOCK) {
3774 Slog.d(TAG, "mBroadcastRefCount -> " + (mBroadcastRefCount + 1));
3775 }
Christopher Tate14a7bb02015-10-01 10:24:31 -07003776 if (mBroadcastRefCount == 0) {
3777 setWakelockWorkSource(alarm.operation, alarm.workSource,
3778 alarm.type, alarm.statsTag, (alarm.operation == null) ? alarm.uid : -1,
3779 true);
3780 mWakeLock.acquire();
Dianne Hackborn627dfa12015-11-11 18:10:30 -08003781 mHandler.obtainMessage(AlarmHandler.REPORT_ALARMS_ACTIVE, 1).sendToTarget();
Christopher Tate14a7bb02015-10-01 10:24:31 -07003782 }
3783 final InFlight inflight = new InFlight(AlarmManagerService.this,
3784 alarm.operation, alarm.listener, alarm.workSource, alarm.uid,
3785 alarm.packageName, alarm.type, alarm.statsTag, nowELAPSED);
3786 mInFlight.add(inflight);
3787 mBroadcastRefCount++;
3788
3789 if (allowWhileIdle) {
3790 // Record the last time this uid handled an ALLOW_WHILE_IDLE alarm.
3791 mLastAllowWhileIdleDispatch.put(alarm.uid, nowELAPSED);
3792 if (RECORD_DEVICE_IDLE_ALARMS) {
3793 IdleDispatchEntry ent = new IdleDispatchEntry();
3794 ent.uid = alarm.uid;
3795 ent.pkg = alarm.packageName;
3796 ent.tag = alarm.statsTag;
3797 ent.op = "DELIVER";
3798 ent.elapsedRealtime = nowELAPSED;
3799 mAllowWhileIdleDispatches.add(ent);
3800 }
3801 }
3802
3803 final BroadcastStats bs = inflight.mBroadcastStats;
3804 bs.count++;
3805 if (bs.nesting == 0) {
3806 bs.nesting = 1;
3807 bs.startTime = nowELAPSED;
3808 } else {
3809 bs.nesting++;
3810 }
3811 final FilterStats fs = inflight.mFilterStats;
3812 fs.count++;
3813 if (fs.nesting == 0) {
3814 fs.nesting = 1;
3815 fs.startTime = nowELAPSED;
3816 } else {
3817 fs.nesting++;
3818 }
3819 if (alarm.type == ELAPSED_REALTIME_WAKEUP
3820 || alarm.type == RTC_WAKEUP) {
3821 bs.numWakeup++;
3822 fs.numWakeup++;
3823 if (alarm.workSource != null && alarm.workSource.size() > 0) {
3824 for (int wi=0; wi<alarm.workSource.size(); wi++) {
Christopher Tate0029f572016-06-14 10:16:28 -07003825 final String wsName = alarm.workSource.getName(wi);
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003826 ActivityManager.noteWakeupAlarm(
Christopher Tate14a7bb02015-10-01 10:24:31 -07003827 alarm.operation, alarm.workSource.get(wi),
Christopher Tate0029f572016-06-14 10:16:28 -07003828 (wsName != null) ? wsName : alarm.packageName,
3829 alarm.statsTag);
Dianne Hackborn81038902012-11-26 17:04:09 -08003830 }
Christopher Tatec4a07d12012-04-06 14:19:13 -07003831 } else {
Sudheer Shankadc589ac2016-11-10 15:30:17 -08003832 ActivityManager.noteWakeupAlarm(
Joe Onorato78bcdf92016-05-09 10:10:29 -07003833 alarm.operation, alarm.uid, alarm.packageName, alarm.statsTag);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003834 }
3835 }
3836 }
3837 }
3838}